focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@CanIgnoreReturnValue public final Ordered containsAtLeast( @Nullable Object firstExpected, @Nullable Object secondExpected, @Nullable Object @Nullable ... restOfExpected) { return containsAtLeastElementsIn(accumulate(firstExpected, secondExpected, restOfExpected)); }
@Test public void iterableContainsAtLeastWithDuplicatesFailure() { expectFailureWhenTestingThat(asList(1, 2, 3)).containsAtLeast(1, 2, 2, 2, 3, 4); assertFailureValue("missing (3)", "2 [2 copies], 4"); }
public static boolean isTimeoutException(Throwable exception) { if (exception == null) return false; if (exception instanceof ExecutionException) { exception = exception.getCause(); if (exception == null) return false; } return exception instanceof TimeoutExceptio...
@Test public void testWrappedRuntimeExceptionIsNotTimeoutException() { assertFalse(isTimeoutException(new ExecutionException(new RuntimeException()))); }
@VisibleForTesting void validateRoleDuplicate(String name, String code, Long id) { // 0. 超级管理员,不允许创建 if (RoleCodeEnum.isSuperAdmin(code)) { throw exception(ROLE_ADMIN_CODE_ERROR, code); } // 1. 该 name 名字被其它角色所使用 RoleDO role = roleMapper.selectByName(name); ...
@Test public void testValidateRoleDuplicate_success() { // 调用,不会抛异常 roleService.validateRoleDuplicate(randomString(), randomString(), null); }
@Override public int run(String[] args) throws Exception { YarnConfiguration yarnConf = getConf() == null ? new YarnConfiguration() : new YarnConfiguration( getConf()); boolean isHAEnabled = yarnConf.getBoolean(YarnConfiguration.RM_HA_ENABLED, YarnConfiguration.DEFAULT_...
@Test public void testRemoveFromClusterNodeLabels() throws Exception { // Successfully remove labels dummyNodeLabelsManager.addToCluserNodeLabelsWithDefaultExclusivity(ImmutableSet.of("x", "y")); String[] args = { "-removeFromClusterNodeLabels", "x,,y", "-directlyAccessNodeLabelStore" ...
@Override public Long createDiyPage(DiyPageCreateReqVO createReqVO) { // 校验名称唯一 validateNameUnique(null, createReqVO.getTemplateId(), createReqVO.getName()); // 插入 DiyPageDO diyPage = DiyPageConvert.INSTANCE.convert(createReqVO); diyPage.setProperty("{}"); diyPageMapp...
@Test public void testCreateDiyPage_success() { // 准备参数 DiyPageCreateReqVO reqVO = randomPojo(DiyPageCreateReqVO.class); // 调用 Long diyPageId = diyPageService.createDiyPage(reqVO); // 断言 assertNotNull(diyPageId); // 校验记录的属性是否正确 DiyPageDO diyPage = diy...
@Override public boolean isInstanceOf(String jobInstanceName, boolean ignoreCase, String jobConfigName) { String jobConfigNameWithMarker = translatedJobName(jobInstanceName, jobConfigName); return ignoreCase ? jobInstanceName.equalsIgnoreCase(jobConfigNameWithMarker) : jobInstanceName.equals(jobConf...
@Test public void shouldTellIsInstanceOfCorrectly() throws Exception { assertThat(jobConfig.isInstanceOf("job-runInstance-1", false), is(true)); assertThat(jobConfig.isInstanceOf("Job-runInstance-1", true), is(true)); assertThat(jobConfig.isInstanceOf("Job-runInstance-1", false), is(false)); }
public static Iterator<String> splitOnCharacterAsIterator(String value, char needle, int count) { // skip leading and trailing needles int end = value.length() - 1; boolean skipStart = value.charAt(0) == needle; boolean skipEnd = value.charAt(end) == needle; if (skipStart && skip...
@Test public void testSplitOnCharacterAsIterator() { Iterator<String> it = splitOnCharacterAsIterator("foo", ',', 1); assertEquals("foo", it.next()); assertFalse(it.hasNext()); it = splitOnCharacterAsIterator("foo,bar", ',', 2); assertEquals("foo", it.next()); assert...
@Override public double[] dijkstra(int s) { int n = graph.length; double[] wt = new double[n]; Arrays.fill(wt, Double.POSITIVE_INFINITY); PriorityQueue queue = new PriorityQueue(wt); for (int v = 0; v < n; v++) { queue.insert(v); } wt[s] = 0.0; ...
@Test public void testDijkstra() { System.out.println("Dijkstra"); double[][] wt = { {0.00, 0.41, 0.82, 0.86, 0.50, 0.29}, {1.13, 0.00, 0.51, 0.68, 0.32, 1.06}, {0.95, 1.17, 0.00, 0.50, 1.09, 0.88}, {0.45, 0.67, 0.91, 0.00, 0.59, 0.38}, {0....
@Override public ObjectNode encode(MappingInstruction instruction, CodecContext context) { checkNotNull(instruction, "Mapping instruction cannot be null"); return new EncodeMappingInstructionCodecHelper(instruction, context).encode(); }
@Test public void multicastPriorityInstructionTest() { final MulticastMappingInstruction.PriorityMappingInstruction instruction = (MulticastMappingInstruction.PriorityMappingInstruction) MappingInstructions.multicastPriority(MULTICAST_PRIORITY); final ObjectNo...
public String convertUnicodeCharacterRepresentation(String input) { final char[] chars = input.toCharArray(); int nonAsciiCharCount = countNonAsciiCharacters(chars); if(! (input.contains("\\u") || input.contains("\\U")) && nonAsciiCharCount == 0) return input; int replacedNonAsciiCharacterCount = 0; final ...
@Test public void convertsLatin1toUnicode() { final FormatTranslation formatTranslation = new FormatTranslation(); assertThat(formatTranslation.convertUnicodeCharacterRepresentation("ä"), CoreMatchers.equalTo("\\u00E4")); assertThat(formatTranslation.convertUnicodeCharacterRepresentation("ä1"), CoreM...
@Override public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException { User user = null; try { user = this.identityService.createUserQuery() .userId(userId) .singleResult(); } catch (FlowableException ...
@Test public void testLoadingByNullUserShouldIgnoreFlowableException() { assertThatThrownBy(() -> userDetailsService.loadUserByUsername(null)) .isInstanceOf(UsernameNotFoundException.class) .hasMessage("user (null) could not be found"); }
@Override public String toString() { return toString(null); }
@Test public void toStringTest() { Condition conditionNull = new Condition("user", null); assertEquals("user IS NULL", conditionNull.toString()); Condition conditionNotNull = new Condition("user", "!= null"); assertEquals("user IS NOT NULL", conditionNotNull.toString()); Condition condition2 = new Conditio...
public int maxRetries() { return maxRetries; }
@Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN(\\d)*: Invalid max_retries \\(value=-1\\). " + "Value should be greater or equal than zero.") public void testNegativeRetriesPerServer() { ConfigurationBuilder builder = HotRodClientTes...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SnapshotDto that = (SnapshotDto) o; return Objects.equals(uuid, that.uuid) && Objects.equals(rootComponentUuid, that.rootComponentUuid) &...
@Test void equals_whenComparedToDifferentInstanceWithSameValues_shouldReturnTrue() { SnapshotDto snapshotDto1 = create(); SnapshotDto snapshotDto2 = create(); assertThat(snapshotDto1.equals(snapshotDto2)).isTrue(); assertThat(snapshotDto2.equals(snapshotDto1)).isTrue(); }
private Function<KsqlConfig, Kudf> getUdfFactory( final Method method, final UdfDescription udfDescriptionAnnotation, final String functionName, final FunctionInvoker invoker, final String sensorName ) { return ksqlConfig -> { final Object actualUdf = FunctionLoaderUtils.instan...
@Test public void shouldUseConfigForExtDir() { final InternalFunctionRegistry functionRegistry = new InternalFunctionRegistry(); // The tostring function is in the udf-example.jar that is found in src/test/resources final ImmutableMap<Object, Object> configMap = ImmutableMap.builder().put(KsqlConf...
@Override public byte[] echo(byte[] message) { return read(null, ByteArrayCodec.INSTANCE, ECHO, message); }
@Test public void testEcho() { assertThat(connection.echo("test".getBytes())).isEqualTo("test".getBytes()); }
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test public void test31RefSiblings() { SwaggerConfiguration config = new SwaggerConfiguration().openAPI31(true).openAPI(new OpenAPI()); Reader reader = new Reader(config); OpenAPI openAPI = reader.read(TagResource.class); String yaml = "openapi: 3.1.0\n" + "paths:\n...
public void onError(Throwable cause) { if (cause instanceof StatusRuntimeException && ((StatusRuntimeException) cause).getStatus().getCode() == Status.Code.CANCELLED) { // Cancellation is already handled. return; } mSerializingExecutor.execute(() -> { LogUtils.warnWithException(LOG...
@Test public void ErrorReceived() throws Exception { mWriteHandler.onError(new IOException("test exception")); }
@Override public void run() { if (!redoService.isConnected()) { LogUtils.NAMING_LOGGER.warn("Grpc Connection is disconnect, skip current redo task"); return; } try { redoForInstances(); redoForSubscribes(); } catch (Exception e) { ...
@Test void testRunRedoRemoveInstanceRedoData() throws NacosException { Set<InstanceRedoData> mockData = generateMockInstanceData(false, true, false); when(redoService.findInstanceRedoData()).thenReturn(mockData); redoTask.run(); verify(redoService).removeInstanceForRedo(SERVICE, GROU...
public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR if (splittee == null || splitChar == null) { return new String[0]; } final String EMPTY_ELEMENT = ""; int spot; final int splitLength = splitChar.length(); final Stri...
@Test public void testSplitNullStringString() { Assertions.assertThrows( NullPointerException.class, () -> JOrphanUtils.split(null, ",", "?")); }
public BootstrapMetadata read() throws Exception { Path path = Paths.get(directoryPath); if (!Files.isDirectory(path)) { if (Files.exists(path)) { throw new RuntimeException("Path " + directoryPath + " exists, but is not " + "a directory."); ...
@Test public void testMissingDirectory() { assertEquals("No such directory as ./non/existent/directory", assertThrows(RuntimeException.class, () -> new BootstrapDirectory("./non/existent/directory", Optional.empty()).read()).getMessage()); }
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldChooseSpecificOverVarArgsAtEnd() { // Given: givenFunctions( function(EXPECTED, -1, INT, INT, STRING), function(OTHER, 2, INT, INT, STRING_VARARGS) ); // When: final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of( SqlArgu...
public static String removeTags(String text, List<Tag> tagsToRemove) { if (StringUtils.isBlank(text)) { return text; } var textCopy = new AtomicReference<>(text); tagsToRemove.forEach(tagToRemove -> textCopy.set(removeTag(textCopy.get(), tagToRemove))); return textCopy.get(); }
@Test public void removeTags_mixedCarriageReturns () { var text = "some text\n" + TAG1.getText() + " other following text ending with " + TAG2.getText(); var expected = "some text\n other following text ending with " + TAG2.getText(); var result = TagsHelper.removeTags(text, singletonList(TAG1)); as...
boolean isWriteShareGroupStateSuccessful(List<PersisterStateBatch> stateBatches) { WriteShareGroupStateResult response; try { response = persister.writeState(new WriteShareGroupStateParameters.Builder() .setGroupTopicPartitionData(new GroupTopicPartitionData.Builder<Partition...
@Test public void testWriteShareGroupStateWithNullTopicsData() { Persister persister = Mockito.mock(Persister.class); mockPersisterReadStateMethod(persister); SharePartition sharePartition = SharePartitionBuilder.builder().withPersister(persister).build(); WriteShareGroupStateResult...
public static <T> boolean contains(T[] array, T item) { for (T o : array) { if (o == null) { if (item == null) { return true; } } else { if (o.equals(item)) { return true; } ...
@Test public void contains() { Object[] array = new Object[1]; Object object = new Object(); array[0] = object; assertTrue(ArrayUtils.contains(array, object)); }
protected int computeCount() { int c = 0; for (byte b : map) { c += Integer.bitCount(b & 0xFF); } return length - c; }
@Test public void testComputeCount() { LinearCounting lc = new LinearCounting(4); lc.offer(0); lc.offer(1); lc.offer(2); lc.offer(3); lc.offer(16); lc.offer(17); lc.offer(18); lc.offer(19); assertEquals(27, lc.computeCount()); }
public static Builder builder() { return new Builder(); }
@Test // Test cases that cannot be built with our builder, but that are accepted when parsed public void testCanDeserializeWithoutDefaultValues() throws JsonProcessingException { ConfigResponse noOverrides = ConfigResponse.builder().withDefaults(DEFAULTS).build(); String jsonMissingOverrides = "{\"defaults\...
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) { while (in.readableBytes() >= 1 + MySQLBinlogEventHeader.MYSQL_BINLOG_EVENT_HEADER_LENGTH) { in.markReaderIndex(); MySQLPacketPayload payload = new MySQLPacketPayload(in, ctx.c...
@Test void assertDecodeFormatDescriptionEvent() { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeBytes(StringUtil.decodeHexDump("00513aa8620f01000000790000000000000000000400382e302e323700000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "00000...
static void checkValidTableId(String idToCheck) { if (idToCheck.length() < MIN_TABLE_ID_LENGTH) { throw new IllegalArgumentException("Table ID " + idToCheck + " cannot be empty."); } if (idToCheck.length() > MAX_TABLE_ID_LENGTH) { throw new IllegalArgumentException( "Table ID " ...
@Test public void testCheckValidTableIdWhenIdIsValid() { checkValidTableId("table-id_valid.Test1"); }
public int size() { return data.size(); }
@Test public void testLibSVMLoading() throws IOException { MockOutputFactory factory = new MockOutputFactory(); URL dataFile = LibSVMDataSourceTest.class.getResource("/org/tribuo/datasource/test-1.libsvm"); LibSVMDataSource<MockOutput> source = new LibSVMDataSource<>(dataFile,factory); ...
public void optimize(PinotQuery pinotQuery, @Nullable Schema schema) { optimize(pinotQuery, null, schema); }
@Test public void testMergeEqInFilter() { String query = "SELECT * FROM testTable WHERE int IN (1, 1) AND (long IN (2, 3) OR long IN (3, 4) OR long = 2) AND (float = " + "3.5 OR double IN (1.1, 1.2) OR float = 4.5 OR float > 5.5 OR double = 1.3)"; PinotQuery pinotQuery = CalciteSqlParser.c...
@GetMapping(params = "search=accurate") @Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "roles", action = ActionTypes.READ) public Object getRoles(@RequestParam int pageNo, @RequestParam int pageSize, @RequestParam(name = "username", defaultValue = "") String username, @...
@Test void testGetRoles() { Page<RoleInfo> rolesTest = new Page<RoleInfo>(); when(roleService.getRolesFromDatabase(anyString(), anyString(), anyInt(), anyInt())).thenReturn(rolesTest); Object roles = roleController.getRoles(1, 10, "nacos", "test"); assertEquals(role...
@Override public Collection<RedisServer> slaves(NamedNode master) { List<Map<String, String>> slaves = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_SLAVES, master.getName()); return toRedisServersList(slaves); }
@Test public void testSlaves() { Collection<RedisServer> masters = connection.masters(); Collection<RedisServer> slaves = connection.slaves(masters.iterator().next()); assertThat(slaves).hasSize(2); }
public String getFingerprint() { return fingerprint; }
@Test public void testWithEmptyStreamList() throws Exception { final StreamListFingerprint fingerprint = new StreamListFingerprint(Lists.<Stream>newArrayList()); assertEquals(expectedEmptyFingerprint, fingerprint.getFingerprint()); }
public int compareTo(int left, int right) { int leftSegment = segment(left); int leftSegmentOffset = offset(left); int rightSegment = segment(right); int rightSegmentOffset = offset(right); Slice leftRawSlice = getSegmentRawSlice(leftSegment); int leftOffset = offse...
@Test public void testCompareTo() { SegmentedSliceBlockBuilder blockBuilder = new SegmentedSliceBlockBuilder(10, 10); for (int i = 0; i < SLICE.length(); i++) { blockBuilder.writeBytes(SLICE, i, 1); blockBuilder.closeEntry(); } for (int i = 0; i < SLICE.l...
public static boolean canDrop( FilterPredicate pred, List<ColumnChunkMetaData> columns, DictionaryPageReadStore dictionaries) { Objects.requireNonNull(pred, "pred cannnot be null"); Objects.requireNonNull(columns, "columns cannnot be null"); return pred.accept(new DictionaryFilter(columns, dictionarie...
@Test public void testLtEqLong() throws Exception { LongColumn i64 = longColumn("int64_field"); long lowest = Long.MAX_VALUE; for (long value : longValues) { lowest = Math.min(lowest, value); } assertTrue("Should drop: <= lowest - 1", canDrop(ltEq(i64, lowest - 1), ccmd, dictionaries)); ...
@Operation(summary = "start new activation session with username/password", tags = { SwaggerConfig.ACTIVATE_WEBSITE, SwaggerConfig.REQUEST_ACCOUNT_AND_APP, SwaggerConfig.ACTIVATE_SMS, SwaggerConfig.ACTIVATE_LETTER, SwaggerConfig.ACTIVATE_RDA, SwaggerConfig.ACTIVATE_WITH_APP}, operationId = "session_data", param...
@Test void validateIfCorrectProcessesAreCalledSessionData() throws FlowNotDefinedException, NoSuchAlgorithmException, IOException, FlowStateNotDefinedException, SharedServiceClientException { SessionDataRequest request = new SessionDataRequest(); activationController.sessionData(request); v...
@Override public List<byte[]> mGet(byte[]... keys) { if (isQueueing() || isPipelined()) { for (byte[] key : keys) { read(key, ByteArrayCodec.INSTANCE, RedisCommands.GET, key); } return null; } CommandBatchService es = new CommandBatchServi...
@Test public void testMGet() { Map<byte[], byte[]> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.put(("test" + i).getBytes(), ("test" + i*100).getBytes()); } connection.mSet(map); List<byte[]> r = connection.mGet(map.keySet().toArray(new byte[0][])); ...
@Override public Checksum compute(final InputStream in, final TransferStatus status) throws BackgroundException { return new Checksum(HashAlgorithm.sha512, this.digest("SHA-512", this.normalize(in, status), status)); }
@Test public void testNormalize() throws Exception { assertEquals("dc6d6c30f2be9c976d6318c9a534d85e9a1c3f3608321a04b4678ef408124d45d7164f3e562e68c6c0b6c077340a785824017032fddfa924f4cf400e6cbb6adc", new SHA512ChecksumCompute().compute(IOUtils.toInputStream("input", Charset.defaultCharset()), ...
@Override public void start() { if (taskExecutorThread == null) { taskExecutorThread = new TaskExecutorThread(name); taskExecutorThread.start(); shutdownGate = new CountDownLatch(1); } }
@Test public void shouldPunctuateStreamTime() { when(taskExecutionMetadata.canProcessTask(eq(task), anyLong())).thenReturn(false); when(taskExecutionMetadata.canPunctuateTask(task)).thenReturn(true); when(task.maybePunctuateStreamTime()).thenReturn(true); taskExecutor.start(); ...
public void writeLong(long value) throws IOException { writeInt((int)value); writeInt((int)(value >> 32)); }
@Test public void testWriteLong() throws IOException { writer.writeLong(0x1122334455667788L); writer.writeLong(-0x1122334455667788L); expectData(0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x78, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE); }
@Override public String version() { return AppInfoParser.getVersion(); }
@Test public void testVersionRetrievedFromAppInfoParser() { assertEquals(AppInfoParser.getVersion(), converter.version()); }
public static boolean delete(File path) { if (!path.exists()) { return false; } boolean ret = true; if (path.isDirectory()) { File[] files = path.listFiles(); if (files != null) { for (File f : files) { ret = ret...
@Test public void testDeleteFile() throws IOException { File dir = new File(TemporaryFolderFinder.resolve("testfile")); dir.mkdirs(); File path = File.createTempFile("test", "suffix", dir); assertThat(path.exists(), is(true)); Utils.delete(dir); assertThat(path.e...
@Override public KTable<K, V> toTable() { return toTable(NamedInternal.empty(), Materialized.with(keySerde, valueSerde)); }
@Test public void shouldNotAllowNullNamedOnToTable() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.toTable((Named) null)); assertThat(exception.getMessage(), equalTo("named can't be null")); }
public T getDataByIndex(int index) { return scesimData.get(index); }
@Test public void getDataByIndex() { final Scenario dataByIndex = model.getDataByIndex(3); assertThat(dataByIndex).isNotNull(); assertThat(model.scesimData).contains(dataByIndex); }
@Udf public String uuid() { return java.util.UUID.randomUUID().toString(); }
@Test public void invalidCapacityShouldReturnNullValue() { final ByteBuffer bytes = ByteBuffer.wrap(new byte[17]); final String uuid = udf.uuid(bytes); assertThat(uuid, is(nullValue())); }
@Override public FeatureRange clone() throws CloneNotSupportedException { return (FeatureRange)super.clone(); }
@Test void requireThatCloneIsImplemented() throws CloneNotSupportedException { FeatureRange node1 = new FeatureRange("foo", 6L, 9L); FeatureRange node2 = node1.clone(); assertEquals(node1, node2); assertNotSame(node1, node2); }
public static <T> AvroSchema<T> of(SchemaDefinition<T> schemaDefinition) { if (schemaDefinition.getSchemaReaderOpt().isPresent() && schemaDefinition.getSchemaWriterOpt().isPresent()) { return new AvroSchema<>(schemaDefinition.getSchemaReaderOpt().get(), schemaDefinition.getSchema...
@Test public void testLocalDateTime() { SchemaDefinition<LocalDateTimePojo> schemaDefinition = SchemaDefinition.<LocalDateTimePojo>builder().withPojo(LocalDateTimePojo.class) .withJSR310ConversionEnabled(true).build(); AvroSchema<LocalDateTimePojo> avroSchema...
public Long getNextUniqueId() { return withMetricLogError( () -> withRetryableQuery( GET_UNIQUE_ROWID, stmt -> {}, result -> { if (result.next()) { return result.getLong(ID_COLUMN); } ...
@Test public void testGetNextUniqueId() { assertNotNull(stepDao.getNextUniqueId()); }
@Override public TimelineDomains getDomains(String owner) throws IOException { try (DBIterator iterator = ownerdb.iterator()) { byte[] prefix = KeyBuilder.newInstance().add(owner).getBytesForLookup(); iterator.seek(prefix); List<TimelineDomain> domains = new ArrayList<TimelineDomain>(); wh...
@Test public void testGetDomains() throws IOException { super.testGetDomains(); }
public IntArrayList getEdgesWithDifferentHeading(int baseNode, double heading) { double xAxisAngle = AngleCalc.ANGLE_CALC.convertAzimuth2xaxisAngle(heading); IntArrayList edges = new IntArrayList(1); EdgeIterator iter = edgeExplorer.setBaseNode(baseNode); while (iter.next()) { ...
@Test public void withQueryGraph() { // 2 // 0 -x- 1 BooleanEncodedValue accessEnc = new SimpleBooleanEncodedValue("access", true); DecimalEncodedValue speedEnc = new DecimalEncodedValueImpl("speed", 5, 5, false); EncodingManager em = EncodingManager.start().add(accessEnc)...
public void setProtectThreshold(float protectThreshold) { this.protectThreshold = protectThreshold; }
@Test void testSetProtectThreshold() { serviceMetadata.setProtectThreshold(1.0F); assertEquals(1.0F, serviceMetadata.getProtectThreshold(), 0); }
static ParseResult parse(String expression, NameValidator validator, ClassHelper helper) { ParseResult result = new ParseResult(); try { Parser parser = new Parser(new Scanner("ignore", new StringReader(expression))); Java.Atom atom = parser.parseConditionalExpression(); ...
@Test public void testNegativeConstant() { ParseResult result = parse("average_slope < -0.5", "average_slope"::equals, k -> ""); assertTrue(result.ok); assertEquals("[average_slope]", result.guessedVariables.toString()); result = parse("-average_slope > -0.5", "average_slope"::equals...
public void allocationQuantum(int allocationQuantum) { checkPositive(allocationQuantum, "allocationQuantum"); this.allocationQuantum = allocationQuantum; }
@Test public void writeShouldPreferHighestWeight() throws Http2Exception { // Root the streams at the connection and assign weights. setPriority(STREAM_A, 0, (short) 50, false); setPriority(STREAM_B, 0, (short) 200, false); setPriority(STREAM_C, 0, (short) 100, false); setPri...
@Override public void remove(final String name) { this.faultItemTable.remove(name); }
@Test public void testRemove() throws Exception { latencyFaultTolerance.updateFaultItem(brokerName, 3000, 3000, true); assertThat(latencyFaultTolerance.isAvailable(brokerName)).isFalse(); latencyFaultTolerance.remove(brokerName); assertThat(latencyFaultTolerance.isAvailable(brokerNam...
@Override public LeaveGroupRequest.Builder buildBatchedRequest(int coordinatorId, Set<CoordinatorKey> groupIds) { validateKeys(groupIds); return new LeaveGroupRequest.Builder(groupId.idValue, members); }
@Test public void testBuildRequest() { RemoveMembersFromConsumerGroupHandler handler = new RemoveMembersFromConsumerGroupHandler(groupId, members, logContext); LeaveGroupRequest request = handler.buildBatchedRequest(1, singleton(CoordinatorKey.byGroupId(groupId))).build(); assertEquals(group...
@SuppressWarnings("unchecked") protected ValueWrapper getSingleFactValueResult(FactMapping factMapping, FactMappingValue expectedResult, DMNDecisionResult decisionResult, ...
@Test public void getSingleFactValueResult_failDecision() { DMNDecisionResult failedDecision = createDecisionResultMock("Test", false, new ArrayList<>()); ValueWrapper<?> failedResult = runnerHelper.getSingleFactValueResult(null, ...
@Override public void logoutSuccess(HttpRequest request, @Nullable String login) { checkRequest(request); if (!LOGGER.isDebugEnabled()) { return; } LOGGER.debug("logout success [IP|{}|{}][login|{}]", request.getRemoteAddr(), getAllIps(request), preventLogFlood(emptyIfNull(login))); ...
@Test public void logout_success_does_not_interact_with_request_if_log_level_is_above_DEBUG() { HttpRequest request = mock(HttpRequest.class); logTester.setLevel(Level.INFO); underTest.logoutSuccess(request, "foo"); verifyNoInteractions(request); }
public RingbufferConfig setRingbufferStoreConfig(RingbufferStoreConfig ringbufferStoreConfig) { this.ringbufferStoreConfig = ringbufferStoreConfig; return this; }
@Test public void setRingbufferStoreConfig() { RingbufferStoreConfig ringbufferStoreConfig = new RingbufferStoreConfig() .setEnabled(true) .setClassName("myClassName"); RingbufferConfig config = new RingbufferConfig(NAME); config.setRingbufferStoreConfig(rin...
@VisibleForTesting void parseWorkflowParameter( Map<String, Parameter> workflowParams, Parameter param, String workflowId) { parseWorkflowParameter(workflowParams, param, workflowId, new HashSet<>()); }
@Test public void testParseWorkflowParameterWithImplicitToLong() { LongParameter bar = LongParameter.builder().name("bar").expression("foo + 1;").build(); paramEvaluator.parseWorkflowParameter( Collections.singletonMap("foo", StringParameter.builder().expression("1+2+3;").build()), bar, ...
protected CompletableFuture<AckMessageResponse> ackMessageInBatch(ProxyContext ctx, String group, String topic, AckMessageRequest request) { List<ReceiptHandleMessage> handleMessageList = new ArrayList<>(request.getEntriesCount()); for (AckMessageEntry ackMessageEntry : request.getEntriesList()) { ...
@Test public void testAckMessageInBatch() throws Throwable { ConfigurationManager.getProxyConfig().setEnableBatchAck(true); String successMessageId = "msg1"; String notOkMessageId = "msg2"; String exceptionMessageId = "msg3"; doAnswer((Answer<CompletableFuture<List<BatchAck...
@GetMapping("/") public List<ServiceDTO> listAllServices() { List<ServiceDTO> allServices = Lists.newLinkedList(); allServices .addAll(discoveryService.getServiceInstances(ServiceNameConsts.APOLLO_CONFIGSERVICE)); allServices.addAll(discoveryService.getServiceInstances(ServiceNameConsts.APOLLO_ADM...
@Test public void testListAllServices() { ServiceDTO someServiceDto = mock(ServiceDTO.class); ServiceDTO anotherServiceDto = mock(ServiceDTO.class); when(discoveryService.getServiceInstances(ServiceNameConsts.APOLLO_CONFIGSERVICE)).thenReturn( Lists.newArrayList(someServiceDto)); when(discove...
public SortOrder sortOrder() { return sortOrdersById.get(defaultSortOrderId); }
@Test public void testSortOrder() { Schema schema = new Schema(Types.NestedField.required(10, "x", Types.StringType.get())); TableMetadata meta = TableMetadata.newTableMetadata( schema, PartitionSpec.unpartitioned(), null, ImmutableMap.of()); assertThat(meta.sortOrder().isUnsorted())....
@Override public String toString() { return "ConfigResource(type=" + type + ", name='" + name + "')"; }
@Test public void shouldRoundTripEveryType() { Arrays.stream(ConfigResource.Type.values()).forEach(type -> assertEquals(type, ConfigResource.Type.forId(type.id()), type.toString())); }
@Operation(summary = "provide session", tags = { SwaggerConfig.UPGRADE_LOGIN_LEVEL }, operationId = "digidRdaInit", parameters = {@Parameter(ref = "API-V"), @Parameter(ref = "OS-T"), @Parameter(ref = "APP-V"), @Parameter(ref = "OS-V"), @Parameter(ref = "REL-T")}) @PostMapping(value = "rda/init", produces = ...
@Test void validateIfcorrectProcessesAreCalledRequestStationgetSessionRda () throws FlowNotDefinedException, SharedServiceClientException, NoSuchAlgorithmException, IOException, FlowStateNotDefinedException { RdaSessionRequest request = new RdaSessionRequest(); activationController.getSessionRda(req...
public static URI parse(String gluePath) { requireNonNull(gluePath, "gluePath may not be null"); if (gluePath.isEmpty()) { return rootPackageUri(); } // Legacy from the Cucumber Eclipse plugin // Older versions of Cucumber allowed it. if (CLASSPATH_SCHEME_PRE...
@Test void can_parse_empty_glue_path() { URI uri = GluePath.parse(""); assertAll( () -> assertThat(uri.getScheme(), is("classpath")), () -> assertThat(uri.getSchemeSpecificPart(), is("/"))); }
public Map<String, PartitionStatistics> getQuickStats(ConnectorSession session, SemiTransactionalHiveMetastore metastore, SchemaTableName table, MetastoreContext metastoreContext, List<String> partitionIds) { if (!isQuickStatsEnabled(session)) { return partitionIds.stream().collect(t...
@Test(enabled = false, invocationCount = 3) public void testConcurrentFetchForSamePartition() throws ExecutionException, InterruptedException { QuickStatsBuilder longRunningQuickStatsBuilderMock = (session, metastore, table, metastoreContext, partitionId, files) -> { // Sleep for...
public static String keyToString(Object key, URLEscaper.Escaping escaping, UriComponent.Type componentType, boolean full, ProtocolVersion version) { if (version.compareTo(All...
@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "stringKey") public void testStringKeyToString(ProtocolVersion version, String expected) { String stringKey = "key"; String stringKeyString = URIParamUtils.keyToString(stringKey, NO_ESCAPING, null, true, version); Assert.assertEquals(string...
@Override public int write(String path, ByteBuffer buf, long size, long offset, FuseFileInfo fi) { final long fd = fi.fh.get(); return AlluxioFuseUtils.call(LOG, () -> writeInternal(path, buf, size, offset, fd), FuseConstants.FUSE_WRITE, "path=%s,fd=%d,size=%d,offset=%d", path, fd, size, offse...
@Test public void write() throws Exception { FileOutStream fos = mock(FileOutStream.class); AlluxioURI anyURI = any(); CreateFilePOptions options = any(); when(mFileSystem.createFile(anyURI, options)).thenReturn(fos); // "create" checks if the file already exists first when(mFileSystem.getStat...
@Override public void merge(Accumulator<Double, Double> other) { this.min = Math.min(this.min, other.getLocalValue()); }
@Test void testMerge() { DoubleMinimum min1 = new DoubleMinimum(); min1.add(1234.5768); DoubleMinimum min2 = new DoubleMinimum(); min2.add(5678.9012); min2.merge(min1); assertThat(min2.getLocalValue()).isCloseTo(1234.5768, within(0.0)); min1.merge(min2); ...
@Override public AwsProxyResponse handle(Throwable ex) { log.error("Called exception handler for:", ex); // adding a print stack trace in case we have no appender or we are running inside SAM local, where need the // output to go to the stderr. ex.printStackTrace(); if (ex i...
@Test void streamHandle_InvalidResponseObjectException_responseString() throws IOException { ByteArrayOutputStream respStream = new ByteArrayOutputStream(); exceptionHandler.handle(new InvalidResponseObjectException(INVALID_RESPONSE_MESSAGE, null), respStream); assertNotNull(res...
private QueryFederationQueuePoliciesResponse filterPoliciesConfigurationsByQueues( List<String> queues, Map<String, SubClusterPolicyConfiguration> policiesConfigurations, int pageSize, int currentPage) throws YarnException { // Step1. Check the parameters, if the policy list is empty, return empty dire...
@Test public void testFilterPoliciesConfigurationsByQueues() throws Exception { // SubClusters : SC-1,SC-2 List<String> subClusterLists = new ArrayList<>(); subClusterLists.add("SC-1"); subClusterLists.add("SC-2"); // We initialize 26 queues, queue root.a~root.z List<FederationQueueWeight> fe...
String getEntryName( String name ) { return "${" + Const.INTERNAL_VARIABLE_ENTRY_CURRENT_DIRECTORY + "}/" + name; }
@Test public void testEntryName() { assertEquals( "${Internal.Entry.Current.Directory}/" + FILE_NAME, dialog.getEntryName( FILE_NAME ) ); }
@Override public RSet<V> get(final K key) { String keyHash = keyHash(key); final String setName = getValuesName(keyHash); return new RedissonSet<V>(codec, commandExecutor, setName, null) { @Override public RFuture<Boolean> addAsync(V value) { ...
@Test public void testDelete() { RSetMultimap<String, String> map = redisson.getSetMultimap("simple"); map.put("1", "2"); map.put("2", "3"); assertThat(map.delete()).isTrue(); RSetMultimap<String, String> map2 = redisson.getSetMultimap("simple1"); assertThat(...
public EnumSet<RepositoryFilePermission> processCheckboxes() { return processCheckboxes( false ); }
@Test public void testProcessCheckboxesWriteCheckedEnableAppropriateFalse() { when( readCheckbox.isChecked() ).thenReturn( false ); when( writeCheckbox.isChecked() ).thenReturn( true ); when( deleteCheckbox.isChecked() ).thenReturn( false ); when( manageCheckbox.isChecked() ).thenReturn( false ); ...
@RequiresApi(api = Build.VERSION_CODES.O) private static void createNormalChannel(Context context) { NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (mNotificationManager.getNotificationChannel(CHANNEL_NORMAL_ID) == null) { ...
@Test @Config(sdk = {P}) // min sdk is O public void testCreateNormalChannel() { NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_NORMAL_ID); NotificationConstants.setMetadata(context, builder, TYPE_NORMAL); List<Object> channels = shadowNotificationManager.getNotific...
@Override public void run() { if (processor != null) { processor.execute(); } else { if (!beforeHook()) { logger.info("before-feature hook returned [false], aborting: {}", this); } else { scenarios.forEachRemaining(this::processScen...
@Test void testTypeConversion() { run("type-conversion.feature"); }
void visit(final PathItem.HttpMethod method, final Operation operation, final PathItem pathItem) { if (filter.accept(operation.getOperationId())) { final String methodName = method.name().toLowerCase(); emitter.emit(methodName, path); emit("id", operation.getOperationId()); ...
@Test public void testDestinationToSyntax() { final Builder method = MethodSpec.methodBuilder("configure"); final MethodBodySourceCodeEmitter emitter = new MethodBodySourceCodeEmitter(method); final OperationVisitor<?> visitor = new OperationVisitor<>( ...
@Override public RefreshNodesResponse refreshNodes(RefreshNodesRequest request) throws StandbyException, YarnException, IOException { // parameter verification. // We will not check whether the DecommissionType is empty, // because this parameter has a default value at the proto level. if (requ...
@Test public void testRefreshNodes() throws Exception { // We will test 2 cases: // case 1, request is null. // case 2, normal request. // If the request is null, a Missing RefreshNodes request exception will be thrown. // null request. LambdaTestUtils.intercept(YarnException.class, "...
public static int booleanToValue(Boolean booleanValue) { if (booleanValue) { return TRUE; } else { return FALSE; } }
@Test public void testBooleanToValue() { assertTrue(BooleanUtils.valueToBoolean(1)); assertFalse(BooleanUtils.valueToBoolean(0)); }
@Override public boolean isOldValueAvailable() { return hasOldValue; }
@Test public void isOldValueAvailable() { assertThat(event.isOldValueAvailable()).isTrue(); }
@SuppressWarnings("unchecked") public static <S, F> S visit(final Schema schema, final Visitor<S, F> visitor) { final BiFunction<Visitor<?, ?>, Schema, Object> handler = HANDLER.get(schema.type()); if (handler == null) { throw new UnsupportedOperationException("Unsupported schema type: " + schema.type()...
@Test public void shouldThrowByDefaultFromNonStructured() { // Given: visitor = new Visitor<String, Integer>() { }; nonStructuredSchemas().forEach(schema -> { try { // When: SchemaWalker.visit(schema, visitor); fail(); } catch (final UnsupportedOperationExceptio...
static Builder newBuilder() { return new AutoValue_SplunkEventWriter.Builder(); }
@Test public void eventWriterMissingURLProtocol() { Exception thrown = assertThrows( IllegalArgumentException.class, () -> SplunkEventWriter.newBuilder().withUrl("test-url").build()); assertTrue(thrown.getMessage().contains(SplunkEventWriter.INVALID_URL_FORMAT_MESSAGE)); }
@Override public void close() { httpClient.dispatcher().executorService().shutdown(); httpClient.connectionPool().evictAll(); }
@Test public void testConnectionResourceHandling() throws Exception { List<Connection> connections = new ArrayList<>(); for (int i = 0; i < 100; i++) { Connection connection = createConnection(); connections.add(connection); try (Statement statem...
public Optional<User> login(String nameOrEmail, String password) { if (nameOrEmail == null || password == null) { return Optional.empty(); } User user = userDAO.findByName(nameOrEmail); if (user == null) { user = userDAO.findByEmail(nameOrEmail); } if (user != null && !user.isDisabled()) { boolean...
@Test void callingLoginShouldLookupUserByName() { userService.login("test", "password"); Mockito.verify(userDAO).findByName("test"); }
@Override public RangeBoundary getLowBoundary() { return lowBoundary; }
@Test void getLowBoundary() { final Range.RangeBoundary lowBoundary = Range.RangeBoundary.CLOSED; final RangeImpl rangeImpl = new RangeImpl(lowBoundary, 10, 15, Range.RangeBoundary.OPEN); assertThat(rangeImpl.getLowBoundary()).isEqualTo(lowBoundary); }
@Override public Iterable<T> get() { return values; }
@Test public void testGet() throws Exception { FakeBeamFnStateClient fakeBeamFnStateClient = new FakeBeamFnStateClient( StringUtf8Coder.of(), ImmutableMap.of(key(), asList("A1", "A2", "A3", "A4", "A5", "A6"))); IterableSideInput<String> iterableSideInput = new Iterable...
public EndpointResponse streamQuery( final KsqlSecurityContext securityContext, final KsqlRequest request, final CompletableFuture<Void> connectionClosedFuture, final Optional<Boolean> isInternalRequest, final MetricsCallbackHolder metricsCallbackHolder, final Context context ) { ...
@Test public void shouldReturn400OnBadStatement() { // Given: when(mockStatementParser.parseSingleStatement(any())) .thenThrow(new IllegalArgumentException("some error message")); // When: final KsqlRestException e = assertThrows( KsqlRestException.class, () -> testResource.st...
@Override protected int command() { if (!validateConfigFilePresent()) { return 1; } final MigrationConfig config; try { config = MigrationConfig.load(getConfigFile()); } catch (KsqlException | MigrationException e) { LOGGER.error(e.getMessage()); return 1; } retur...
@Test public void shouldFailOnEmptyDescription() { // Given: command = PARSER.parse(""); // When: final int result = command.command(migrationsDir); // Then: assertThat(result, is(1)); }
@Override public long getStatusTimestamp(JobStatus status) { return stateTimestamps[status.ordinal()]; }
@Test void getStatusTimestamp() { final JobStatusStore store = new JobStatusStore(0L); store.jobStatusChanges(new JobID(), JobStatus.RUNNING, 1L); assertThat(store.getStatusTimestamp(JobStatus.RUNNING), is(1L)); }
public static void apply(LoggingConfiguration conf, File logbackFile) { Logback.configure(logbackFile, conf.getSubstitutionVariables()); if (conf.getLogOutput() != null) { setCustomRootAppender(conf); } }
@Test public void testNoListener() throws UnsupportedEncodingException { System.setOut(new PrintStream(out, false, StandardCharsets.UTF_8.name())); LoggingConfigurator.apply(conf); Logger logger = LoggerFactory.getLogger(this.getClass()); logger.info("info"); assertThat(out.toString(StandardChar...
List<GcpAddress> getAddresses() { try { return RetryUtils.retry(this::fetchGcpAddresses, RETRIES, NON_RETRYABLE_KEYWORDS); } catch (RestClientException e) { handleKnownException(e); return emptyList(); } }
@Test public void getAddressesUnauthorized() { // given Label label = null; String forbiddenMessage = "\"reason\":\"Request had insufficient authentication scopes\""; RestClientException exception = new RestClientException(forbiddenMessage, HttpURLConnection.HTTP_UNAUTHORIZED); ...
void removeBuiltinRole(final String roleName) { final Bson roleFindingFilter = Filters.eq(RoleServiceImpl.NAME_LOWER, roleName.toLowerCase(Locale.ENGLISH)); final MongoDatabase mongoDatabase = mongoConnection.getMongoDatabase(); final MongoCollection<Document> rolesCollection = mongoDatabase.get...
@Test public void testAttemptToRemoveNonExistingRoleDoesNotHaveEffectOnExistingUsersAndRoles() { final Document adminUserBefore = usersCollection.find(Filters.eq(UserImpl.USERNAME, TEST_ADMIN_USER_WITH_BOTH_ROLES)).first(); final Document testUserBefore = usersCollection.find(Filters.eq(UserImpl.USE...
public static CompletableFuture<Void> runAfterwards( CompletableFuture<?> future, RunnableWithException runnable) { return runAfterwardsAsync(future, runnable, Executors.directExecutor()); }
@Test void testRunAfterwardsExceptional() { final CompletableFuture<Void> inputFuture = new CompletableFuture<>(); final OneShotLatch runnableLatch = new OneShotLatch(); final FlinkException testException = new FlinkException("Test exception"); final CompletableFuture<Void> runFutur...
public synchronized boolean maybeUpdateGetRequestTimestamp(long currentTime) { long lastRequestTimestamp = Math.max(lastGetRequestTimestamp, lastPushRequestTimestamp); long timeElapsedSinceLastMsg = currentTime - lastRequestTimestamp; if (timeElapsedSinceLastMsg >= pushIntervalMs) { ...
@Test public void testMaybeUpdateGetRequestWithImmediateRetryFail() { assertTrue(clientInstance.maybeUpdateGetRequestTimestamp(System.currentTimeMillis())); // Second request should be rejected as time since last request is less than the push interval. assertFalse(clientInstance.maybeUpdateG...
@Override public boolean next() throws SQLException { return proxyBackendHandler.next(); }
@Test void assertNext() throws SQLException { when(proxyBackendHandler.next()).thenReturn(true, false); assertTrue(queryExecutor.next()); assertFalse(queryExecutor.next()); }
@Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // has the class loaded already? Class<?> loadedClass = findLoadedClass(name); if (loadedClass == null) { try { // find the class from given jar urls as in first c...
@Test public void canLoadClassFromIntermediate() throws Exception { URL jarUrl = resourceJarUrl("deployment/sample-pojo-1.0-car.jar"); intermediateCl = new URLClassLoader(new URL[]{jarUrl}, ClassLoader.getSystemClassLoader()); cl = new ChildFirstClassLoader(new URL[]{emptyJarUrl}, ...
@Override public void doRun() { final Instant mustBeOlderThan = Instant.now().minus(maximumSearchAge); searchDbService.getExpiredSearches(findReferencedSearchIds(), mustBeOlderThan).forEach(searchDbService::delete); }
@Test public void testForEmptyViews() { when(viewService.streamAll()).thenReturn(Stream.empty()); final SearchSummary search = SearchSummary.builder() .id("This search is expired and should be deleted") .createdAt(DateTime.now(DateTimeZone.UTC).minus(Duration.standar...
@GET @Path("{path:.*}") @Produces({MediaType.APPLICATION_OCTET_STREAM + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8}) public Response get(@PathParam("path") String path, @Context UriInfo uriInfo, @QueryParam(OperationParam.NAME) O...
@Test @TestDir @TestJetty @TestHdfs public void testGlobFilter() throws Exception { createHttpFSServer(false, false); long oldOpsListStatus = metricsGetter.get("LISTSTATUS").call(); FileSystem fs = FileSystem.get(TestHdfsHelper.getHdfsConf()); fs.mkdirs(new Path("/tmp")); fs.create(n...
public static synchronized void configure(DataflowWorkerLoggingOptions options) { if (!initialized) { throw new RuntimeException("configure() called before initialize()"); } // For compatibility reason, we do not call SdkHarnessOptions.getConfiguredLoggerFromOptions // to config the logging for l...
@Test public void testWithWorkerCustomLogLevels() { DataflowWorkerLoggingOptions options = PipelineOptionsFactory.as(DataflowWorkerLoggingOptions.class); options.setWorkerLogLevelOverrides( new WorkerLogLevelOverrides() .addOverrideForName("A", DataflowWorkerLoggingOptions.Level.DE...