focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
static int getConfigValueAsInt(ServiceConfiguration conf, String configProp, int defaultValue) { Object value = conf.getProperty(configProp); if (value instanceof Integer) { log.info("Configuration for [{}] is [{}]", configProp, value); return (Integer) value; } else if (...
@Test public void testGetConfigValueAsIntegerWorks() { Properties props = new Properties(); props.setProperty("prop1", "1234"); ServiceConfiguration config = new ServiceConfiguration(); config.setProperties(props); int actual = ConfigUtils.getConfigValueAsInt(config, "prop1",...
public static String humanReadableByteCountSI(long bytes) { if (-1000 < bytes && bytes < 1000) { if (bytes == 1) { return bytes + " byte"; } return bytes + " bytes"; } CharacterIterator ci = new StringCharacterIterator("kMGTPE"); while (bytes <= -999_950 || bytes >= 999_950) { ...
@Test public void humanReadableByteCountSI_returns_kbs() { assertThat(FileUtils.humanReadableByteCountSI(1_234)).isEqualTo("1.2 kB"); assertThat(FileUtils.humanReadableByteCountSI(1_000)).isEqualTo("1.0 kB"); assertThat(FileUtils.humanReadableByteCountSI(9_999)).isEqualTo("10.0 kB"); assertThat(FileUt...
public static Parser parser() { return ParserImpl.INSTANCE; }
@Test void testReaderInputValidation() { assertThrows(NullPointerException.class, new Executable() { @Override public void execute() throws IOException { HostsFileEntriesProvider.parser().parse((Reader) null); } }); }
@Override public String getMediaType() { return mediaType; }
@Test public void getMediaType() { underTest.setMediaType("JSON"); assertThat(underTest.getMediaType()).isEqualTo("JSON"); }
public static List<AclEntry> replaceAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); // Replacement is done separately for eac...
@Test public void testReplaceAclEntriesAccessMaskCalculated() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, OTHER, READ)) .build(); List<AclEntry> aclSpec...
@Override protected PolarisRegistration getManagementRegistration() { return null; }
@Test public void testGetManagementRegistration() { assertThat(polarisAutoServiceRegistration.getManagementRegistration()).isNull(); }
public void validateUrl(String serverUrl) { HttpUrl url = buildUrl(serverUrl, "/rest/api/1.0/repos"); doGet("", url, body -> buildGson().fromJson(body, RepositoryList.class)); }
@Test public void validate_url_success() { server.enqueue(new MockResponse().setResponseCode(200) .setBody(REPOS_BODY)); underTest.validateUrl(server.url("/").toString()); }
@Override public Column convert(BasicTypeDefine typeDefine) { Long typeDefineLength = typeDefine.getLength(); PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.get...
@Test public void testConvertTinyint() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("tinyint") .dataType("tinyint") .build(); Column column = ...
@Override public String toString() { String t = map2String(tags); return measurement + (t.length() > 0? "," + t : "") + " value=" + value + " " + timestamp; }
@Test public void testToString() { Map<String, String> tags = new LinkedHashMap<>(); tags.put("key1", "value1"); tags.put("key2", "value2"); tags.put("key3", "value3"); InfluxDbPoint point = new InfluxDbPoint("counter", tags, 1234567890, "123"); Assert.assertEquals("c...
public boolean matches(Evidence evidence) { return sourceMatches(evidence) && confidenceMatches(evidence) && name.equalsIgnoreCase(evidence.getName()) && valueMatches(evidence); }
@Test public void testExactMatching() throws Exception { final EvidenceMatcher exactMatcherHighest = new EvidenceMatcher("source", "name", "value", false, Confidence.HIGHEST); assertTrue("exact matcher should match EVIDENCE_HIGHEST", exactMatcherHighest.matches(EVIDENCE_HIGHEST)); assertFals...
@Override public boolean addAll(Collection<? extends E> c) { for (E e : c) { add(e); } return true; }
@Test(expected = IllegalStateException.class) public void testAddAll_whenOverCapacity_thenThrowException() { queue.addAll(asList(1, 2, 3, 4, 5, 6)); }
public void createOrUpdate(final String key, final String value, final CreateMode mode) { String val = StringUtils.isEmpty(value) ? "" : value; try { client.create().orSetData().creatingParentsIfNeeded().withMode(mode).forPath(key, val.getBytes(StandardCharsets.UTF_8)); } catch (Exce...
@Test void createOrUpdate() throws Exception { assertThrows(ShenyuException.class, () -> client.createOrUpdate("/test", "hello", CreateMode.PERSISTENT)); CreateBuilder createBuilder = mock(CreateBuilder.class); when(curatorFramework.create()).thenReturn(createBuilder); ...
public BlobStoreFile write(String key, boolean create) throws IOException { return new HdfsBlobStoreFile(getKeyDir(key), true, create, hadoopConf); }
@Test public void testGetFileLength() throws Exception { Map<String, Object> conf = new HashMap<>(); String validKey = "validkeyBasic"; String testString = "testingblob"; try (TestHdfsBlobStoreImpl hbs = new TestHdfsBlobStoreImpl(blobDir, conf, DFS_CLUSTER_EXTENSION.getHadoopConf()))...
@Nonnull public static String checkHasText(String argument, String errorMessage) { if (argument == null || argument.isEmpty()) { throw new IllegalArgumentException(errorMessage); } return argument; }
@Test public void checkHasText() { checkHasText(null, false); checkHasText("", false); checkHasText("foobar", true); }
public static PostgreSQLCommandPacket newInstance(final PostgreSQLCommandPacketType commandPacketType, final PostgreSQLPacketPayload payload) { if (!PostgreSQLCommandPacketType.isExtendedProtocolPacketType(commandPacketType)) { payload.getByteBuf().skipBytes(1); return getPostgreSQLComma...
@Test void assertNewInstanceWithExecuteComPacket() { assertThat(PostgreSQLCommandPacketFactory.newInstance(PostgreSQLCommandPacketType.EXECUTE_COMMAND, payload), instanceOf(PostgreSQLAggregatedCommandPacket.class)); }
public void setIncludedCipherSuites(String cipherSuites) { this.includedCipherSuites = cipherSuites; }
@Test public void testSetIncludedCipherSuites() throws Exception { configurable.setSupportedCipherSuites(new String[] { "A", "B", "C", "D" }); configuration.setIncludedCipherSuites("A,B ,C, D"); configuration.configure(configurable); assertTrue(Arrays.equals(new String[] { "A", "B", ...
public boolean isVisibleBySelectedOptionIds(Collection<Long> selectedOptionIds) { return visibleType == VisibleType.ALWAYS || selectedOptionIds.contains(onSelectedOptionId); }
@Test void 조건_옵션을_선택하면_섹션이_보인다() { // given Section section = new Section(VisibleType.CONDITIONAL, List.of(), 1L, "섹션명", "말머리", 1); // when boolean actual = section.isVisibleBySelectedOptionIds(List.of(1L, 2L, 3L)); // then assertThat(actual).isTrue(); }
@Override public KeyValues getLowCardinalityKeyValues(DubboServerContext context) { return super.getLowCardinalityKeyValues(context.getInvocation()); }
@Test void testGetLowCardinalityKeyValues() throws NoSuchFieldException, IllegalAccessException { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("testMethod"); invocation.setAttachment("interface", "com.example.TestService"); invocation.setTargetServiceUniqu...
public void removeAll() { lastKey = null; firstKey = null; rows.clear(); }
@Test public void testRemoveAll() { Table table = new Table(TWO_COLUMN_TABLE); assertFalse(table.removeAt(ROW_1)); table.put(1, ROW_1); table.put(2, ROW_2); table.put(3, ROW_3); table.removeAll(); assertEquals(0, table.count()); }
@Override public FilteredMessage apply(Message msg) { try (var ignored = executionTime.time()) { return doApply(msg); } }
@Test void applyWithNoFilterAndOneDestination(MessageFactory messageFactory) { final var filter = createFilter(Map.of(), Set.of("indexer")); final var message = messageFactory.createMessage("msg", "src", Tools.nowUTC()); message.addStream(defaultStream); final var filteredMessage = ...
public static boolean isTimecodeLink(String link) { return link != null && link.matches(TIMECODE_LINK_REGEX.pattern()); }
@Test public void testIsTimecodeLink() { assertFalse(ShownotesCleaner.isTimecodeLink(null)); assertFalse(ShownotesCleaner.isTimecodeLink("http://antennapod/timecode/123123")); assertFalse(ShownotesCleaner.isTimecodeLink("antennapod://timecode/")); assertFalse(ShownotesCleaner.isTimec...
public static PostgreSQLErrorResponsePacket newInstance(final Exception cause) { Optional<ServerErrorMessage> serverErrorMessage = findServerErrorMessage(cause); return serverErrorMessage.map(PostgreSQLErrorPacketFactory::createErrorResponsePacket) .orElseGet(() -> createErrorResponsePac...
@Test void assertPSQLExceptionWithServerErrorMessageNotNull() throws ReflectiveOperationException { ServerErrorMessage serverErrorMessage = mock(ServerErrorMessage.class); when(serverErrorMessage.getSeverity()).thenReturn(PostgreSQLMessageSeverityLevel.FATAL); when(serverErrorMessage.getSQLS...
public KsqlEntityList execute( final KsqlSecurityContext securityContext, final List<ParsedStatement> statements, final SessionProperties sessionProperties ) { final KsqlEntityList entities = new KsqlEntityList(); for (final ParsedStatement parsed : statements) { final PreparedStatemen...
@Test public void shouldDefaultToDistributor() { // Given givenRequestHandler(ImmutableMap.of()); // When final List<ParsedStatement> statements = KSQL_PARSER.parse(SOME_STREAM_SQL); final KsqlEntityList entities = handler.execute(securityContext, statements, sessionProperties); // Then ...
public static boolean get(String path, Map<String, String> headers) { HttpURLConnection conn = null; try { URL url = new java.net.URL(path); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(2)); conn.setReadTimeout(...
@Test public void testGet() { assertThat(OkHttpUtil.get("http://localhost:" + port + "/test", Maps.newHashMap("key", "value"))).isTrue(); assertThat(OkHttpUtil.checkUrl("localhost", port, "/test", Maps.newHashMap("key", "value"))).isTrue(); assertThat(OkHttpUtil.checkUrl("localhost", port, "test", Maps.newHashMa...
@Override public UserCredentials findByActivateToken(TenantId tenantId, String activateToken) { return DaoUtil.getData(userCredentialsRepository.findByActivateToken(activateToken)); }
@Test public void testFindByActivateToken() { UserCredentials foundedUserCredentials = userCredentialsDao.findByActivateToken(SYSTEM_TENANT_ID, ACTIVATE_TOKEN); assertNotNull(foundedUserCredentials); assertEquals(neededUserCredentials.getId(), foundedUserCredentials.getId()); }
public CompletableFuture<Void> clearUsernameHash(final Account account) { if (account.getUsernameHash().isEmpty()) { // no username to clear return CompletableFuture.completedFuture(null); } final byte[] usernameHash = account.getUsernameHash().get(); final Timer.Sample sample = Timer.start(...
@Test void testClearUsernameNoUsername() { final Account account = generateAccount("+18005551234", UUID.randomUUID(), UUID.randomUUID()); createAccount(account); assertThatNoException().isThrownBy(() -> accounts.clearUsernameHash(account).join()); }
@Private public void scheduleAllReduces() { for (ContainerRequest req : pendingReduces) { scheduledRequests.addReduce(req); } pendingReduces.clear(); }
@Test public void testUnsupportedReduceContainerRequirement() throws Exception { final Resource maxContainerSupported = Resource.newInstance(1, 1); final ApplicationId appId = ApplicationId.newInstance(1, 1); final ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance( appId, 1); ...
@Override public Map<String, Object> getVariables() { final Map<String, Object> collectedVariables = new HashMap<>(); if (parent != null) { collectedVariables.putAll(parent.getVariables()); } variables.forEach(collectedVariables::put); return collectedVariables; ...
@Test public void testGetVariables() { ProcessContextImpl context = new ProcessContextImpl(); ProcessContextImpl parentContext = new ProcessContextImpl(); parentContext.setVariable("key", "value"); context.setParent(parentContext); Assertions.assertEquals(1, context.getVariab...
@Override public boolean verifyClient(DistroClientVerifyInfo verifyData) { String clientId = verifyData.getClientId(); IpPortBasedClient client = clients.get(clientId); if (null != client) { // remote node of old version will always verify with zero revision if (0 == ...
@Test void testVerifyClient0() { assertTrue(ephemeralIpPortClientManager.verifyClient(new DistroClientVerifyInfo(ephemeralIpPortId, 0))); assertTrue(ephemeralIpPortClientManager.verifyClient(new DistroClientVerifyInfo(syncedClientId, 0))); }
NettyPartitionRequestClient createPartitionRequestClient(ConnectionID connectionId) throws IOException, InterruptedException { // We map the input ConnectionID to a new value to restrict the number of tcp connections connectionId = new ConnectionID( co...
@TestTemplate void testNettyClientConnectRetry() throws Exception { NettyTestUtil.NettyServerAndClient serverAndClient = createNettyServerAndClient(); UnstableNettyClient unstableNettyClient = new UnstableNettyClient(serverAndClient.client(), 2); PartitionRequestClientFactor...
public Lease acquire() throws Exception { String path = internals.attemptLock(-1, null, null); return makeLease(path); }
@Test public void testSimple2() throws Exception { final int MAX_LEASES = 3; Timing timing = new Timing(); List<Lease> leases = Lists.newArrayList(); CuratorFramework client = CuratorFrameworkFactory.newClient( server.getConnectString(), timing.session(), timing.conn...
protected CompletableFuture<Triple<MessageExt, String, Boolean>> getMessageFromRemoteAsync(String topic, long offset, int queueId, String brokerName) { try { String brokerAddr = this.brokerController.getTopicRouteInfoManager().findBrokerAddressInSubscribe(brokerName, MixAll.MASTER_ID, false); ...
@Test public void getMessageFromRemoteAsyncTest_message_found() throws Exception { PullResult pullResult = new PullResult(PullStatus.FOUND, 1, 1, 1, Arrays.asList(new MessageExt())); when(brokerOuterAPI.pullMessageFromSpecificBrokerAsync(anyString(), anyString(), anyString(), anyString(), anyInt(), ...
public void removeMapping(String name, boolean ifExists) { if (relationsStorage.removeMapping(name) != null) { listeners.forEach(TableListener::onTableChanged); } else if (!ifExists) { throw QueryException.error("Mapping does not exist: " + name); } }
@Test public void when_removesNonExistingMappingWithIfExists_then_succeeds() { // given String name = "name"; given(relationsStorage.removeMapping(name)).willReturn(null); // when // then catalog.removeMapping(name, true); verifyNoInteractions(listener); ...
@Override public String select(String text) { return selectGroup(text).get(group); }
@Test public void testRegexWithZeroWidthAssertions() { String regex = "^.*(?=\\?)(?!\\?yy)"; String source = "hello world?xx?yy"; RegexSelector regexSelector = new RegexSelector(regex); String select = regexSelector.select(source); Assertions.assertThat(select).isEqualTo("hel...
public abstract byte[] encode(MutableSpan input);
@Test void span_shared_JSON_V2() { MutableSpan span = clientSpan; span.kind(Kind.SERVER); span.setShared(); assertThat(new String(encoder.encode(clientSpan), UTF_8)) .isEqualTo( "{\"traceId\":\"7180c278b62e8f6a216a2aea45d08fc9\",\"parentId\":\"6b221d5bc9e6496c\",\"id\":\"5b4185666d5...
public static GraphQLRequestParams toGraphQLRequestParams(byte[] postData, final String contentEncoding) throws JsonProcessingException, UnsupportedEncodingException { final String encoding = StringUtils.isNotEmpty(contentEncoding) ? contentEncoding : EncoderCache.URL_ARGUMENT_ENCODI...
@Test void testToGraphQLRequestParamsWithPostData() throws Exception { GraphQLRequestParams params = GraphQLRequestParamUtils .toGraphQLRequestParams(EXPECTED_POST_BODY.getBytes(StandardCharsets.UTF_8), null); assertNull(params.getOperationName()); assertEquals(QUERY.trim(), ...
public static String buildEventSignature(String methodSignature) { byte[] input = methodSignature.getBytes(); byte[] hash = Hash.sha3(input); return Numeric.toHexString(hash); }
@Test public void testBuildEventSignature() { assertEquals( EventEncoder.buildEventSignature("Deposit(address,hash256,uint256)"), ("0x50cb9fe53daa9737b786ab3646f04d0150dc50ef4e75f59509d83667ad5adb20")); assertEquals( EventEncoder.buildEventSignature("...
public void eval(Object... args) throws HiveException { // When the parameter is (Integer, Array[Double]), Flink calls udf.eval(Integer, // Array[Double]), which is not a problem. // But when the parameter is a single array, Flink calls udf.eval(Array[Double]), // at this point java's v...
@Test public void testStruct() throws Exception { Object[] constantArgs = new Object[] {null}; DataType[] dataTypes = new DataType[] { DataTypes.ARRAY( DataTypes.ROW( DataTypes.FIELD("1", DataTypes.I...
@Override public void showPreviewForKey( Keyboard.Key key, Drawable icon, View parentView, PreviewPopupTheme previewPopupTheme) { KeyPreview popup = getPopupForKey(key, parentView, previewPopupTheme); Point previewPosition = mPositionCalculator.calculatePositionForPreview( key, previ...
@Test public void testNoPopupForNoPreview() { KeyPreviewsManager underTest = new KeyPreviewsManager(getApplicationContext(), mPositionCalculator, 3); PopupWindow createdPopupWindow = getLatestCreatedPopupWindow(); Assert.assertNull(createdPopupWindow); mTestKeys[0].showPreview = false; u...
static void manageMissingValues(final KiePMMLMiningField miningField, final PMMLRequestData requestData) { MISSING_VALUE_TREATMENT_METHOD missingValueTreatmentMethod = miningField.getMissingValueTreatmentMethod() != null ? miningField.getMissingValueTreatmentMethod() ...
@Test void manageMissingValuesReturnInvalid() { assertThatExceptionOfType(KiePMMLException.class).isThrownBy(() -> { KiePMMLMiningField miningField = KiePMMLMiningField.builder("FIELD", null) .withDataType(DATA_TYPE.STRING) .withMissingValueTreatmentMethod...
CreateConnectorRequest parseConnectorConfigurationFile(String filePath) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); File connectorConfigurationFile = Paths.get(filePath).toFile(); try { Map<String, String> connectorConfigs = objectMapper.readValue( ...
@Test public void testParseJsonFileWithCreateConnectorRequestWithUnknownField() throws Exception { Map<String, Object> requestToWrite = new HashMap<>(); requestToWrite.put("name", CONNECTOR_NAME); requestToWrite.put("config", CONNECTOR_CONFIG); requestToWrite.put("unknown-field", "ra...
public void decode(ByteBuf buffer) { boolean last; int statusCode; while (true) { switch(state) { case READ_COMMON_HEADER: if (buffer.readableBytes() < SPDY_HEADER_SIZE) { return; } ...
@Test public void testSpdySettingsPersistedValues() throws Exception { short type = 4; byte flags = 0; int numSettings = 1; int length = 8 * numSettings + 4; byte idFlags = 0x02; // FLAG_SETTINGS_PERSISTED int id = RANDOM.nextInt() & 0x00FFFFFF; int value = RA...
@Override public Object handle(String targetService, List<Object> invokers, Object invocation, Map<String, String> queryMap, String serviceInterface) { if (!shouldHandle(invokers)) { return invokers; } List<Object> result = getTargetInvokersByRules(invokers, targetSe...
@Test public void testGetTargetInvokerByTagRulesWithPolicySceneOne() { // initialize the routing rule RuleInitializationUtils.initAZTagMatchTriggerThresholdPolicyRule(); List<Object> invokers = new ArrayList<>(); ApacheInvoker<Object> invoker1 = new ApacheInvoker<>("1.0.0", "az1"); ...
public static Blob string2blob(String str) { if (str == null) { return null; } try { return new SerialBlob(str.getBytes(Constants.DEFAULT_CHARSET)); } catch (Exception e) { throw new ShouldNeverHappenException(e); } }
@Test public void testString2blob() throws SQLException { assertNull(BlobUtils.string2blob(null)); assertThat(BlobUtils.string2blob("123abc")).isEqualTo( new SerialBlob("123abc".getBytes(Constants.DEFAULT_CHARSET))); }
public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); List<AclEntry> foundAclSpecEntries = ...
@Test public void testMergeAclEntriesDefaultMaskCalculated() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(ACCESS, USER, ALL)) .add(aclEntry(ACCESS, GROUP, READ)) .add(aclEntry(ACCESS, OTHER, READ)) .add(aclEntry(DEFAULT, USER, ALL)) ...
static void populateEvaluateNode(final JavaParserDTO toPopulate, final NodeNamesDTO nodeNamesDTO, final List<Field<?>> fields, final boolean isRoot) { String nodeClassName = nodeNamesDTO.nodeClassName;...
@Test void populateEvaluateNode() { final String packageName = "packageName"; // empty node boolean isRoot = false; KiePMMLNodeFactory.NodeNamesDTO nodeNamesDTO = new KiePMMLNodeFactory.NodeNamesDTO(nodeLeaf, createNodeClassName(), "PARENTNODECLASS", ...
public static boolean isP2PKH(Script script) { List<ScriptChunk> chunks = script.chunks(); if (chunks.size() != 5) return false; if (!chunks.get(0).equalsOpCode(OP_DUP)) return false; if (!chunks.get(1).equalsOpCode(OP_HASH160)) return false; b...
@Test public void testCreateP2PKHOutputScript() { assertTrue(ScriptPattern.isP2PKH( ScriptBuilder.createP2PKHOutputScript(keys.get(0)) )); }
public static String toJson(SnapshotRef ref) { return toJson(ref, false); }
@Test public void testBranchToJsonAllFields() { String json = "{\"snapshot-id\":1,\"type\":\"branch\",\"min-snapshots-to-keep\":2," + "\"max-snapshot-age-ms\":3,\"max-ref-age-ms\":4}"; SnapshotRef ref = SnapshotRef.branchBuilder(1L) .minSnapshotsToKeep(2) .m...
@Override public List<PartitionKey> getPrunedPartitions(Table table, ScalarOperator predicate, long limit, TableVersionRange version) { IcebergTable icebergTable = (IcebergTable) table; String dbName = icebergTable.getRemoteDbName(); String tableName = icebergTable.getRemoteTableName(); ...
@Test public void testDateDayPartitionPrune() { IcebergHiveCatalog icebergHiveCatalog = new IcebergHiveCatalog(CATALOG_NAME, new Configuration(), DEFAULT_CONFIG); List<Column> columns = Lists.newArrayList(new Column("k1", INT), new Column("dt", DATE)); IcebergMetadata metadata = new IcebergM...
public Optional<Measure> toMeasure(@Nullable ScannerReport.Measure batchMeasure, Metric metric) { Objects.requireNonNull(metric); if (batchMeasure == null) { return Optional.empty(); } Measure.NewMeasureBuilder builder = Measure.newMeasureBuilder(); switch (metric.getType().getValueType()) { ...
@Test public void toMeasure_returns_no_value_if_dto_has_no_string_value_for_LEVEL_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_BATCH_MEASURE, SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); }
public HollowHashIndexResult findMatches(Object... query) { if (hashStateVolatile == null) { throw new IllegalStateException(this + " wasn't initialized"); } int hashCode = 0; for(int i=0;i<query.length;i++) { if(query[i] == null) throw new Illega...
@Test public void testIndexingReferenceTypeFieldWithNullValues() throws Exception { mapper.add(new TypeC(null)); mapper.add(new TypeC(new TypeD(null))); mapper.add(new TypeC(new TypeD("one"))); roundTripSnapshot(); HollowHashIndex index = new HollowHashIndex(readStateEngine,...
@Override public void start() { File dbHome = new File(getRequiredSetting(PATH_DATA.getKey())); if (!dbHome.exists()) { dbHome.mkdirs(); } startServer(dbHome); }
@Test public void start_creates_db_and_adds_tcp_listener() throws IOException { int port = NetworkUtilsImpl.INSTANCE.getNextLoopbackAvailablePort(); settings .setProperty(PATH_DATA.getKey(), temporaryFolder.newFolder().getAbsolutePath()) .setProperty(JDBC_URL.getKey(), "jdbc url") .setProper...
public static <K, N, V, S extends State> InternalKvState<K, N, ?> createStateAndWrapWithLatencyTrackingIfEnabled( InternalKvState<K, N, ?> kvState, StateDescriptor<S, V> stateDescriptor, LatencyTrackingStateConfig latencyTrackingStateConfig) ...
@TestTemplate @SuppressWarnings("unchecked") <K, N> void testTrackValueState() throws Exception { InternalValueState<K, N, String> valueState = mock(InternalValueState.class); ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("value", String.class); ...
@Override public QualityGate findEffectiveQualityGate(Project project) { return findQualityGate(project).orElseGet(this::findDefaultQualityGate); }
@Test public void findDefaultQualityGate_by_property_found() { QualityGateDto qualityGateDto = new QualityGateDto(); qualityGateDto.setUuid(QUALITY_GATE_DTO.getUuid()); qualityGateDto.setName(QUALITY_GATE_DTO.getName()); when(qualityGateDao.selectDefault(any())).thenReturn(qualityGateDto); when(q...
@Override public double logp(int k) { if (k < Math.max(0, m + n - N) || k > Math.min(m, n)) { return Double.NEGATIVE_INFINITY; } else { return lchoose(m, k) + lchoose(N - m, n - k) - lchoose(N, n); } }
@Test public void testLogP() { System.out.println("logP"); HyperGeometricDistribution instance = new HyperGeometricDistribution(100, 30, 70); instance.rand(); assertEquals(Math.log(3.404564e-26), instance.logp(0), 1E-5); assertEquals(Math.log(7.149584e-23), instance.logp(1), ...
public static Payload convert(Request request, RequestMeta meta) { //meta. Payload.Builder payloadBuilder = Payload.newBuilder(); Metadata.Builder metaBuilder = Metadata.newBuilder(); if (meta != null) { metaBuilder.putAllHeaders(request.getHeaders()).setType(request.getClass...
@Test void testConvertResponse() { Payload convert = GrpcUtils.convert(response); assertEquals(response.getClass().getSimpleName(), convert.getMetadata().getType()); }
public Optional<Measure> toMeasure(@Nullable ScannerReport.Measure batchMeasure, Metric metric) { Objects.requireNonNull(metric); if (batchMeasure == null) { return Optional.empty(); } Measure.NewMeasureBuilder builder = Measure.newMeasureBuilder(); switch (metric.getType().getValueType()) { ...
@Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Boolean_metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_BATCH_MEASURE, SOME_BOOLEAN_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); }
@InvokeOnHeader(Web3jConstants.ETH_GET_CODE) void ethGetCode(Message message) throws IOException { DefaultBlockParameter atBlock = toDefaultBlockParameter(message.getHeader(Web3jConstants.AT_BLOCK, configuration::getAtBlock, String.class)); String address = message.getHeader(Web3jCon...
@Test public void ethGetCodeTest() throws Exception { EthGetCode response = Mockito.mock(EthGetCode.class); Mockito.when(mockWeb3j.ethGetCode(any(), any())).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.getCode()).thenReturn("test"); ...
public static void ensureMarkFileLink(final File serviceDir, final File actualFile, final String linkFilename) { final String serviceDirPath; final String markFileParentPath; try { serviceDirPath = serviceDir.getCanonicalPath(); } catch (final IOException...
@Test void shouldCreateLinkFileIfFileInDifferentLocation() throws IOException { final String linkFilename = "markfile.lnk"; final File markFileLocation = new File(alternativeDirectory, "markfile.dat"); MarkFile.ensureMarkFileLink(serviceDirectory, markFileLocation, linkFilename); ...
public static void main(String args[]) { BaseBarSeriesBuilder barSeriesBuilder = new BaseBarSeriesBuilder(); BarSeries seriesD = barSeriesBuilder.withName("Sample Series Double ") .withNumTypeOf(DoubleNum::valueOf) .build(); BarSeries seriesP = barSeriesBuilder...
@Test public void test() { CompareNumTypes.main(null); }
@Override public int compareTo(final ComparableWrapper other) { if (!Objects.equals(type, Type.NORMAL) || !Objects.equals(other.type, Type.NORMAL)) { return type.compareTo(other.type); } else { Comparator<Comparable> nullFirstCompare = Comparator.nullsFirst(Comparable::compa...
@Test void compareTo() { assertThat(theNull.compareTo(theNull)).isEqualTo(0); assertThat(one.compareTo(one)).isEqualTo(0); assertThat(ten.compareTo(ten)).isEqualTo(0); assertThat(min.compareTo(min)).isEqualTo(0); assertThat(max.compareTo(max)).isEqualTo(0); assertTha...
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } MessageSubject that = (MessageSubject) obj; retur...
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(subject1, sameAsSubject1) .addEqualityGroup(subject2) .addEqualityGroup(subject3) .testEquals(); }
public static boolean isReserved(final String token) { final SqlBaseLexer sqlBaseLexer = new SqlBaseLexer( new CaseInsensitiveStream(CharStreams.fromString(token))); final CommonTokenStream tokenStream = new CommonTokenStream(sqlBaseLexer); final SqlBaseParser sqlBaseParser = new SqlBaseParser(...
@Test public void shouldNotBeReserved() { // Given: final String[] keywords = new String[]{ "source", // non-reserved keyword "sink", // non-reserved keyword "MAP", //upper case "Array", //case insensitive ...
@Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { MainSettingsActivity mainSettingsActivity = (MainSettingsActivity) getActivity(); if (mainSettingsActivity == null) return super.onOptionsItemSelected(item); if (item.getItemId() == R.id.add_user_word) { createEmptyItemForAdd()...
@Test public void testTwiceAddNewWordFromMenuAtEmptyState() { UserDictionaryEditorFragment fragment = startEditorFragment(); RecyclerView wordsRecyclerView = fragment.getView().findViewById(R.id.words_recycler_view); Assert.assertNotNull(wordsRecyclerView); Assert.assertEquals(1 /*empty view*/, words...
public Quantity<U> add(Quantity<U> second) { if(unit == second.unit) return new Quantity<U>(value + second.value, unit); else { final double sum = value + second.in(unit).value; return new Quantity<U>(sum, unit); } }
@Test public void addQuantitiesInSameUnits() throws Exception { Quantity<Metrics> first = new Quantity<Metrics>(1, Metrics.m); Quantity<Metrics> second = new Quantity<Metrics>(2, Metrics.m); assertThat(first.add(second)).isEqualTo(new Quantity<Metrics>(3, Metrics.m)); }
public void runExtractor(Message msg) { try(final Timer.Context ignored = completeTimer.time()) { final String field; try (final Timer.Context ignored2 = conditionTimer.time()) { // We can only work on Strings. if (!(msg.getField(sourceField) instanceof St...
@Test public void testConvertersWithNonStringFieldValue() throws Exception { final Converter converter = new TestConverter.Builder() .callback(new Function<Object, Object>() { @Nullable @Override public Object apply(Object input) { ...
public static <T> T instantiateClassDefConstructor(Class<T> clazz) { //if constructor present then it should have a no arg constructor //if not present then default constructor is already their Objects.requireNonNull(clazz, "class to instantiate should not be null"); if (clazz.getConstru...
@Test public void shouldInstantiateClassWithDefaultConstructor2() { assertThat(ClassUtils.instantiateClassDefConstructor(DefaultConstructor2.class)).isNotNull(); }
@Override public boolean match(String attributeValue) { if (attributeValue == null) { return false; } switch (type) { case Equals: return attributeValue.equals(value); case StartsWith: return (length == -1 || length == attributeValue.length()) && ...
@Test public void testDegeneratedContains() { LikeCondition likeCondition = new LikeCondition("%ab%"); assertTrue(likeCondition.match("ab")); assertTrue(likeCondition.match("xabxx")); assertFalse(likeCondition.match("axb")); }
@Override public DescriptiveUrlBag toUrl(final Path file) { final DescriptiveUrlBag list = new DescriptiveUrlBag(); list.add(new DescriptiveUrl(this.toUrl(file, distribution.getOrigin()), DescriptiveUrl.Type.origin, MessageFormat.format(LocaleFactory.localizedString("{0} {1} URL"), ...
@Test public void testDownload() { final Distribution distribution = new Distribution(Distribution.DOWNLOAD, "n", URI.create("https://test.cyberduck.ch.s3.amazonaws.com"), true); final DescriptiveUrl url = new DistributionUrlProvider(distribution).toUrl( new Path("/test.cyberduck.ch/p/f"...
@Override public void stopConnector(final String connName, final Callback<Void> callback) { log.trace("Submitting request to transition connector {} to STOPPED state", connName); addRequest( () -> { if (!configState.contains(connName)) thr...
@Test public void testStopConnector() throws Exception { when(herder.connectorType(anyMap())).thenReturn(ConnectorType.SOURCE); when(member.memberId()).thenReturn("leader"); when(member.currentProtocolVersion()).thenReturn(CONNECT_PROTOCOL_V0); // join as leader expectRebala...
@Override public boolean isTrusted(Address address) { if (address == null) { return false; } if (trustedInterfaces.isEmpty()) { return true; } String host = address.getHost(); if (matchAnyInterface(host, trustedInterfaces)) { retur...
@Test public void givenInterfaceIsConfigured_whenMessageWithNonMatchingHost_thenDoNotTrust() throws UnknownHostException { AddressCheckerImpl joinMessageTrustChecker = new AddressCheckerImpl(singleton("127.0.0.2"), logger); Address address = createAddress("127.0.0.1"); assertFalse(joinMessag...
public static SimpleFunction<Row, String> getRowToJsonStringsFunction(Schema beamSchema) { return new RowToJsonFn<String>(beamSchema) { @Override public String apply(Row input) { return RowJsonUtils.rowToJson(objectMapper, input); } }; }
@Test public void testGetRowToJsonStringsFunction() { for (TestCase<? extends RowEncodable> caze : testCases) { String expected = caze.jsonString; String actual = JsonUtils.getRowToJsonStringsFunction(caze.row.getSchema()).apply(caze.row); assertJsonEquals(caze.userT.toString(), expected, actual...
public static Ip4Prefix valueOf(int address, int prefixLength) { return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength); }
@Test public void testContainsIpPrefixIPv4() { Ip4Prefix ipPrefix; ipPrefix = Ip4Prefix.valueOf("1.2.0.0/24"); assertTrue(ipPrefix.contains(Ip4Prefix.valueOf("1.2.0.0/24"))); assertTrue(ipPrefix.contains(Ip4Prefix.valueOf("1.2.0.0/32"))); assertTrue(ipPrefix.contains(Ip4Pref...
@VisibleForTesting static int getNumWriteBehindBuffers(int numBuffers) { int numIOBufs = (int) (Math.log(numBuffers) / Math.log(4) - 1.5); return numIOBufs > 6 ? 6 : numIOBufs; }
@Test public void testIOBufferCountComputation() { assertThat(BinaryHashTable.getNumWriteBehindBuffers(32)).isEqualTo(1); assertThat(BinaryHashTable.getNumWriteBehindBuffers(33)).isEqualTo(1); assertThat(BinaryHashTable.getNumWriteBehindBuffers(40)).isEqualTo(1); assertThat(BinaryHas...
@Override public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean useAutoinc, boolean addFieldName, boolean addCr ) { StringBuilder retval = new StringBuilder( 128 ); String fieldname = v.getName(); int length = v.getLength(); int prec...
@Test public void testGetFieldDefinition() throws Exception { ValueMetaInterface vm = new ValueMetaString(); String sql = hypersonicDatabaseMeta.getFieldDefinition( vm, null, null, false, false, false ); String expectedSql = "VARCHAR()"; assertEquals( "Check PDI-11461 without length", expectedSql, sql...
@Override public boolean isAsync() { return isAsync; }
@Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY) public void cacheFactory_loadFactory( BoundedLocalCache<Int, Int> cache, CacheContext context) throws Throwable { var factory1 = LocalCacheFactory.loadFactory(cache.getClass().getSimpleName()); var other = factory1.newInstance(co...
public static Getter newFieldGetter(Object object, Getter parent, Field field, String modifier) throws Exception { return newGetter(object, parent, modifier, field.getType(), field::get, (t, et) -> new FieldGetter(parent, field, modifier, t, et)); }
@Test public void newFieldGetter_whenExtractingFromEmpty_Array_AndReducerSuffixInNotEmpty_thenReturnNullGetter() throws Exception { OuterObject object = OuterObject.emptyInner("name"); Getter getter = GetterFactory.newFieldGetter(object, null, innersArrayField, "[any]"); Class<?...
@GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) @Override public ClusterInfo get() { return getClusterInfo(); }
@Test public void testClusterSlash() throws JSONException, Exception { WebResource r = resource(); // test with trailing "/" to make sure acts same as without slash ClientResponse response = r.path("ws").path("v1").path("cluster/") .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); ...
public static FunctionConfig validateUpdate(FunctionConfig existingConfig, FunctionConfig newConfig) { FunctionConfig mergedConfig = existingConfig.toBuilder().build(); if (!existingConfig.getTenant().equals(newConfig.getTenant())) { throw new IllegalArgumentException("Tenants differ"); ...
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Tenants differ") public void testMergeDifferentTenant() { FunctionConfig functionConfig = createFunctionConfig(); FunctionConfig newFunctionConfig = createUpdatedFunctionConfig("tenant", "Different"); ...
public static Set<Result> anaylze(String log) { Set<Result> results = new HashSet<>(); for (Rule rule : Rule.values()) { Matcher matcher = rule.pattern.matcher(log); if (matcher.find()) { results.add(new Result(rule, log, matcher)); } } ...
@Test public void outOfMemoryJVM1() throws IOException { CrashReportAnalyzer.Result result = findResultByRule( CrashReportAnalyzer.anaylze(loadLog("/logs/out_of_memory2.txt")), CrashReportAnalyzer.Rule.OUT_OF_MEMORY); }
@Override public String buildContext() { final String plugins = ((Collection<?>) getSource()) .stream() .map(s -> ((ShenyuDictDO) s).getDictName()) .collect(Collectors.joining(",")); return String.format("the shenyu dict[%s] is %s", plugins, StringUtil...
@Test public void batchChangeDictContextTest() { BatchDictChangedEvent batchDictChangedEvent = new BatchDictChangedEvent(Arrays.asList(one, two), null, EventTypeEnum.DICT_UPDATE, "test-operator"); String context = String.format("the shenyu dict[%s] is %s", "one,two", EventTypeEnum.D...
public static Object coerceValue(DMNType requiredType, Object valueToCoerce) { return (requiredType != null && valueToCoerce != null) ? actualCoerceValue(requiredType, valueToCoerce) : valueToCoerce; }
@Test void coerceValueCollectionToArrayConverted() { Object item = "TESTED_OBJECT"; Object value = Collections.singleton(item); DMNType requiredType = new SimpleTypeImpl("http://www.omg.org/spec/DMN/20180521/FEEL/", "string", ...
public DateTokenConverter<Object> getPrimaryDateTokenConverter() { Converter<Object> p = headTokenConverter; while (p != null) { if (p instanceof DateTokenConverter) { DateTokenConverter<Object> dtc = (DateTokenConverter<Object>) p; // only primary converters should be returned as ...
@Test public void settingTimeZoneOptionHasAnEffect() { TimeZone tz = TimeZone.getTimeZone("Australia/Perth"); FileNamePattern fnp = new FileNamePattern("%d{hh, " + tz.getID() + "}", context); assertEquals(tz, fnp.getPrimaryDateTokenConverter().getTimeZone()); }
@Override public List<V> containsEach(Collection<V> c) { return get(containsEachAsync(c)); }
@Test public void testContainsEach() { RSet<Integer> set = redisson.getSet("list", IntegerCodec.INSTANCE); set.add(0); set.add(1); assertThat(set.containsEach(Collections.emptySet())).isEmpty(); assertThat(set.containsEach(Arrays.asList(0, 1))) .hasSize(2) ...
@Override public boolean areEqual(Object one, Object another) { if (one == another) { return true; } if (one == null || another == null) { return false; } if (one instanceof String && another instanceof String) { return one.equals(another);...
@Test public void testClassesWithoutEqualsMethodShouldEqualAsJsonNodes() { JsonTypeDescriptor descriptor = new JsonTypeDescriptor(); FormWithoutEqualsMethod firstEntity = new FormWithoutEqualsMethod("value1"); FormWithoutEqualsMethod secondEntity = new FormWithoutEqualsMethod("value1"); ...
public List<InetAddress> getNetworkInterfaceAddresses() throws SocketException { return Collections.list(NetworkInterface.getNetworkInterfaces()) .stream() .flatMap(ni -> Collections.list(ni.getInetAddresses()).stream()) .toList(); }
@Test public void itGetsListOfNetworkInterfaceAddresses() throws SocketException { assertThat(underTest.getNetworkInterfaceAddresses()) .isInstanceOf(List.class) .hasSizeGreaterThan(0); }
@Override public Service queryService(String serviceName, String groupName) throws NacosException { return null; }
@Test void testQueryService() throws Exception { Service service = client.queryService(SERVICE_NAME, GROUP_NAME); assertNull(service); }
@Override public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) { table.refresh(); if (lastPosition != null) { return discoverIncrementalSplits(lastPosition); } else { return discoverInitialSplits(); } }
@Test public void testIncrementalFromLatestSnapshotWithEmptyTable() throws Exception { ScanContext scanContext = ScanContext.builder() .startingStrategy(StreamingStartingStrategy.INCREMENTAL_FROM_LATEST_SNAPSHOT) .splitSize(1L) .build(); ContinuousSplitPlannerImpl s...
public static CsvIOParse<Row> parseRows(Schema schema, CSVFormat csvFormat) { CsvIOParseHelpers.validateCsvFormat(csvFormat); CsvIOParseHelpers.validateCsvFormatWithSchema(csvFormat, schema); RowCoder coder = RowCoder.of(schema); CsvIOParseConfiguration.Builder<Row> builder = CsvIOParseConfiguration.bui...
@Test public void givenInvalidCsvFormat_throws() { Pipeline pipeline = Pipeline.create(); CSVFormat csvFormat = CSVFormat.DEFAULT .withHeader("a_string", "an_integer", "a_double") .withAllowDuplicateHeaderNames(true); Schema schema = Schema.builder() .ad...
@VisibleForTesting public ConfigDO validateConfigExists(Long id) { if (id == null) { return null; } ConfigDO config = configMapper.selectById(id); if (config == null) { throw exception(CONFIG_NOT_EXISTS); } return config; }
@Test public void testValidateConfigExist_notExists() { assertServiceException(() -> configService.validateConfigExists(randomLongId()), CONFIG_NOT_EXISTS); }
@ExecuteOn(TaskExecutors.IO) @Get(uri = "/{executionId}") @Operation(tags = {"Executions"}, summary = "Get an execution") public Execution get( @Parameter(description = "The execution id") @PathVariable String executionId ) { return executionRepository .findById(tenantService...
@Test void get() { Execution result = triggerInputsFlowExecution(false); // Get the triggered execution by execution id Execution foundExecution = client.retrieve( GET("/api/v1/executions/" + result.getId()), Execution.class ).block(); assertThat(fou...
public static void checkTrue(boolean expression, String errorMessage) { if (!expression) { throw new IllegalArgumentException(errorMessage); } }
@Test public void test_checkTrue_whenTrue() { checkTrue(true, "must be true"); }
@Override public KvMetadata resolveMetadata( boolean isKey, List<MappingField> resolvedFields, Map<String, String> options, InternalSerializationService serializationService ) { Map<QueryPath, MappingField> fieldsByPath = extractFields(resolvedFields, isKe...
@Test @Parameters({ "true", "false" }) public void when_noKeyOrThisPrefixInExternalName_then_usesValue(boolean key) { KvMetadata metadata = INSTANCE.resolveMetadata( key, singletonList(field("field", QueryDataType.INT, "extField")), ...
@Public @Deprecated public static ApplicationId toApplicationId(RecordFactory recordFactory, String applicationIdStr) { return ApplicationId.fromString(applicationIdStr); }
@Test @SuppressWarnings("deprecation") void testApplicationId() { assertThrows(IllegalArgumentException.class, () -> { ConverterUtils.toApplicationId("application_1423221031460"); }); }
protected boolean matches(String pattern, String value) { char[] patArr = pattern.toCharArray(); char[] valArr = value.toCharArray(); int patIndex = 0; int patEndIndex = patArr.length - 1; int valIndex = 0; int valEndIndex = valArr.length - 1; char ch; b...
@Test public void testMatches() { assertMatch("x", "x"); assertNoMatch("x", "y"); assertMatch("xx", "xx"); assertNoMatch("xy", "xz"); assertMatch("?", "x"); assertMatch("x?", "xy"); assertMatch("?y", "xy"); assertMatch("x?z", "xyz"); assertM...
@Override public Response submitApplication(ApplicationSubmissionContextInfo newApp, HttpServletRequest hsr) throws AuthorizationException, IOException, InterruptedException { long startTime = clock.getTime(); // We verify the parameters to ensure that newApp is not empty and // that the format of...
@Test public void testSubmitApplicationWrongFormat() throws IOException, InterruptedException { ApplicationSubmissionContextInfo context = new ApplicationSubmissionContextInfo(); context.setApplicationId("Application_wrong_id"); Response response = interceptor.submitApplication(context, null); ...
@Override public List<String> detect(ClassLoader classLoader) { List<File> classpathContents = classGraph .disableNestedJarScanning() .addClassLoader(classLoader) .scan(1) .getClasspathFiles(); return classpathContents.stream().map(File::getAbsolutePath...
@Test public void shouldNotDetectClassPathResourceThatIsNotAFile() throws Exception { String url = "http://www.example.com/all-the-secrets.jar"; ClassLoader classLoader = new URLClassLoader(new URL[] {new URL(url)}); ClasspathScanningResourcesDetector detector = new ClasspathScanningResourcesDetec...
public Map<Uuid, String> topicIdToNameView() { return new TranslatedValueMapView<>(topicsById, TopicImage::name); }
@Test public void testTopicIdToNameView() { Map<Uuid, String> map = IMAGE1.topicIdToNameView(); assertTrue(map.containsKey(FOO_UUID)); assertEquals("foo", map.get(FOO_UUID)); assertTrue(map.containsKey(BAR_UUID)); assertEquals("bar", map.get(BAR_UUID)); assertFalse(ma...
@Override public boolean addClass(final Class<?> stepClass) { if (stepClasses.contains(stepClass)) { return true; } checkNoComponentAnnotations(stepClass); if (hasCucumberContextConfiguration(stepClass)) { checkOnlyOneClassHasCucumberContextConfiguration(step...
@Test void shouldFailIfMultipleClassesWithSpringAnnotationsAreFound() { final ObjectFactory factory = new SpringFactory(); factory.addClass(WithSpringAnnotations.class); Executable testMethod = () -> factory.addClass(BellyStepDefinitions.class); CucumberBackendException actualThrown...
@Override public InetSocketAddress resolveHost() { List<InetSocketAddress> list = addressList; checkState( list != null, "No service url is provided yet"); checkState( !list.isEmpty(), "No hosts found for service url : " + serviceUrl); if (list.size() == 1) { ...
@Test(expectedExceptions = IllegalStateException.class) public void testResolveBeforeUpdateServiceUrl() { resolver.resolveHost(); }