focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@SuppressWarnings({"SimplifyBooleanReturn"}) public static Map<String, ParamDefinition> cleanupParams(Map<String, ParamDefinition> params) { if (params == null || params.isEmpty()) { return params; } Map<String, ParamDefinition> mapped = params.entrySet().stream() .collect( ...
@Test public void testCleanupOptionalNestedEmptyParams() throws JsonProcessingException { Map<String, ParamDefinition> allParams = parseParamDefMap( "{'map': {'type': 'MAP','value': {'optional': {'type': 'STRING', 'internal_mode': 'OPTIONAL'}}}}"); Map<String, ParamDefinition> cleanedParam...
static ByteBuffer resetBuffer(ByteBuffer buffer, int len) { int pos = buffer.position(); buffer.put(getEmptyChunk(len), 0, len); buffer.position(pos); return buffer; }
@Test public void testResetBuffer() { ByteBuffer buf = ByteBuffer.allocate(chunkSize * 2).putInt(1234); buf.position(0); ByteBuffer ret = CoderUtil.resetBuffer(buf, chunkSize); for (int i = 0; i < chunkSize; i++) { assertEquals(0, ret.getInt(i)); } byte[] inputs = ByteBuffer.allocate(nu...
@Override public T master() { List<ChildData<T>> children = getActiveChildren(); children.sort(sequenceComparator); if (children.isEmpty()) { return null; } return children.get(0).getNode(); }
@Test public void testMasterWithStaleNodes2() throws Exception { putChildData(group, PATH + "/001", "container1"); // stale putChildData(group, PATH + "/002", "container2"); putChildData(group, PATH + "/003", "container1"); putChildData(group, PATH + "/004", "container3"); // stale ...
@Override public InterpreterResult interpret(final String st, final InterpreterContext context) throws InterpreterException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("st:\n{}", st); } final FormType form = getFormType(); RemoteInterpreterProcess interpreterProcess = null; try { ...
@Test void testFIFOScheduler() throws InterruptedException, InterpreterException { interpreterSetting.getOption().setPerUser(InterpreterOption.SHARED); // by default SleepInterpreter would use FIFOScheduler final Interpreter interpreter1 = interpreterSetting.getInterpreter("user1", note1Id, "sleep"); ...
@Override public void deleteDiyTemplate(Long id) { // 校验存在 DiyTemplateDO diyTemplateDO = validateDiyTemplateExists(id); // 校验使用中 if (BooleanUtil.isTrue(diyTemplateDO.getUsed())) { throw exception(DIY_TEMPLATE_USED_CANNOT_DELETE); } // 删除 diyTemplat...
@Test public void testDeleteDiyTemplate_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> diyTemplateService.deleteDiyTemplate(id), DIY_TEMPLATE_NOT_EXISTS); }
static Result coerceUserList( final Collection<Expression> expressions, final ExpressionTypeManager typeManager ) { return coerceUserList(expressions, typeManager, Collections.emptyMap()); }
@Test public void shouldNotCoerceArrayWithDifferentExpression() { // Given: final ImmutableList<Expression> expressions = ImmutableList.of( new CreateArrayExpression( ImmutableList.of( new IntegerLiteral(10) ) ), new CreateArrayExpression( ...
@Override public E poll() { E item = next(); if (item != null) { return item; } if (!drainPutStack()) { return null; } return next(); }
@Test public void poll() throws InterruptedException { queue.setConsumerThread(Thread.currentThread()); queue.offer("1"); queue.offer("2"); assertEquals("1", queue.poll()); assertEquals("2", queue.poll()); }
@Override public YamlProcessList swapToYamlConfiguration(final Collection<Process> data) { YamlProcessList result = new YamlProcessList(); result.setProcesses(data.stream().map(yamlProcessSwapper::swapToYamlConfiguration).collect(Collectors.toList())); return result; }
@Test void assertSwapToYamlConfiguration() { String processId = new UUID(ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextLong()).toString().replace("-", ""); ExecutionGroupReportContext reportContext = new ExecutionGroupReportContext(processId, "foo_db", new Grantee("root", "...
public String generateInvalidPayloadExceptionMessage(final byte[] hl7Bytes) { if (hl7Bytes == null) { return "HL7 payload is null"; } return generateInvalidPayloadExceptionMessage(hl7Bytes, hl7Bytes.length); }
@Test public void testGenerateInvalidPayloadExceptionMessage() { String message = hl7util.generateInvalidPayloadExceptionMessage(TEST_MESSAGE.getBytes()); assertNull(message, "Valid payload should result in a null message"); }
@Override public String toString() { StringBuilder result = new StringBuilder(); result.append(" ORDER BY "); for (int i = 0; i < columnLabels.size(); i++) { if (0 == i) { result.append(columnLabels.get(0)).append(' ').append(orderDirections.get(i).name()); ...
@Test void assertToString() { assertThat(orderByToken.toString(), is(" ORDER BY Test1 ASC,Test2 ASC ")); }
private static GuardedByExpression bind(JCTree.JCExpression exp, BinderContext context) { GuardedByExpression expr = BINDER.visit(exp, context); checkGuardedBy(expr != null, String.valueOf(exp)); checkGuardedBy(expr.kind() != Kind.TYPE_LITERAL, "Raw type literal: %s", exp); return expr; }
@Test public void namedClass_super() { assertThat( bind( "Test", "Super.class", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Super {}", "class Te...
@Udf public <T> List<T> remove( @UdfParameter(description = "Array of values") final List<T> array, @UdfParameter(description = "Value to remove") final T victim) { if (array == null) { return null; } return array.stream() .filter(el -> !Objects.equals(el, victim)) .coll...
@Test public void shouldRemoveAllMatchingElements() { final List<String> input1 = Arrays.asList("foo", " ", "foo", "bar"); final String input2 = "foo"; final List<String> result = udf.remove(input1, input2); assertThat(result, is(Arrays.asList(" ", "bar"))); }
public WorkerService getWorkerService() throws UnsupportedOperationException { return functionWorkerService.orElseThrow(() -> new UnsupportedOperationException("Pulsar Function Worker " + "is not enabled, probably functionsWorkerEnabled is set to false")); }
@Test public void testGetWorkerServiceException() throws Exception { conf.setFunctionsWorkerEnabled(false); setup(); String errorMessage = "Pulsar Function Worker is not enabled, probably functionsWorkerEnabled is set to false"; int thrownCnt = 0; try { pulsar.g...
@Override public void close() { this.displayResultExecutorService.shutdown(); }
@Test void testFailedStreamingResult() { final Configuration testConfig = new Configuration(); testConfig.set(EXECUTION_RESULT_MODE, ResultMode.TABLEAU); testConfig.set(RUNTIME_MODE, RuntimeExecutionMode.STREAMING); ResultDescriptor resultDescriptor = new ResultDescri...
static List<String> locateScripts(ArgsMap argsMap) { String script = argsMap.get(SCRIPT); String scriptDir = argsMap.get(SCRIPT_DIR); List<String> scripts = new ArrayList<>(); if (script != null) { StringTokenizer tokenizer = new StringTokenizer(script, ":"); if (log.isDebugEnabled()) { ...
@Test void locateScriptsDir() throws Exception { Path dir = Files.createTempDirectory("test-"); Path script = Files.createTempFile(dir, "script-", ".btrace"); ArgsMap argsMap = new ArgsMap(new String[] {"scriptdir=" + dir.toString()}); List<String> scripts = Main.locateScripts(argsMap); assertEqu...
public int format(String... args) throws UsageException { CommandLineOptions parameters = processArgs(args); if (parameters.version()) { errWriter.println(versionString()); return 0; } if (parameters.help()) { throw new UsageException(); } JavaFormatterOptions options = ...
@Test public void version() throws UsageException { StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); Main main = new Main(new PrintWriter(out, true), new PrintWriter(err, true), System.in); assertThat(main.format("-version")).isEqualTo(0); assertThat(err.toString()).co...
public String text() { return text; }
@Test public void textOnly() { badge = NodeBadge.text(TXT); checkFields(badge, Status.INFO, false, TXT, null); }
@NonNull @Override public FileName toProviderFileName( @NonNull ConnectionFileName pvfsFileName, @NonNull T details ) throws KettleException { StringBuilder providerUriBuilder = new StringBuilder(); appendProviderUriConnectionRoot( providerUriBuilder, details ); // Examples: // providerUriBu...
@Test public void testToProviderFileNameHandlesTwoLevelPaths() throws Exception { ConnectionFileName pvfsFileName = mockPvfsFileNameWithPath( "/rest/path" ); FileName providerFileName = transformer.toProviderFileName( pvfsFileName, details1 ); assertEquals( "scheme1://rest/path", providerFileName.getUR...
public abstract void run(Bootstrap<?> bootstrap, Namespace namespace) throws Exception;
@Test void listHelpOnceOnArgumentOmission() throws Exception { assertThat(cli.run("test", "-h")) .isEmpty(); assertThat(stdOut) .hasToString(String.format( "usage: java -jar dw-thing.jar test [-h] {a,b,c}%n" + "%n" + "t...
private CompletableFuture<Boolean> isSuperUser() { assert ctx.executor().inEventLoop(); if (service.isAuthenticationEnabled() && service.isAuthorizationEnabled()) { CompletableFuture<Boolean> isAuthRoleAuthorized = service.getAuthorizationService().isSuperUser( authRole, ...
@Test(timeOut = 30000) public void testNonExistentTopic() throws Exception { AuthorizationService authorizationService = spyWithClassAndConstructorArgs(AuthorizationService.class, svcConfig, pulsar.getPulsarResources()); doReturn(authorizationService).when(brokerService).getAuthoriza...
static String lastPartOf(String string, String separator) { String[] parts = string.split(separator); return parts[parts.length - 1]; }
@Test public void lastPartOfTest() { assertEquals("us-east1-a", lastPartOf("https://www.googleapis.com/compute/v1/projects/projectId/zones/us-east1-a", "/")); assertEquals("", lastPartOf("", "")); assertEquals("", lastPartOf("", "/")); }
@Override public boolean tryLock(String name) { return tryLock(name, DEFAULT_LOCK_DURATION_SECONDS); }
@Test public void tryLock_fails_with_IAE_if_name_length_is_more_than_max_or_more() { String badLockName = RandomStringUtils.random(LOCK_NAME_MAX_LENGTH + 1 + new Random().nextInt(96)); expectBadLockNameIAE(() -> underTest.tryLock(badLockName), badLockName); }
public void ensureActiveGroup() { while (!ensureActiveGroup(time.timer(Long.MAX_VALUE))) { log.warn("still waiting to ensure active group"); } }
@Test public void testWakeupAfterSyncGroupReceivedExternalCompletion() throws Exception { setupCoordinator(); mockClient.prepareResponse(groupCoordinatorResponse(node, Errors.NONE)); mockClient.prepareResponse(joinGroupFollowerResponse(1, memberId, leaderId, Errors.NONE)); mockClien...
public static ExtensibleLoadManagerImpl get(LoadManager loadManager) { if (!(loadManager instanceof ExtensibleLoadManagerWrapper loadManagerWrapper)) { throw new IllegalArgumentException("The load manager should be 'ExtensibleLoadManagerWrapper'."); } return loadManagerWrapper.get();...
@Test(timeOut = 10 * 1000) public void unloadTimeoutCheckTest() throws Exception { Pair<TopicName, NamespaceBundle> topicAndBundle = getBundleIsNotOwnByChangeEventTopic("unload-timeout"); String topic = topicAndBundle.getLeft().toString(); var bundle = topicAndBundle.getRight().t...
public Watcher getWatcher() throws IOException { if (JAVA_VERSION >= 1.7) { if (IS_WINDOWS) { return new TreeWatcherNIO(); } else { return new WatcherNIO2(); } } else { throw new UnsupportedOperationException("Watcher is imp...
@Test public void testGetWatcher() throws Exception { assertNotNull(new WatcherFactory().getWatcher()); }
public static String encodeInUtf8(String url) { String[] parts = url.split("/"); StringBuilder builder = new StringBuilder(); for (int i = 0; i < parts.length; i++) { String part = parts[i]; builder.append(URLEncoder.encode(part, StandardCharsets.UTF_8)); if (...
@Test public void shouldKeepTrailingSlash() { assertThat(UrlUtil.encodeInUtf8("a%b/c%d/"), is("a%25b/c%25d/")); }
public static Map<String, Object> appendDeserializerToConfig(Map<String, Object> configs, Deserializer<?> keyDeserializer, Deserializer<?> valueDeserializer) { // validate deserializ...
@Test public void testAppendDeserializerToConfigWithException() { Map<String, Object> configs = new HashMap<>(); configs.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, null); configs.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, valueDeserializerClass); assertThrows(ConfigEx...
@Override public List<String> getAttributes() { return attributes; }
@Test public void testGetAttributes() throws Exception { NumberField f = new NumberField("test", "Name", 0, "foo", ConfigurationField.Optional.NOT_OPTIONAL); assertEquals(0, f.getAttributes().size()); NumberField f1 = new NumberField("test", "Name", 0, "foo", NumberField.Attribute.IS_PORT_N...
public NetworkConfig setPortCount(int portCount) { if (portCount < 1) { throw new IllegalArgumentException("port count can't be smaller than 0"); } this.portCount = portCount; return this; }
@Test(expected = IllegalArgumentException.class) public void testNegativePortCount() { int portCount = -1; networkConfig.setPortCount(portCount); }
private EntityRelation doDelete(String strFromId, String strFromType, String strRelationType, String strRelationTypeGroup, String strToId, String strToType) throws ThingsboardException { checkParameter(FROM_ID, strFromId); checkParameter(FROM_TYPE, strFromType); checkParameter(RELATION_TYPE, str...
@Test public void testDeleteRelationWithOtherFromDeviceError() throws Exception { Device device = buildSimpleDevice("Test device 1"); EntityRelation relation = createFromRelation(mainDevice, device, "CONTAINS"); doPost("/api/relation", relation).andExpect(status().isOk()); Device d...
public List<String[]> select() { return select(this.datas.length); }
@Test public void selectTest() { Arrangement arrangement = new Arrangement(new String[] { "1", "2", "3", "4" }); List<String[]> list = arrangement.select(2); assertEquals(Arrangement.count(4, 2), list.size()); assertArrayEquals(new String[] {"1", "2"}, list.get(0)); assertArrayEquals(new String[] {"1", "3"},...
@Override public int compare(T o1, T o2) { if (!(o1 instanceof CharSequence) || !(o2 instanceof CharSequence)) { throw new RuntimeException("Attempted use of AvroCharSequenceComparator on non-CharSequence objects: " + o1.getClass().getName() + " and " + o2.getClass().getName()); } return c...
@Test void compareUtf8ToString() { assertEquals(0, mComparator.compare(new Utf8(""), "")); assertThat(mComparator.compare(new Utf8(""), "a"), lessThan(0)); assertThat(mComparator.compare(new Utf8("a"), ""), greaterThan(0)); assertEquals(0, mComparator.compare(new Utf8("a"), "a")); assertThat(mCom...
@Override public V pollFromAny(long timeout, TimeUnit unit, String... queueNames) throws InterruptedException { return commandExecutor.getInterrupted(pollFromAnyAsync(timeout, unit, queueNames)); }
@Test public void testPollFromAny() throws InterruptedException { final RBoundedBlockingQueue<Integer> queue1 = redisson.getBoundedBlockingQueue("queue:pollany"); assertThat(queue1.trySetCapacity(10)).isTrue(); ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();...
@Override public SelType call(String methodName, SelType[] args) { if (args.length == 1) { if ("dateIntToTs".equals(methodName)) { return dateIntToTs(args[0]); } else if ("tsToDateInt".equals(methodName)) { return tsToDateInt(args[0]); } } else if (args.length == 2) { i...
@Test(expected = IllegalArgumentException.class) public void testCallTimeoutForDateIntDeadlineInvalidInput() { SelUtilFunc.INSTANCE.call( "timeoutForDateIntDeadline", new SelType[] {SelString.of("2019010101"), SelString.of("1 day")}); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { if (!requestContext.getUriInfo().getPath().endsWith(targetPath)) { return; } final List<MediaType> acceptedFormats = requestContext.getAcceptableMediaTypes(); final Map<MediaType, E...
@Test void returns415IfNoCompatibleFormatIsFound() throws Exception { final ContainerRequestFilter filter = new MessageExportFormatFilter(Collections.singleton(() -> MoreMediaTypes.TEXT_PLAIN_TYPE)); final ContainerRequestContext requestContext = mockRequestContext(Collections.singletonList(MoreMedi...
public Result parse(final String string) throws DateNotParsableException { return this.parse(string, new Date()); }
@Test public void issue1226() throws Exception { NaturalDateParser.Result result99days = naturalDateParser.parse("last 99 days"); assertThat(result99days.getFrom()).isEqualToIgnoringMillis(result99days.getTo().minusDays(100)); NaturalDateParser.Result result100days = naturalDateParser.parse...
@Nonnull public static <K, V> BatchSource<Entry<K, V>> map(@Nonnull String mapName) { return batchFromProcessor("mapSource(" + mapName + ')', readMapP(mapName)); }
@Test public void map_byRef() { // Given List<Integer> input = sequence(itemCount); putToBatchSrcMap(input); // When BatchSource<Entry<String, Integer>> source = Sources.map(srcMap); // Then p.readFrom(source).writeTo(sink); execute(); List<E...
public boolean checkIfEnabled() { try { this.gitCommand = locateDefaultGit(); MutableString stdOut = new MutableString(); this.processWrapperFactory.create(null, l -> stdOut.string = l, gitCommand, "--version").execute(); return stdOut.string != null && stdOut.string.startsWith("git version"...
@Test public void git_should_not_be_enabled_if_version_command_does_not_return_string_output() { ProcessWrapperFactory mockedCmd = mockGitVersionCommand(null); NativeGitBlameCommand blameCommand = new NativeGitBlameCommand(System2.INSTANCE, mockedCmd); assertThat(blameCommand.checkIfEnabled()).isFalse(); ...
public static ReduceByKey.CombineFunctionWithIdentity<Float> ofFloats() { return SUMS_OF_FLOAT; }
@Test public void testSumOfFloats() { assertEquals(6f, (float) apply(Stream.of(1f, 2f, 3f), Sums.ofFloats()), 0.001); }
public TurnServerOptions getRoutingFor( @Nonnull final UUID aci, @Nonnull final Optional<InetAddress> clientAddress, final int instanceLimit ) { try { return getRoutingForInner(aci, clientAddress, instanceLimit); } catch(Exception e) { logger.error("Failed to perform routing", e)...
@Test public void testOrderedByPerformance() throws UnknownHostException { when(performanceTable.getDatacentersFor(any(), any(), any(), any())) .thenReturn(List.of("dc-performance2", "dc-performance1")); assertThat(router().getRoutingFor(aci, Optional.of(InetAddress.getByName("0.0.0.1")), 10)) ...
public static boolean checkpw(String plaintext, String hashed) { byte[] hashed_bytes; byte[] try_bytes; String try_pw; try{ try_pw = hashpw(plaintext, hashed); } catch (Exception ignore){ // 生成密文时错误直接返回false issue#1377@Github return false; } hashed_bytes = hashed.getBytes(CharsetUtil.CHARSET_UTF...
@Test public void checkpwTest(){ assertFalse(BCrypt.checkpw("xxx", "$2a$2a$10$e4lBTlZ019KhuAFyqAlgB.Jxc6cM66GwkSR/5/xXNQuHUItPLyhzy")); }
@Override public String resolveRedirect(String requestedRedirect, ClientDetails client) throws OAuth2Exception { String redirect = super.resolveRedirect(requestedRedirect, client); if (blacklistService.isBlacklisted(redirect)) { // don't let it go through throw new InvalidRequestException("The supplied redir...
@Test(expected = InvalidRequestException.class) public void testResolveRedirect_blacklisted() { // this should fail with an error resolver.resolveRedirect(blacklistedUri, client); }
public static FieldScope fromSetFields(Message message) { return fromSetFields( message, AnyUtils.defaultTypeRegistry(), AnyUtils.defaultExtensionRegistry()); }
@Test public void testFromSetFields_iterables_unionsElements() { Message message = parse("o_int: 1 r_string: \"foo\" r_string: \"bar\""); Message diffMessage1 = parse("o_int: 2 r_string: \"foo\" r_string: \"bar\""); Message diffMessage2 = parse("o_int: 4 r_string: \"baz\" r_string: \"qux\""); expectT...
public void setProperty(String key, Object value) { setProperty(splitKey(key), value); }
@Test public void testSerDer() { runSerDer(()->{ // update main (no commit yet) manager.setProperty("framework", "llap"); manager.setProperty("ser.store", "Parquet"); manager.setProperty("ser.der.id", 42); manager.setProperty("ser.der.name", "serder"); manager.setProperty("ser....
@Description("encode value as a big endian varbinary according to IEEE 754 double-precision floating-point format") @ScalarFunction("to_ieee754_64") @SqlType(StandardTypes.VARBINARY) public static Slice toIEEE754Binary64(@SqlType(StandardTypes.DOUBLE) double value) { Slice slice = Slices.allocat...
@Test public void testToIEEE754Binary64() { assertFunction("to_ieee754_64(0.0)", VARBINARY, sqlVarbinaryHex("0000000000000000")); assertFunction("to_ieee754_64(1.0)", VARBINARY, sqlVarbinaryHex("3FF0000000000000")); assertFunction("to_ieee754_64(3.1415926)", VARBINARY, sqlVarbinaryHex("4...
public static Color fromObject(@Nonnull final Object object) { int i = object.hashCode(); float h = (i % 360) / 360f; return Color.getHSBColor(h, 1, 1); }
@Test public void fromObject() { List<Object> ASSORTED_OBJECTS = List.of("Wise Old Man", 7, true, 1.337, COLOR_ALPHA_HEXSTRING_MAP); ASSORTED_OBJECTS.forEach((object) -> { assertNotNull(ColorUtil.fromObject(object)); }); }
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromStrin...
@Test void positiveIntegerLiteral() { String inputExpression = "+10"; BaseNode number = parse( inputExpression ); assertThat( number).isInstanceOf(SignedUnaryNode.class); assertThat( number.getResultType()).isEqualTo(BuiltInType.NUMBER); assertLocation( inputExpression, numb...
static OpType getTargetOpType(final MiningFunction miningFunction) { switch (miningFunction) { case REGRESSION: return OpType.CONTINUOUS; case CLASSIFICATION: case CLUSTERING: return OpType.CATEGORICAL; default: retu...
@Test void getTargetOpType() { MiningFunction miningFunction = MiningFunction.REGRESSION; OpType retrieved = KiePMMLUtil.getTargetOpType(miningFunction); assertThat(retrieved).isEqualTo(OpType.CONTINUOUS); miningFunction = MiningFunction.CLASSIFICATION; retrieved = KiePMMLUt...
public boolean isInSonarQubeTable() { String tableName = table.toLowerCase(Locale.ENGLISH); return SqTables.TABLES.contains(tableName); }
@Test public void isInSonarQubeTable_returns_false_if_sqlazure_system_table() { ColumnDef underTest = new ColumnDef("sys.sysusers", "login", "charset", "collation", "NVARCHAR", 100L, false); assertThat(underTest.isInSonarQubeTable()).isFalse(); underTest = new ColumnDef("SYS.SYSUSERS", "login", "charset"...
@Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); }
@Test public void selfCreatedAreNotRisky() { Transaction tx = new Transaction(); tx.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0)).setSequenceNumber(1); tx.addOutput(COIN, key1); tx.setLockTime(TIMESTAMP + 86400); { // Is risky ... ...
public boolean isValid(String value) { if (value == null) { return false; } URI uri; // ensure value is a valid URI try { uri = new URI(value); } catch (URISyntaxException e) { return false; } // OK, perfom additional validatio...
@Test public void testValidator375() { UrlValidator validator = new UrlValidator(); String url = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"; assertTrue("IPv6 address URL should validate: " + url, validator.isValid(url)); url = "http://[::1]:80/index.html"; ass...
public static Collection<AndPredicate> getAndPredicates(final ExpressionSegment expression) { Collection<AndPredicate> result = new LinkedList<>(); extractAndPredicates(result, expression); return result; }
@Test void assertExtractAndPredicates() { ColumnSegment left = new ColumnSegment(26, 33, new IdentifierValue("order_id")); ParameterMarkerExpressionSegment right = new ParameterMarkerExpressionSegment(35, 35, 0); ExpressionSegment expressionSegment = new BinaryOperationExpression(26, 35, lef...
@Override public void flush(ChannelHandlerContext ctx) throws Exception { if (readInProgress) { // If there is still a read in progress we are sure we will see a channelReadComplete(...) call. Thus // we only need to flush if we reach the explicitFlushAfterFlushes limit. ...
@Test public void testFlushViaThresholdOutsideOfReadLoop() { final AtomicInteger flushCount = new AtomicInteger(); EmbeddedChannel channel = newChannel(flushCount, true); // After a given threshold, the async task should be bypassed and a flush should be triggered immediately for (in...
public String getLocation() { String location = properties.getProperty(NACOS_LOGGING_CONFIG_PROPERTY); if (StringUtils.isBlank(location)) { if (isDefaultLocationEnabled()) { return defaultLocation; } return null; } return location; ...
@Test void testGetLocationForSpecified() { properties.setProperty("nacos.logging.config", "classpath:specified-test.xml"); properties.setProperty("nacos.logging.default.config.enabled", "false"); assertEquals("classpath:specified-test.xml", loggingProperties.getLocation()); }
public static Configuration readSSLConfiguration(Configuration conf, Mode mode) { Configuration sslConf = new Configuration(false); sslConf.setBoolean(SSL_REQUIRE_CLIENT_CERT_KEY, conf.getBoolean( SSL_REQUIRE_CLIENT_CERT_KEY, SSL_REQUIRE_CLIENT_CERT_DEF...
@Test public void testNonExistSslClientXml() throws Exception{ Configuration conf = new Configuration(false); conf.setBoolean(SSL_REQUIRE_CLIENT_CERT_KEY, false); conf.set(SSL_CLIENT_CONF_KEY, "non-exist-ssl-client.xml"); Configuration sslConf = SSLFactory.readSSLConfiguration(conf, SSLFactory...
protected List<HeaderValue> parseHeaderValue(String headerValue) { return parseHeaderValue(headerValue, HEADER_VALUE_SEPARATOR, HEADER_QUALIFIER_SEPARATOR); }
@Test void headers_parseHeaderValue_headerWithPaddingButNotBase64Encoded() { AwsHttpServletRequest context = new AwsProxyHttpServletRequest(null, null, null); List<AwsHttpServletRequest.HeaderValue> result = context.parseHeaderValue("hello="); assertTrue(result.size() > 0); assertEq...
@Override public void alterTable( ObjectPath tablePath, CatalogBaseTable newCatalogTable, boolean ignoreIfNotExists) throws TableNotExistException, CatalogException { HoodieCatalogUtil.alterTable(this, tablePath, newCatalogTable, Collections.emptyList(), ignoreIfNotExists, hiveConf, this::inferTablePa...
@Test public void testAlterTable() throws Exception { Map<String, String> originOptions = new HashMap<>(); originOptions.put(FactoryUtil.CONNECTOR.key(), "hudi"); CatalogTable originTable = new CatalogTableImpl(schema, partitions, originOptions, "hudi table"); hoodieCatalog.createTable(tablePa...
public static <T> Iterator<T> limit(final Iterator<? extends T> base, final CountingPredicate<? super T> filter) { return new Iterator<>() { private T next; private boolean end; private int index = 0; @Override public boolean hasNext() { ...
@Test public void limit() { assertEquals("[0]", com.google.common.collect.Iterators.toString(Iterators.limit(asList(0, 1, 2, 3, 4).iterator(), EVEN))); assertEquals("[]", com.google.common.collect.Iterators.toString(Iterators.limit(asList(1, 2, 4, 6).iterator(), EVEN))); }
public Member getTarget() { return target; }
@Test public void testConstructor_withTarget() { Member localMember = Mockito.mock(Member.class); Member target = Mockito.mock(Member.class); WrongTargetException exception = new WrongTargetException(localMember, target, 23, 42, "WrongTargetExceptionTest"); assertEquals(target, exc...
static CapsVersionAndHash generateVerificationString(DiscoverInfoView discoverInfo) { return generateVerificationString(discoverInfo, null); }
@Test public void testComplexGenerationExample() throws XmppStringprepException { DiscoverInfo di = createComplexSamplePacket(); CapsVersionAndHash versionAndHash = EntityCapsManager.generateVerificationString(di, StringUtils.SHA1); assertEquals("q07IKJEyjvHSyhy//CH0CxmKi8w=", versionAndHas...
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) { OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers); if (filteredOpenAPI == null) { return filte...
@Test(description = "it should contain all tags in the top level OpenAPI object") public void shouldContainAllTopLevelTags() throws IOException { final OpenAPI openAPI = getOpenAPI(RESOURCE_REFERRED_SCHEMAS); final NoOpOperationsFilter filter = new NoOpOperationsFilter(); final OpenAPI filte...
@Override public IntMinimum clone() { IntMinimum clone = new IntMinimum(); clone.min = this.min; return clone; }
@Test void testClone() { IntMinimum min = new IntMinimum(); int value = 42; min.add(value); IntMinimum clone = min.clone(); assertThat(clone.getLocalValue().intValue()).isEqualTo(value); }
@Override public boolean next() throws SQLException { if (skipAll) { return false; } if (!paginationContext.getActualRowCount().isPresent()) { return getMergedResult().next(); } return rowNumber++ <= paginationContext.getActualRowCount().get() && getMe...
@Test void assertNextWithOffsetWithoutRowCount() throws SQLException { ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); when(database.getSchema(DefaultDatabase.LOGIC_NAME)).thenReturn(schema); SQLServerSelectStatement sqlStatement = new SQLServerSelec...
@Nullable @Override public <InputT> TransformEvaluator<InputT> forApplication( AppliedPTransform<?, ?, ?> application, CommittedBundle<?> inputBundle) { return (TransformEvaluator<InputT>) new ImpulseEvaluator(ctxt, (AppliedPTransform) application); }
@Test public void testImpulse() throws Exception { Pipeline p = Pipeline.create(); PCollection<byte[]> impulseOut = p.apply(Impulse.create()); AppliedPTransform<?, ?, ?> impulseApplication = DirectGraphs.getProducer(impulseOut); ImpulseEvaluatorFactory factory = new ImpulseEvaluatorFactory(context);...
@VisibleForTesting Iterator<UdfProvider> getUdfProviders(ClassLoader classLoader) throws IOException { return ServiceLoader.load(UdfProvider.class, classLoader).iterator(); }
@Test public void testClassLoaderHasNoUdfProviders() throws IOException { JavaUdfLoader udfLoader = new JavaUdfLoader(); Iterator<UdfProvider> udfProviders = udfLoader.getUdfProviders(ReflectHelpers.findClassLoader()); assertFalse(udfProviders.hasNext()); }
@Override public boolean updateTaskExecutionState(TaskExecutionStateTransition taskExecutionState) { return state.tryCall( StateWithExecutionGraph.class, stateWithExecutionGraph -> stateWithExecutionGraph.updateTaskExecutionStat...
@Test void testExceptionHistoryWithTaskFailureWithRestart() throws Exception { final Exception expectedException = new Exception("Expected Local Exception"); final Consumer<AdaptiveSchedulerBuilder> setupScheduler = builder -> builder.setRestartBackoffTimeStra...
public static XPath buildXPath(NamespaceContext namespaceContext) { XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setNamespaceContext(namespaceContext); return xPath; }
@Test public void testBuildXPath() { assertNotNull(XmlHelper.buildXPath(new CamelSpringNamespace())); }
public double compute() { return metricValue(consumer.metrics(), "io-wait-time-ns-total") + metricValue(consumer.metrics(), "io-time-ns-total") + metricValue(consumer.metrics(), "committed-time-ns-total") + metricValue(consumer.metrics(), "commit-sync-time-ns-total") ...
@Test public void shouldComputeTotalBlockedTime() { assertThat( blockedTime.compute(), equalTo(IO_TIME_TOTAL + IO_WAIT_TIME_TOTAL + COMMITTED_TIME_TOTAL + COMMIT_SYNC_TIME_TOTAL + RESTORE_IOTIME_TOTAL + RESTORE_IO_WAITTIME_TOTAL + PRODUCER_BLOCKED_TIME...
public ValidationResult isPackageConfigurationValid(String pluginId, final com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration packageConfiguration, final RepositoryConfiguration repositoryConfiguration) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_VALIDATE_PACKAGE_CON...
@Test public void shouldTalkToPluginToCheckIfPackageConfigurationIsValid() throws Exception { String expectedRequestBody = "{\"repository-configuration\":{\"key-one\":{\"value\":\"value-one\"},\"key-two\":{\"value\":\"value-two\"}}," + "\"package-configuration\":{\"key-three\":{\"value\":\"v...
@Override public void execute(Context context) { if (analysisMetadataHolder.isPullRequest() && targetInputFactory.hasTargetBranchAnalysis()) { int fixedIssuesCount = pullRequestFixedIssueRepository.getFixedIssues().size(); measureRepository.add(treeRootHolder.getRoot(), metricRepository.getByKey(CoreM...
@Test public void execute_whenNoFixedIssues_shouldCreateMeasureWithValueZero() { when(analysisMetadataHolder.isPullRequest()).thenReturn(true); when(pullRequestFixedIssueRepository.getFixedIssues()).thenReturn(Collections.emptyList()); underTest.execute(new TestComputationStepContext()); assertThat(...
@Override public Response toResponse(Throwable exception) { debugLog(exception); if (exception instanceof WebApplicationException w) { var res = w.getResponse(); if (res.getStatus() >= 500) { log(w); } return res; } if (exception instanceof AuthenticationException) {...
@Test void toResponse_authentication() { // when var res = mapper.toResponse(new AuthenticationException(null)); // then assertEquals(401, res.getStatus()); }
public static MaskRuleConfiguration convert(final Collection<MaskRuleSegment> ruleSegments) { Collection<MaskTableRuleConfiguration> tables = new LinkedList<>(); Map<String, AlgorithmConfiguration> algorithms = new HashMap<>(); for (MaskRuleSegment each : ruleSegments) { tables.add(c...
@Test void assertCovert() { MaskRuleConfiguration actual = MaskRuleStatementConverter.convert(Collections.singleton(new MaskRuleSegment("t_mask", createColumns()))); assertThat(actual.getTables().iterator().next().getName(), is("t_mask")); assertThat(actual.getTables().iterator().next().getC...
public static Mode defaults() { return new Mode(Constants.DEFAULT_FILE_SYSTEM_MODE); }
@Test public void umaskNotInteger() { String umask = "NotInteger"; mThrown.expect(IllegalArgumentException.class); mThrown.expectMessage(ExceptionMessage.INVALID_CONFIGURATION_VALUE.getMessage(umask, PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_UMASK)); ModeUtils.applyDirectoryUMask(Mode.defa...
@Override public ItemChangeSets resolve(long namespaceId, String configText, List<ItemDTO> baseItems) { Map<Integer, ItemDTO> oldLineNumMapItem = BeanUtils.mapByKey("lineNum", baseItems); Map<String, ItemDTO> oldKeyMapItem = BeanUtils.mapByKey("key", baseItems); //remove comment and blank item map. ...
@Test public void testRepeatKey() { try { resolver.resolve(1, "a=b\nb=c\nA=d\nB=e", Collections.emptyList()); } catch (Exception e) { Assert.assertTrue(e instanceof BadRequestException); } }
public RuntimeOptionsBuilder parse(String... args) { return parse(Arrays.asList(args)); }
@Test void set_monochrome_on_color_aware_formatters() { RuntimeOptions options = parser .parse("--monochrome", "--plugin", AwareFormatter.class.getName()) .build(); Plugins plugins = new Plugins(new PluginFactory(), options); plugins.setEventBusOnEventListener...
public native boolean isSandboxed();
@Test public void testIsSandboxed() { assertFalse(new Sandbox().isSandboxed()); }
@Override public Optional<Page> commit() { try { orcWriter.close(); } catch (IOException | UncheckedIOException | PrestoException e) { try { rollbackAction.call(); } catch (Exception ignored) { // ignore ...
@Test public void testPrestoExceptionPropagation() { // This test is to verify that a PrestoException thrown by the underlying data sink implementation is propagated as is OrcFileWriter orcFileWriter = createOrcFileWriter(true); try { // Throws PrestoException with STORAGE_E...
@Override public boolean isOperational() { if (nodeOperational) { return true; } boolean flag = false; try { flag = checkOperational(); } catch (InterruptedException e) { LOG.trace("Interrupted while checking ES node is operational", e); Thread.currentThread().interrupt();...
@Test public void isOperational_should_return_true_if_Elasticsearch_was_GREEN_once() { EsConnector esConnector = mock(EsConnector.class); when(esConnector.getClusterHealthStatus()).thenReturn(Optional.of(ClusterHealthStatus.GREEN)); EsManagedProcess underTest = new EsManagedProcess(mock(Process.class), Pr...
@Override public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException { final ThreadPool pool = ThreadPoolFactory.get("list", concurrency); try { final String prefix = this.createPrefix(directory); if(log.isDebugEnabl...
@Test public void testDirectoyPlaceholderWithChildren() throws Exception { final Path bucket = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); final S3AccessControlListFeature acl = new S3AccessControlListFeature(session); final Path dir...
Plugin create(Options.Plugin plugin) { try { return instantiate(plugin.pluginString(), plugin.pluginClass(), plugin.argument()); } catch (IOException | URISyntaxException e) { throw new CucumberException(e); } }
@Test void instantiates_wants_nothing_plugin() { PluginOption option = parse(WantsNothing.class.getName()); WantsNothing plugin = (WantsNothing) fc.create(option); assertThat(plugin.getClass(), is(equalTo(WantsNothing.class))); }
public void schedule(BeanContainer container, String id, String cron, String interval, String zoneId, String className, String methodName, List<JobParameter> parameterList) { JobScheduler scheduler = container.beanInstance(JobScheduler.class); String jobId = getId(id); String optionalCronExpress...
@Test void scheduleDeletesJobFromJobRunrIfIntervalExpressionIsIntervalDisabled() { final String id = "my-job-id"; final JobDetails jobDetails = jobDetails().build(); final String cron = null; final String interval = "-"; final String zoneId = null; jobRunrRecurringJo...
@Override public Object next() { if (_numberOfValuesPerEntry == 1) { return getNextNumber(); } return MultiValueGeneratorHelper.generateMultiValueEntries(_numberOfValuesPerEntry, _random, this::getNextNumber); }
@Test public void testNext() { Random random = mock(Random.class); when(random.nextInt(anyInt())).thenReturn(10); // initial value int cardinality = 5; double numValuesPerEntry = 1.0; // long generator NumberGenerator generator = new NumberGenerator(cardinality, FieldSpec.DataType.LONG, numVa...
public static String buildGlueExpression(Map<Column, Domain> partitionPredicates) { List<String> perColumnExpressions = new ArrayList<>(); int expressionLength = 0; for (Map.Entry<Column, Domain> partitionPredicate : partitionPredicates.entrySet()) { String columnName = partition...
@Test public void testDecimalConversion() { Map<Column, Domain> predicates = new PartitionFilterBuilder(HIVE_TYPE_TRANSLATOR) .addDecimalValues("col1", "10.134") .build(); String expression = buildGlueExpression(predicates); assertEquals(expression, "((col...
@Override public void validate(final String methodName, final Class<?>[] parameterTypes, final Object[] arguments) throws Exception { List<Class<?>> groups = new ArrayList<>(); Class<?> methodClass = methodClass(methodName); if (Objects.nonNull(methodClass)) { groups.add(methodCl...
@Test public void testValidateWithExistMethod() throws Exception { final URL url = URL.valueOf(MOCK_SERVICE_URL + "?shenyuValidation=org.hibernate.validator.HibernateValidator"); ApacheDubboClientValidator apacheDubboClientValidator = new ApacheDubboClientValidator(url); apacheDubboClientVal...
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testFetchingPendingPartitions() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); // normal fetch assertEquals(1, sendFetches()); client.prepareResponse(fullFetchResponse(tidp0, records, Errors.NONE, 100L, 0)); n...
public boolean shouldPreserve(FileAttribute attribute) { return preserveStatus.contains(attribute); }
@Test public void testPreserve() { DistCpOptions options = new DistCpOptions.Builder( new Path("hdfs://localhost:8020/source/first"), new Path("hdfs://localhost:8020/target/")) .build(); Assert.assertFalse(options.shouldPreserve(FileAttribute.BLOCKSIZE)); Assert.assertFalse(options...
@Override public void removeManagedLedger(String ledgerName, MetaStoreCallback<Void> callback) { log.info("[{}] Remove ManagedLedger", ledgerName); String path = PREFIX + ledgerName; store.delete(path, Optional.empty()) .thenAcceptAsync(v -> { if (log.isD...
@Test void deleteNonExistingML() throws Exception { MetaStore store = new MetaStoreImpl(metadataStore, executor); AtomicReference<MetaStoreException> exception = new AtomicReference<>(); CountDownLatch counter = new CountDownLatch(1); store.removeManagedLedger("non-existing", new M...
public void generate() throws IOException { packageNameByTypes.clear(); generatePackageInfo(); generateTypeStubs(); generateMessageHeaderStub(); for (final List<Token> tokens : ir.messages()) { final Token msgToken = tokens.get(0); final List<...
@Test void shouldGenerateRepeatingGroupCountLimits() throws Exception { generator().generate(); final String className = "CarEncoder$FuelFiguresEncoder"; final String fqClassName = ir.applicableNamespace() + "." + className; final Class<?> clazz = compile(fqClassName); ...
public boolean promptForSave() throws KettleException { List<TabMapEntry> list = delegates.tabs.getTabs(); for ( TabMapEntry mapEntry : list ) { TabItemInterface itemInterface = mapEntry.getObject(); if ( !itemInterface.canBeClosed() ) { // Show the tab tabfolder.setSelected( mapEn...
@Test public void testYesPromptToSave() throws Exception { SpoonBrowser mockBrowser = setPromptToSave( SWT.YES, false ); assertTrue( spoon.promptForSave() ); verify( mockBrowser ).applyChanges(); }
public static Object[] parseKey(HollowReadStateEngine readStateEngine, PrimaryKey primaryKey, String keyString) { /** * Split by the number of fields of the primary key. This ensures correct extraction of an empty value for the last field. * Escape the delimiter if it is preceded by a backslas...
@Test public void testParseKey() { String keyString = "a:b"; Object[] key = SearchUtils.parseKey(stateEngine, primaryKey, keyString); assertEquals(2, key.length); assertEquals("a", key[0]); assertEquals("b", key[1]); // two fields, where the second field contains a '...
@Override public SchemaAndValue toConnectData(String topic, byte[] value) { JsonNode jsonValue; // This handles a tombstone message if (value == null) { return SchemaAndValue.NULL; } try { jsonValue = deserializer.deserialize(topic, value); }...
@Test public void nullToConnect() { // When schemas are enabled, trying to decode a tombstone should be an empty envelope // the behavior is the same as when the json is "{ "schema": null, "payload": null }" // to keep compatibility with the record SchemaAndValue converted = converte...
@SuppressWarnings("FutureReturnValueIgnored") public void start() { running.set(true); configFetcher.start(); memoryMonitor.start(); streamingWorkerHarness.start(); sampler.start(); workerStatusReporter.start(); activeWorkRefresher.start(); }
@Test public void testLimitOnOutputBundleSizeWithMultipleSinks() throws Exception { // Same as testLimitOnOutputBundleSize(), but with 3 sinks for the stage rather than one. // Verifies that output bundle size has same limit even with multiple sinks. List<Integer> finalizeTracker = Lists.newArrayList(); ...
@Override public boolean isAbsentSince(AlluxioURI path, long absentSince) { MountInfo mountInfo = getMountInfo(path); if (mountInfo == null) { return false; } AlluxioURI mountBaseUri = mountInfo.getAlluxioUri(); while (path != null && !path.equals(mountBaseUri)) { Pair<Long, Long> cac...
@Test public void removePath() throws Exception { String ufsBase = "/a/b"; String alluxioBase = "/mnt" + ufsBase; // Create ufs directories assertTrue((new File(mLocalUfsPath + ufsBase)).mkdirs()); // 'base + /c' will be the first absent path process(new AlluxioURI(alluxioBase + "/c/d")); ...
public String getClientLatency() { if (!enabled) { return null; } Instant trackerStart = Instant.now(); String latencyDetails = queue.poll(); // non-blocking pop if (LOG.isDebugEnabled()) { Instant stop = Instant.now(); long elapsed = Duration.between(trackerStart, stop).toMillis...
@Test public void verifyGettingLatencyRecordsIsCheapWhenDisabled() throws Exception { // when latency tracker is disabled, we expect it to take time equivalent to checking a boolean value final double maxLatencyWhenDisabledMs = 1000; final double minLatencyWhenDisabledMs = 0; final long numTasks = 100...
@Override public PathAttributes toAttributes(final DavResource resource) { final PathAttributes attributes = super.toAttributes(resource); final Map<QName, String> properties = resource.getCustomPropsNS(); if(null != properties) { if(properties.containsKey(OC_FILEID_CUSTOM_NAMESP...
@Test public void testCustomModified_Epoch() { final NextcloudAttributesFinderFeature f = new NextcloudAttributesFinderFeature(null); final DavResource mock = mock(DavResource.class); Map<QName, String> map = new HashMap<>(); map.put(DAVTimestampFeature.LAST_MODIFIED_CUSTOM_NAMESPAC...
@Override public List<BlockWorkerInfo> getPreferredWorkers(WorkerClusterView workerClusterView, String fileId, int count) throws ResourceExhaustedException { if (workerClusterView.size() < count) { throw new ResourceExhaustedException(String.format( "Not enough workers in the cluster %d work...
@Test public void getMultipleWorkers() throws Exception { WorkerLocationPolicy policy = WorkerLocationPolicy.Factory.create(mConf); assertTrue(policy instanceof KetamaHashPolicy); // Prepare a worker list WorkerClusterView workers = new WorkerClusterView(Arrays.asList( new WorkerInfo() ...
@Override public double read() { return gaugeSource.read(); }
@Test public void whenCreatedForDynamicDoubleMetricWithProvidedValue() { DoubleGaugeImplTest.SomeObject someObject = new DoubleGaugeImplTest.SomeObject(); someObject.longField = 42; metricsRegistry.registerDynamicMetricsProvider((descriptor, context) -> context .collect(descr...
public static RawTransaction decode(final String hexTransaction) { final byte[] transaction = Numeric.hexStringToByteArray(hexTransaction); TransactionType transactionType = getTransactionType(transaction); switch (transactionType) { case EIP1559: return decodeEIP155...
@Test public void testDecoding4844() { final RawTransaction rawTransaction = createEip4844RawTransaction(); final Transaction4844 transaction4844 = (Transaction4844) rawTransaction.getTransaction(); final byte[] encodedMessage = TransactionEncoder.encode(rawTransaction); final Strin...
@Override public AppTimeoutInfo getAppTimeout(HttpServletRequest hsr, String appId, String type) throws AuthorizationException { if (type == null || type.isEmpty()) { routerMetrics.incrGetAppTimeoutFailedRetrieved(); RouterAuditLogger.logFailure(getUser().getShortUserName(), GET_APP_TIMEOUT, ...
@Test public void testGetAppTimeout() throws IOException, InterruptedException { // Generate ApplicationId information ApplicationId appId = ApplicationId.newInstance(Time.now(), 1); ApplicationSubmissionContextInfo context = new ApplicationSubmissionContextInfo(); context.setApplicationId(appId.toSt...
@SuppressWarnings("unchecked") public static int compare(Comparable lhs, Comparable rhs) { Class lhsClass = lhs.getClass(); Class rhsClass = rhs.getClass(); assert lhsClass != rhsClass; assert lhs instanceof Number; assert rhs instanceof Number; Number lhsNumber = (N...
@Test public void testCompare() { assertCompare(1L, 2, -1); assertCompare(1, 1L, 0); assertCompare(1, (short) 1, 0); assertCompare(1, (byte) 1, 0); assertCompare(1, 1.1, -1); // 1.100000000000000088817841970012523233890533447265625 < 1.10000002384185791015625 ...