focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public Schema addToSchema(Schema schema) { validate(schema); schema.addProp(LOGICAL_TYPE_PROP, name); schema.setLogicalType(this); return schema; }
@Test void decimalFixedPrecisionLimit() { // 4 bytes can hold up to 9 digits of precision final Schema schema = Schema.createFixed("aDecimal", null, null, 4); assertThrows("Should reject precision", IllegalArgumentException.class, "fixed(4) cannot store 10 digits (max 9)", () -> { Logica...
@Override public LookupResult<BrokerKey> handleResponse(Set<BrokerKey> keys, AbstractResponse abstractResponse) { validateLookupKeys(keys); MetadataResponse response = (MetadataResponse) abstractResponse; MetadataResponseData.MetadataResponseBrokerCollection brokers = response.data().broker...
@Test public void testHandleResponseWithNoBrokers() { AllBrokersStrategy strategy = new AllBrokersStrategy(logContext); MetadataResponseData response = new MetadataResponseData(); AdminApiLookupStrategy.LookupResult<AllBrokersStrategy.BrokerKey> lookupResult = strategy.handleResponse( ...
@Override public ServletStream stream() { return stream; }
@Test public void flushBuffer_bufferIsFlushed() throws IOException { underTest.stream().flushBuffer(); verify(response).flushBuffer(); }
public static void checkAndThrowAttributeValue(String value) throws IOException { if (value == null) { return; } else if (value.trim().length() > MAX_LABEL_LENGTH) { throw new IOException("Attribute value added exceeds " + MAX_LABEL_LENGTH + " character(s)"); } value = value...
@Test void testAttributeValueAddition() { String[] values = new String[]{"1_8", "1.8", "ABZ", "ABZ", "az", "a-z", "a_z", "123456789"}; for (String val : values) { try { NodeLabelUtil.checkAndThrowAttributeValue(val); } catch (Exception e) { fail("Valid values fo...
@SuppressWarnings("deprecation") public static String encodeHex(byte[] data) { int l = data.length; byte[] out = new byte[l << 1]; for (int i = 0; i < l; i++) { byte b = data[i]; int j = i << 1; out[j] = DIGITS_LOWER[((0xF0 & b) >>> 4)]; out[...
@Test public void testEncodeHex() { assertEquals("", Hex.encodeHex(new byte[0])); assertEquals("00", Hex.encodeHex(new byte[1])); assertEquals("00000000", Hex.encodeHex(new byte[4])); assertEquals("10a3d1ff", Hex.encodeHex(new byte[]{0x10, (byte) 0xa3, (byte) 0xd1, (byte) 0xff})); ...
public static String stripInstanceAndHost(String metricsName) { String[] pieces = metricsName.split("\\."); int len = pieces.length; if (len <= 1) { return metricsName; } // Master metrics doesn't have hostname included. if (!pieces[0].equals(MetricsSystem.InstanceType.MASTER.toString()) ...
@Test public void stripInstanceAndHostTest() { assertEquals("name", MetricsSystem.stripInstanceAndHost("Master.name")); assertEquals("name", MetricsSystem.stripInstanceAndHost("Worker.name.10_0_0_136")); assertEquals("name.UFS:ufs", MetricsSystem.stripInstanceAndHost("Client.name.UFS:ufs.0_0_0_0")); a...
@Override public void callExtensionPoint( LogChannelInterface logChannelInterface, Object o ) throws KettleException { AbstractMeta abstractMeta = (AbstractMeta) o; final EmbeddedMetaStore embeddedMetaStore = abstractMeta.getEmbeddedMetaStore(); RunConfigurationManager embeddedRunConfigurationManager = ...
@Test public void testCallExtensionPoint() throws Exception { runConfigurationImportExtensionPoint.callExtensionPoint( log, abstractMeta ); verify( abstractMeta ).getEmbeddedMetaStore(); }
@Override public Response submitApplication(ApplicationSubmissionContextInfo newApp, HttpServletRequest hsr) throws AuthorizationException, IOException, InterruptedException { long startTime = clock.getTime(); // We verify the parameters to ensure that newApp is not empty and // that the format of...
@Test public void testSubmitApplication() throws YarnException, IOException, InterruptedException { ApplicationId appId = ApplicationId.newInstance(Time.now(), 1); ApplicationSubmissionContextInfo context = new ApplicationSubmissionContextInfo(); context.setApplicationId(appId.toSt...
@Override public String convert(ILoggingEvent event) { List<KeyValuePair> kvpList = event.getKeyValuePairs(); if (kvpList == null || kvpList.isEmpty()) { return CoreConstants.EMPTY_STRING; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < kvpList.siz...
@Test public void testWithOnelKVP() { event.addKeyValuePair(new KeyValuePair("k", "v")); String result = converter.convert(event); assertEquals("k=\"v\"", result); }
@Override protected void rename( List<LocalResourceId> srcResourceIds, List<LocalResourceId> destResourceIds, MoveOptions... moveOptions) throws IOException { if (moveOptions.length > 0) { throw new UnsupportedOperationException("Support for move options is not yet implemented."); ...
@Test public void testMoveFilesWithException() throws Exception { Path srcPath1 = temporaryFolder.newFile().toPath(); Path srcPath2 = temporaryFolder.newFile().toPath(); Path destPath1 = temporaryFolder.getRoot().toPath().resolve("nonexistentdir").resolve("dest1"); Path destPath2 = srcPath2.resolveSi...
public String convertToPrintFriendlyString(String phiString) { if (null == phiString) { return NULL_REPLACEMENT_VALUE; } else if (phiString.isEmpty()) { return EMPTY_REPLACEMENT_VALUE; } int conversionLength = (logPhiMaxBytes > 0) ? Integer.min(phiString.length()...
@Test public void testConvertToPrintFriendlyStringWithPhiMaxBytes() { Hl7Util local = new Hl7Util(3, LOG_PHI_TRUE); String result = local.convertToPrintFriendlyString(TEST_MESSAGE); assertEquals("MSH", result); }
public static ParamType getSchemaFromType(final Type type) { return getSchemaFromType(type, JAVA_TO_ARG_TYPE); }
@Test public void shouldGetDecimalSchemaForBigDecimalClass() { assertThat( UdfUtil.getSchemaFromType(BigDecimal.class), is(ParamTypes.DECIMAL) ); }
@Override public void renameSnapshot(Path path, String snapshotOldName, String snapshotNewName) throws IOException { super.renameSnapshot(fullPath(path), snapshotOldName, snapshotNewName); }
@Test(timeout = 30000) public void testRenameSnapshot() throws Exception { Path snapRootPath = new Path("/snapPath"); Path chRootedSnapRootPath = new Path("/a/b/snapPath"); Configuration conf = new Configuration(); conf.setClass("fs.mockfs.impl", MockFileSystem.class, FileSystem.class); URI chro...
@Nullable public synchronized Beacon track(@NonNull Beacon beacon) { Beacon trackedBeacon = null; if (beacon.isMultiFrameBeacon() || beacon.getServiceUuid() != -1) { trackedBeacon = trackGattBeacon(beacon); } else { trackedBeacon = beacon; } re...
@Test public void gattBeaconExtraDataIsNotReturned() { Beacon extraDataBeacon = getGattBeaconExtraData(); ExtraDataBeaconTracker tracker = new ExtraDataBeaconTracker(); Beacon trackedBeacon = tracker.track(extraDataBeacon); assertNull("trackedBeacon should be null", trackedBeacon); ...
public SqlType getExpressionSqlType(final Expression expression) { return getExpressionSqlType(expression, Collections.emptyMap()); }
@Test public void shouldProcessDateLiteral() { assertThat(expressionTypeManager.getExpressionSqlType(new DateLiteral(new Date(86400000))), is(SqlTypes.DATE)); }
@Override public Object[] toArray() { Object[] array = new Object[size]; for (int i = 0; i < size; i++) { array[i] = i; } return array; }
@Test public void toArray() throws Exception { RangeSet rs = new RangeSet(4); Object[] array = rs.toArray(); assertEquals(4, array.length); assertEquals(0, array[0]); assertEquals(1, array[1]); assertEquals(2, array[2]); assertEquals(3, array[3]); }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ComplexResourceKey<?, ?> other = (ComplexResourceKey<?, ?>) obj; // Key cannot be null return key.equals(other.key) ...
@Test public void testEquals() throws CloneNotSupportedException { DataMap keyMap = new DataMap(); keyMap.put("keyField1", "keyValue1"); EmptyRecord key1 = new EmptyRecord(keyMap); DataMap paramMap = new DataMap(); paramMap.put("paramField1", "paramValue1"); EmptyRecord param1 = new EmptyRec...
@Override public synchronized DefaultConnectClient get( final Optional<String> ksqlAuthHeader, final List<Entry<String, String>> incomingRequestHeaders, final Optional<KsqlPrincipal> userPrincipal ) { if (defaultConnectAuthHeader == null) { defaultConnectAuthHeader = buildDefaultAuthHead...
@Test public void shouldNotFailOnMissingCredentials() { // Given: givenCustomBasicAuthHeader(); // no credentials file present // When: final DefaultConnectClient connectClient = connectClientFactory.get(Optional.empty(), Collections.emptyList(), Optional.empty()); // Then: asser...
public static GitVersion parse(String versionFromConsoleOutput) { String[] lines = versionFromConsoleOutput.split("\n"); String firstLine = lines[0]; Matcher m = GIT_VERSION_PATTERN.matcher(firstLine); if (m.find()) { try { return new GitVersion(parseVersion(m...
@Test public void shouldThowExceptionWhenGitVersionCannotBeParsed() { String invalidGitVersion = "git version ga5ed0asdasd.ga5ed0"; assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> GitVersion.parse(invalidGitVersion)) .withMessage("cannot parse git ...
@CanIgnoreReturnValue @Override public V put(K key, V value) { if (key == null) { throw new NullPointerException("key == null"); } if (value == null && !allowNullValues) { throw new NullPointerException("value == null"); } Node<K, V> created = find(key, true); V result = created....
@Test public void testEqualsAndHashCode() throws Exception { LinkedTreeMap<String, Integer> map1 = new LinkedTreeMap<>(); map1.put("A", 1); map1.put("B", 2); map1.put("C", 3); map1.put("D", 4); LinkedTreeMap<String, Integer> map2 = new LinkedTreeMap<>(); map2.put("C", 3); map2.put("B"...
public <ConfigType extends ConfigInstance> ConfigType toInstance(Class<ConfigType> clazz, String configId) { return ConfigInstanceUtil.getNewInstance(clazz, configId, this); }
@Test public void non_existent_struct_in_array_of_struct_in_payload_is_ignored() { Slime slime = new Slime(); Cursor nestedArrEntry = slime.setObject().setArray("nestedarr").addObject(); addStructFields(nestedArrEntry.setObject("inner"), "existing", "MALE", null); addStructFields(nes...
public static PositionBound at(final Position position) { return new PositionBound(position); }
@Test public void shouldEqualPosition() { final PositionBound bound1 = PositionBound.at(Position.emptyPosition()); final PositionBound bound2 = PositionBound.at(Position.emptyPosition()); assertEquals(bound1, bound2); }
public Encoding encode(String text) { return encode(text, Language.UNKNOWN); }
@Test void truncates_to_max_length() throws IOException { int maxLength = 3; var builder = new HuggingFaceTokenizer.Builder() .addDefaultModel(decompressModelFile(tmp, "bert-base-uncased")) .setMaxLength(maxLength) .setTruncation(true); String ...
@Override public Byte getByte(K name) { return null; }
@Test public void testGetByte() { assertNull(HEADERS.getByte("name1")); }
public Stream<Hit> stream() { if (nPostingLists == 0) { return Stream.empty(); } return StreamSupport.stream(new PredicateSpliterator(), false); }
@Test void requireThatMinFeatureIsUsedToPruneResults() { PredicateSearch search = createPredicateSearch( new byte[]{3, 1}, postingList( SubqueryBitmap.ALL_SUBQUERIES, entry(0, 0x000100ff), entry(1, 0x0001...
public String generateError(String error) { Map<String, String> values = ImmutableMap.of( PARAMETER_TOTAL_WIDTH, valueOf(MARGIN + computeWidth(error) + MARGIN), PARAMETER_LABEL, error); StringSubstitutor strSubstitutor = new StringSubstitutor(values); return strSubstitutor.replace(errorTemplate)...
@Test public void generate_error() { initSvgGenerator(); String result = underTest.generateError("Error"); assertThat(result).contains("<text", ">Error</text>"); }
public static CacheStats empty() { return EMPTY_STATS; }
@Test public void empty() { var stats = CacheStats.of(0, 0, 0, 0, 0, 0, 0); checkStats(stats, 0, 0, 1.0, 0, 0.0, 0, 0, 0.0, 0, 0, 0.0, 0, 0); assertThat(stats).isEqualTo(CacheStats.empty()); assertThat(stats.equals(null)).isFalse(); assertThat(stats).isNotEqualTo(new Object()); assertThat(sta...
public boolean eval(ContentFile<?> file) { // TODO: detect the case where a column is missing from the file using file's max field id. return new MetricsEvalVisitor().eval(file); }
@Test public void testMissingStats() { DataFile missingStats = new TestDataFile("file.parquet", Row.of(), 50); Expression[] exprs = new Expression[] { lessThan("no_stats", 5), lessThanOrEqual("no_stats", 30), equal("no_stats", 70), greaterThan("no_stats", 78), ...
@Override public ExecuteContext before(ExecuteContext context) { if (!(context.getObject() instanceof Builder)) { return context; } init(); Builder builder = (Builder) context.getObject(); Optional<Object> filters = ReflectUtils.getFieldValue(builder, "filters"); ...
@Test public void testBefore() { // When no filter exists interceptor.before(context); List<ExchangeFilterFunction> list = (List<ExchangeFilterFunction>) ReflectUtils .getFieldValue(builder, "filters").orElse(null); Assert.assertNotNull(list); Assert.assertTru...
private static String getProperty(String name, Configuration configuration) { return Optional.of(configuration.getStringArray(relaxPropertyName(name))) .filter(values -> values.length > 0) .map(Arrays::stream) .map(stream -> stream.collect(Collectors.joining(","))) .orElse(null);...
@Test public void assertPropertiesFromFSSpec() { Map<String, String> configs = new HashMap<>(); configs.put("config.property.1", "val1"); configs.put("config.property.2", "val2"); configs.put("config.property.3", "val3"); PinotFSSpec pinotFSSpec = new PinotFSSpec(); pinotFSSpec.setConfigs(con...
@Override public boolean setProperties(Namespace namespace, Map<String, String> properties) throws NoSuchNamespaceException { if (!namespaceExists(namespace)) { throw new NoSuchNamespaceException("Namespace does not exist: %s", namespace); } Preconditions.checkNotNull(properties, "Invalid pro...
@Test public void testSetProperties() { Namespace testNamespace = Namespace.of("testDb", "ns1", "ns2"); Map<String, String> testMetadata = ImmutableMap.of("key_1", "value_1", "key_2", "value_2", "key_3", "value_3"); catalog.createNamespace(testNamespace, testMetadata); // Add more properties ...
@Override public int hashCode() { return value ? Boolean.TRUE.hashCode() : Boolean.FALSE.hashCode(); }
@Test void requireThatHashCodeIsImplemented() { assertEquals(new BooleanPredicate(true).hashCode(), new BooleanPredicate(true).hashCode()); assertEquals(new BooleanPredicate(false).hashCode(), new BooleanPredicate(false).hashCode()); }
String upload(File report) { LOG.debug("Upload report"); long startTime = System.currentTimeMillis(); Part filePart = new Part(MediaTypes.ZIP, report); PostRequest post = new PostRequest("api/ce/submit") .setMediaType(MediaTypes.PROTOBUF) .setParam("projectKey", moduleHierarchy.root().key())...
@Test public void send_pull_request_characteristic() throws Exception { String branchName = "feature"; String pullRequestId = "pr-123"; when(branchConfiguration.branchName()).thenReturn(branchName); when(branchConfiguration.branchType()).thenReturn(PULL_REQUEST); when(branchConfiguration.pullReque...
@Override public ResultSet getIndexInfo(final String catalog, final String schema, final String table, final boolean unique, final boolean approximate) { return null; }
@Test void assertGetIndexInfo() { assertNull(metaData.getIndexInfo("", "", "", false, false)); }
@Override public String serviceToUrl(String protocol, String serviceId, String tag, String requestKey) { if(StringUtils.isBlank(serviceId)) { logger.debug("The serviceId cannot be blank"); return null; } URL url = loadBalance.select(discovery(protocol, serviceId, tag)...
@Test public void testServiceToSingleUrlWithEnv() { String s = cluster.serviceToUrl("https", "com.networknt.chainwriter-1.0.0", "0000", null); Assert.assertTrue("https://localhost:8444".equals(s)); }
@Override public <VO, VR> KStream<K, VR> leftJoin(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return leftJoin(otherStream, toValueJoinerWi...
@SuppressWarnings("deprecation") @Test public void shouldNotAllowNullValueJoinerOnLeftJoinWithStreamJoined() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.leftJoin( testStream, (ValueJoiner<? su...
@Udf public int field( @UdfParameter final String str, @UdfParameter final String... args ) { if (str == null || args == null) { return 0; } for (int i = 0; i < args.length; i++) { if (str.equals(args[i])) { return i + 1; } } return 0; }
@Test public void shouldFindArgumentWhenOneIsNull() { // When: final int pos = field.field("world", null, "world"); // Then: assertThat(pos, equalTo(2)); }
Future<RecordMetadata> send(final ProducerRecord<byte[], byte[]> record, final Callback callback) { maybeBeginTransaction(); try { return producer.send(record, callback); } catch (final KafkaException uncaughtException) { if (isRecoverable(...
@Test public void shouldFailOnMaybeBeginTransactionIfTransactionsNotInitializedForExactlyOnceAlpha() { final StreamsProducer streamsProducer = new StreamsProducer( eosAlphaConfig, "threadId", eosAlphaMockClientSupplier, new TaskId(0...
public void submit() { //Transmit information to our transfer object to communicate between layers saveToWorker(); //call the service layer to register our worker service.registerWorker(worker); //check for any errors if (worker.getNotification().hasErrors()) { indicateErrors(); LOG...
@Test void submitSuccessfully() { // Ensure the worker is null initially registerWorkerForm = new RegisterWorkerForm("John Doe", "Engineer", LocalDate.of(1990, 1, 1)); assertNull(registerWorkerForm.worker); // Submit the form registerWorkerForm.submit(); // Verify ...
@VisibleForTesting static Optional<String> getChildValue(@Nullable Xpp3Dom dom, String... childNodePath) { if (dom == null) { return Optional.empty(); } Xpp3Dom node = dom; for (String child : childNodePath) { node = node.getChild(child); if (node == null) { return Optional....
@Test public void testGetChildValue_childPathMatched() { Xpp3Dom root = newXpp3Dom("root", "value"); Xpp3Dom foo = addXpp3DomChild(root, "foo", "foo"); addXpp3DomChild(foo, "bar", "bar"); assertThat(MavenProjectProperties.getChildValue(root, "foo")).isEqualTo(Optional.of("foo")); assertThat(Maven...
@Override public double distanceBtw(Point p1, Point p2) { numCalls++; confirmRequiredDataIsPresent(p1); confirmRequiredDataIsPresent(p2); Duration timeDelta = Duration.between(p1.time(), p2.time()); //can be positive of negative timeDelta = timeDelta.abs(); Double...
@Test public void testPointsRequireAltitude() { PointDistanceMetric metric = new PointDistanceMetric(1.0, 1.0); Point point = new PointBuilder() .latLong(0.0, 0.0) .time(Instant.EPOCH) .build(); assertThrows( IllegalArgumentException.class, ...
public void start(ProxyService service) { extensions.values().forEach(extension -> extension.start(service)); }
@Test public void testStart() { ProxyService service = mock(ProxyService.class); extensions.start(service); verify(extension1, times(1)).start(same(service)); verify(extension2, times(1)).start(same(service)); }
@Override public String format(final Schema schema) { final String converted = SchemaWalker.visit(schema, new Converter()) + typePostFix(schema); return options.contains(Option.AS_COLUMN_LIST) ? stripTopLevelStruct(converted) : converted; }
@Test public void shouldFormatOptionalInt() { assertThat(DEFAULT.format(Schema.OPTIONAL_INT32_SCHEMA), is("INT")); assertThat(STRICT.format(Schema.OPTIONAL_INT32_SCHEMA), is("INT")); }
@Override public <X> Object wrap(X value, WrapperOptions options) { if (value == null) { return null; } Blob blob = null; Clob clob = null; if (Blob.class.isAssignableFrom(value.getClass())) { blob = options.getLobCreator().wrap((Blob) value); ...
@Test public void testNullPropertyType() { JsonTypeDescriptor descriptor = new JsonTypeDescriptor(); try { descriptor.wrap("a", null); fail("Should fail because the propertyType is null!"); } catch (HibernateException expected) { } }
@Override public void readLine(String line) { if (line.startsWith("#") || line.isEmpty()) { return; } // In some cases, ARIN may have multiple results with different NetType values. When that happens, // we want to use the data from the entry with the data closest to t...
@Test public void testRunRedirect() throws Exception { ARINResponseParser parser = new ARINResponseParser(); for (String line : REDIRECT_TO_RIPENCC.split("\n")) { parser.readLine(line); } assertTrue(parser.isRedirect()); assertEquals(InternetRegistry.RIPENCC, par...
public static String fix(final String raw) { if ( raw == null || "".equals( raw.trim() )) { return raw; } MacroProcessor macroProcessor = new MacroProcessor(); macroProcessor.setMacros( macros ); return macroProcessor.parse( raw ); }
@Test public void testLeaveAssertLogicalAlone() { final String original = "drools.insertLogical(foo)"; assertEqualsIgnoreWhitespace( original, KnowledgeHelperFixerTest.fixer.fix( original ) ); }
public static Expression generateFilterExpression(SearchArgument sarg) { return translate(sarg.getExpression(), sarg.getLeaves()); }
@Test public void testFloatType() { SearchArgument.Builder builder = SearchArgumentFactory.newBuilder(); SearchArgument arg = builder.startAnd().equals("float", PredicateLeaf.Type.FLOAT, 1200D).end().build(); UnboundPredicate expected = Expressions.equal("float", 1200D); UnboundPredicate actual = (Un...
@Override protected int entrySize() { return ENTRY_SIZE; }
@Test public void testEntrySize() { assertEquals(12, idx.entrySize()); }
public List<Long> allWindows() { return getWindowList(_oldestWindowIndex, _currentWindowIndex); }
@Test public void testAllWindows() { MetricSampleAggregator<String, IntegerEntity> aggregator = new MetricSampleAggregator<>(NUM_WINDOWS, WINDOW_MS, MIN_SAMPLES_PER_WINDOW, 0, _metricDef); assertTrue(aggregator.allWindows().isEmpty()); CruiseControlUnitTestUtil...
public boolean isUsingAloneCoupon() { return this.policy.isCanUseAlone(); }
@Test void 독자_사용_쿠폰이면_true를_반환한다() { // given Coupon coupon = 쿠픈_생성_독자_사용_할인율_10_퍼센트(); // when boolean result = coupon.isUsingAloneCoupon(); // then assertThat(result).isTrue(); }
@Override public int hashCode() { return keyData.hashCode(); }
@Test public void testHashCode() { CachedQueryEntry entry = createEntry("key"); assertEquals(entry.hashCode(), entry.hashCode()); }
public boolean sync() throws IOException { if (!preSyncCheck()) { return false; } if (!getAllDiffs()) { return false; } List<Path> sourcePaths = context.getSourcePaths(); final Path sourceDir = sourcePaths.get(0); final Path targetDir = context.getTargetPath(); final FileSy...
@Test public void testFallback() throws Exception { // the source/target dir are not snapshottable dir Assert.assertFalse(sync()); // make sure the source path has been updated to the snapshot path final Path spath = new Path(source, HdfsConstants.DOT_SNAPSHOT_DIR + Path.SEPARATOR + "s2"); ...
@Override public GetApplicationAttemptReportResponse getApplicationAttemptReport( GetApplicationAttemptReportRequest request) throws YarnException, IOException { if (request == null || request.getApplicationAttemptId() == null || request.getApplicationAttemptId().getApplicationId() == nul...
@Test public void testGetApplicationAttemptReport() throws YarnException, IOException, InterruptedException { LOG.info("Test FederationClientInterceptor: Get ApplicationAttempt Report."); ApplicationId appId = ApplicationId.newInstance(System.currentTimeMillis(), 1); SubmitApplicationR...
public ModelMBeanInfo getMBeanInfo(Object defaultManagedBean, Object customManagedBean, String objectName) throws JMException { if ((defaultManagedBean == null && customManagedBean == null) || objectName == null) return null; // skip proxy classes if (defaultManagedBean != null && P...
@Test(expected = IllegalArgumentException.class) public void testAttributeSetterNameNotCapitial() throws JMException { mbeanInfoAssembler.getMBeanInfo(new BadAttributeSetterNameNotCapital(), null, "someName"); }
@Produces @DefaultBean @Singleton JobRunrDashboardWebServer dashboardWebServer(StorageProvider storageProvider, JsonMapper jobRunrJsonMapper, JobRunrDashboardWebServerConfiguration dashboardWebServerConfiguration) { if (jobRunrBuildTimeConfiguration.dashboard().enabled()) { return new Jo...
@Test void dashboardWebServerIsSetupWhenConfigured() { when(dashboardBuildTimeConfiguration.enabled()).thenReturn(true); assertThat(jobRunrProducer.dashboardWebServer(storageProvider, jsonMapper, usingStandardDashboardConfiguration())).isNotNull(); }
public static boolean isCompositeType(LogicalType logicalType) { if (logicalType instanceof DistinctType) { return isCompositeType(((DistinctType) logicalType).getSourceType()); } LogicalTypeRoot typeRoot = logicalType.getTypeRoot(); return typeRoot == STRUCTURED_TYPE || typ...
@Test void testIsCompositeTypeSimpleType() { DataType dataType = DataTypes.TIMESTAMP(); assertThat(LogicalTypeChecks.isCompositeType(dataType.getLogicalType())).isFalse(); }
@Override public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException { for(Path file : files.keySet()) { callback.delete(file); try { if(file.attributes().isDuplicate()) { ...
@Test public void testDeleteFolderRoomWithContent() throws Exception { final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session); final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(new Path( new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.dire...
@Override public void execute( RunConfiguration runConfiguration, ExecutionConfiguration executionConfiguration, AbstractMeta meta, VariableSpace variableSpace, Repository repository ) throws KettleException { DefaultRunConfiguration defaultRunConfiguration = (DefaultRunConfiguration) runCo...
@Test public void testExecuteClusteredTrans() throws Exception { DefaultRunConfiguration defaultRunConfiguration = new DefaultRunConfiguration(); defaultRunConfiguration.setName( "Default Configuration" ); defaultRunConfiguration.setLocal( false ); defaultRunConfiguration.setRemote( false ); defau...
@Override public void commit(Collection<CommitRequest<FileSinkCommittable>> requests) throws IOException, InterruptedException { for (CommitRequest<FileSinkCommittable> request : requests) { FileSinkCommittable committable = request.getCommittable(); if (committable.hasPe...
@Test void testCleanupInProgressFiles() throws Exception { StubBucketWriter stubBucketWriter = new StubBucketWriter(); FileCommitter fileCommitter = new FileCommitter(stubBucketWriter); MockCommitRequest<FileSinkCommittable> fileSinkCommittable = new MockCommitRequest<>( ...
@Override protected ObjectPermissions getPermissions() { return mPermissions.get(); }
@Test public void getPermissionsWithMapping() throws Exception { Map<PropertyKey, Object> conf = new HashMap<>(); conf.put(PropertyKey.UNDERFS_S3_OWNER_ID_TO_USERNAME_MAPPING, "111=altname"); try (Closeable c = new ConfigurationRule(conf, CONF).toResource()) { S3AUnderFileSystem s3UnderFileSystem = ...
public AbstractRequestBuilder<K, V, R> setReqParam(String key, Object value) { ArgumentUtil.notNull(value, "value"); return setParam(key, value); }
@Test(expectedExceptions = NullPointerException.class) public void testSetReqParamWithNullValue() { final AbstractRequestBuilder<?, ?, ?> builder = new DummyAbstractRequestBuilder(); builder.setReqParam("a", null); }
@Override public void close() { close(Duration.ofMillis(Long.MAX_VALUE)); }
@Test @SuppressWarnings("deprecation") public void testExplicitlyOnlyEnableClientTelemetryReporter() { Properties props = new Properties(); props.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9999"); props.setProperty(ProducerConfig.AUTO_INCLUDE_JMX_REPORTER_CONFIG, "fa...
public static long getUsableMemory() { return getMaxMemory() - getTotalMemory() + getFreeMemory(); }
@Test public void getUsableMemoryTest(){ assertTrue(RuntimeUtil.getUsableMemory() > 0); }
public Optional<Session> login(@Nullable String currentSessionId, String host, ActorAwareAuthenticationToken authToken) throws AuthenticationServiceUnavailableException { final String previousSessionId = StringUtils.defaultIfBlank(currentSessionId, null); final Subjec...
@Test public void serviceUnavailableStateIsCleared() { setUpUserMock(); assertFalse(SecurityUtils.getSubject().isAuthenticated()); final AtomicBoolean doThrow = new AtomicBoolean(true); final SimpleAccountRealm switchableRealm = new SimpleAccountRealm() { @Override ...
@Override public ShardingSphereUser swapToObject(final YamlUserConfiguration yamlConfig) { if (null == yamlConfig) { return null; } Grantee grantee = convertYamlUserToGrantee(yamlConfig.getUser()); return new ShardingSphereUser(grantee.getUsername(), yamlConfig.getPasswor...
@Test void assertSwapToNullObject() { assertNull(new YamlUserSwapper().swapToObject(null)); }
public AnalysisPropertyDto setValue(String value) { requireNonNull(value, "value cannot be null"); this.value = value; return this; }
@Test void null_value_should_throw_NPE() { underTest = new AnalysisPropertyDto(); assertThatThrownBy(() -> underTest.setValue(null)) .isInstanceOf(NullPointerException.class) .hasMessage("value cannot be null"); }
@Override public Catalog createCatalog(Context context) { final FactoryUtil.CatalogFactoryHelper helper = FactoryUtil.createCatalogFactoryHelper(this, context); helper.validate(); return new HiveCatalog( context.getName(), helper.getOptions()....
@Test public void testCreateHiveCatalogWithIllegalHadoopConfDir() throws IOException { final String catalogName = "mycatalog"; final String hadoopConfDir = tempFolder.newFolder().getAbsolutePath(); final Map<String, String> options = new HashMap<>(); options.put(CommonCatalogOptions...
@Override public Enumeration<URL> getResources(String name) throws IOException { final List<URL> urls = new ArrayList<>(); for (ClassLoader classLoader : classLoaders) { final Enumeration<URL> resources = classLoader.getResources(name); if (resources.hasMoreElements()) { ...
@Test public void getResourcesReturnsEmptyEnumerationIfResourceDoesNotExist() throws Exception { final ChainingClassLoader chainingClassLoader = new ChainingClassLoader(getClass().getClassLoader()); final Enumeration<URL> resources = chainingClassLoader.getResources("ThisClassHopeFullyDoesNotExist" ...
public IssueSyncProgress getIssueSyncProgress(DbSession dbSession) { int completedCount = dbClient.projectDao().countIndexedProjects(dbSession); int total = dbClient.projectDao().countProjects(dbSession); boolean hasFailures = dbClient.ceActivityDao().hasAnyFailedOrCancelledIssueSyncTask(dbSession); boo...
@Test public void return_is_completed_true_if_pending_task_exist_but_all_branches_have_been_synced() { insertCeQueue("TASK_1", Status.PENDING); // only project IntStream.range(0, 10).forEach(value -> insertProjectWithBranches(false, 0)); // project + additional branch IntStream.range(0, 10).forEa...
public boolean existsNotCreatedStep() { return totalStepCount > getCreatedStepCount(); }
@Test public void testExistsNotCreatedStep() throws Exception { WorkflowRuntimeOverview overview = loadObject( "fixtures/instances/sample-workflow-runtime-overview.json", WorkflowRuntimeOverview.class); assertFalse(overview.existsNotCreatedStep()); overview.setTotalStepCou...
@Override public HttpHeaders set(HttpHeaders headers) { if (headers instanceof DefaultHttpHeaders) { this.headers.set(((DefaultHttpHeaders) headers).headers); return this; } else { return super.set(headers); } }
@Test public void testSetNullHeaderValueValidate() { final HttpHeaders headers = new DefaultHttpHeaders(true); assertThrows(NullPointerException.class, new Executable() { @Override public void execute() { headers.set(of("test"), (CharSequence) null); ...
public synchronized void flush() { try { output().flush(); } catch (IOException e) { handleIOException(e); } }
@Test public void flush_streamIsFlushed() throws IOException { underTest.flush(); verify(outputStream, Mockito.only()).flush(); }
public Calendar ceil(long t) { Calendar cal = new GregorianCalendar(Locale.US); cal.setTimeInMillis(t); return ceil(cal); }
@Test public void hashedMinute() throws Exception { long t = new GregorianCalendar(2013, Calendar.MARCH, 21, 16, 21).getTimeInMillis(); compare(new GregorianCalendar(2013, Calendar.MARCH, 21, 17, 56), new CronTab("H 17 * * *", Hash.from("stuff")).ceil(t)); compare(new GregorianCalendar(2013, Cal...
@Implementation public static synchronized Dialog getErrorDialog( int errorCode, Activity activity, int requestCode) { return googlePlayServicesUtilImpl.getErrorDialog(errorCode, activity, requestCode); }
@Test public void getErrorDialog() { assertNotNull( GooglePlayServicesUtil.getErrorDialog(ConnectionResult.SERVICE_MISSING, new Activity(), 0)); assertNull(GooglePlayServicesUtil.getErrorDialog(ConnectionResult.SUCCESS, new Activity(), 0)); assertNotNull( GooglePlayServicesUtil.getErrorDia...
@Override public double getStdDev() { // two-pass algorithm for variance, avoids numeric overflow if (values.length <= 1) { return 0; } final double mean = getMean(); double sum = 0; for (long value : values) { final double diff = value - me...
@Test public void calculatesTheStdDev() throws Exception { assertThat(snapshot.getStdDev()) .isEqualTo(1.5811, offset(0.0001)); }
@Override public int hashCode() { return Long.hashCode(bps); }
@Test public void testHashCode() { Long expected = (one * 1000); assertEquals(small.hashCode(), expected.hashCode()); }
public boolean assign(DefaultIssue issue, @Nullable UserDto user, IssueChangeContext context) { String assigneeUuid = user != null ? user.getUuid() : null; if (!Objects.equals(assigneeUuid, issue.assignee())) { String newAssigneeName = user == null ? null : user.getName(); issue.setFieldChange(conte...
@Test void unassign() { issue.setAssigneeUuid("user_uuid"); boolean updated = underTest.assign(issue, null, context); assertThat(updated).isTrue(); assertThat(issue.assignee()).isNull(); assertThat(issue.mustSendNotifications()).isTrue(); FieldDiffs.Diff diff = issue.currentChange().get(ASSIGN...
@Override public void doAlarm(List<AlarmMessage> alarmMessages) throws Exception { Map<String, WechatSettings> settingsMap = alarmRulesWatcher.getWechatSettings(); if (settingsMap == null || settingsMap.isEmpty()) { return; } Map<String, List<AlarmMessage>> groupedMessag...
@Test public void testWechatWebhook() throws Exception { List<String> remoteEndpoints = new ArrayList<>(); remoteEndpoints.add("http://127.0.0.1:" + SERVER.httpPort() + "/wechathook/receiveAlarm"); Rules rules = new Rules(); String template = "{\"msgtype\":\"text\",\"text\":{\"conten...
@Override public AttributedList<Path> read(final Path directory, final List<String> replies) throws FTPInvalidListException { final AttributedList<Path> children = new AttributedList<>(); if(replies.isEmpty()) { return children; } // At least one entry successfully parsed...
@Test public void testSkipParentDir() throws Exception { Path path = new Path( "/www", EnumSet.of(Path.Type.directory)); String[] replies = new String[]{ "Type=pdir;Unique=aaaaacUYqaaa;Perm=cpmel; /", "Type=pdir;Unique=aaaaacUYqaaa;Perm=cpmel; ..", ...
@Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { super.onDataReceived(device, data); if (data.size() < 3) { onInvalidDataReceived(device, data); return; } final int opCode = data.getIntValue(Data.FORMAT_UINT8, 0); if (opCode != OP_CODE_NUMBER_OF_...
@Test public void onRecordAccessOperationError_invalidOperand() { final Data data = new Data(new byte[] { 6, 0, 1, 5 }); callback.onDataReceived(null, data); assertEquals(5, error); }
@Override public ByteOrder getByteOrder() { return ByteOrder.nativeOrder(); }
@Override @Test public void testGetByteOrder() { assertEquals(ByteOrder.nativeOrder(), in.getByteOrder()); }
@Override public void pre(SpanAdapter span, Exchange exchange, Endpoint endpoint) { super.pre(span, exchange, endpoint); span.setTag(TagConstants.DB_SYSTEM, CASSANDRA_DB_TYPE); URI uri = URI.create(endpoint.getEndpointUri()); if (uri.getPath() != null && !uri.getPath().isEmpty()) { ...
@Test public void testPreCqlFromHeader() { String cql = "select * from users"; Endpoint endpoint = Mockito.mock(Endpoint.class); Exchange exchange = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(endpoint.getEndpointUri()).thenRetu...
public char toChar(String name) { return toChar(name, '\u0000'); }
@Test public void testToChar_String() { System.out.println("toChar"); char expResult; char result; Properties props = new Properties(); props.put("value1", "f"); props.put("value2", "w"); props.put("empty", ""); props.put("str", "abc"); props....
@Override public TypeDefinition build( ProcessingEnvironment processingEnv, PrimitiveType type, Map<String, TypeDefinition> typeCache) { TypeDefinition typeDefinition = new TypeDefinition(type.toString()); return typeDefinition; }
@Test void testBuild() { buildAndAssertTypeDefinition(processingEnv, zField, builder); buildAndAssertTypeDefinition(processingEnv, bField, builder); buildAndAssertTypeDefinition(processingEnv, cField, builder); buildAndAssertTypeDefinition(processingEnv, sField, builder); bui...
public static <T> RedistributeArbitrarily<T> arbitrarily() { return new RedistributeArbitrarily<>(null, false); }
@Test @Category({ValidatesRunner.class, UsesTestStream.class}) public void testRedistributeWithTimestampsStreaming() { TestStream<Long> stream = TestStream.create(VarLongCoder.of()) .advanceWatermarkTo(new Instant(0L).plus(Duration.standardDays(48L))) .addElements( ...
static long appendRecords( Logger log, ControllerResult<?> result, int maxRecordsPerBatch, Function<List<ApiMessageAndVersion>, Long> appender ) { try { List<ApiMessageAndVersion> records = result.records(); if (result.isAtomic()) { // ...
@Test public void testAppendRecords() { TestAppender appender = new TestAppender(); assertEquals(5, QuorumController.appendRecords(log, ControllerResult.of(Arrays.asList(rec(0), rec(1), rec(2), rec(3), rec(4)), null), 2, appender)); }
@Override @Transactional(rollbackFor = Exception.class) public void updateFileConfigMaster(Long id) { // 校验存在 validateFileConfigExists(id); // 更新其它为非 master fileConfigMapper.updateBatch(new FileConfigDO().setMaster(false)); // 更新 fileConfigMapper.updateById(new Fi...
@Test public void testUpdateFileConfigMaster_success() { // mock 数据 FileConfigDO dbFileConfig = randomFileConfigDO().setMaster(false); fileConfigMapper.insert(dbFileConfig);// @Sql: 先插入出一条存在的数据 FileConfigDO masterFileConfig = randomFileConfigDO().setMaster(true); fileConfigMa...
public LogicalSchema resolve(final ExecutionStep<?> step, final LogicalSchema schema) { return Optional.ofNullable(HANDLERS.get(step.getClass())) .map(h -> h.handle(this, schema, step)) .orElseThrow(() -> new IllegalStateException("Unhandled step class: " + step.getClass())); }
@Test public void shouldResolveSchemaForTableSelectWithColumnNames() { // Given: final TableSelect<?> step = new TableSelect<>( PROPERTIES, tableSource, ImmutableList.of(ColumnName.of("NEW_KEY")), ImmutableList.of( add("JUICE", "ORANGE", "APPLE"), ref("P...
@Override void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException { // PostgreSQL does not have concept of case-sensitive collation. Only charset ("encoding" in postgresql terminology) // must be verified. expectUtf8AsDefault(connection); if (state == DatabaseCharse...
@Test public void upgrade_fails_if_non_utf8_column() throws Exception { // default charset is ok but two columns are not answerDefaultCharset("utf8"); answerColumns(asList( new String[] {TABLE_ISSUES, COLUMN_KEE, "utf8"}, new String[] {TABLE_PROJECTS, COLUMN_KEE, "latin"}, new String[] {...
public Optional<TableDistribution> mergeDistribution( MergingStrategy mergingStrategy, Optional<TableDistribution> sourceTableDistribution, Optional<TableDistribution> derivedTabledDistribution) { if (derivedTabledDistribution.isPresent() && sourceTableDistri...
@Test void mergeDistributionFromBaseTable() { Optional<TableDistribution> sourceDistribution = Optional.of(TableDistribution.ofHash(Collections.singletonList("a"), 3)); Optional<TableDistribution> mergePartitions = util.mergeDistribution( getDe...
@Override public DubboServerRequest request() { return request; }
@Test void request() { assertThat(response.request()).isSameAs(request); }
public static Builder builder(Type type) { return new Builder(type); }
@Test public void set_uuid_throws_NPE_if_component_arg_is_Null() { assertThatThrownBy(() -> builder(FILE).setKey(null)) .isInstanceOf(NullPointerException.class); }
public static StatementExecutorResponse execute( final ConfiguredStatement<ListQueries> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final RemoteHostExecutor remoteHostExecutor = RemoteHostExecuto...
@Test public void shouldNotMergeDifferentRunningQueries() { // Given when(sessionProperties.getInternalRequest()).thenReturn(false); final ConfiguredStatement<?> showQueries = engine.configure("SHOW QUERIES;"); final PersistentQueryMetadata localMetadata = givenPersistentQuery("id", RUNNING_QUERY_STAT...
@SuppressWarnings("rawtypes") @Deprecated public synchronized Topology addProcessor(final String name, final org.apache.kafka.streams.processor.ProcessorSupplier supplier, final String... parentNames) { return ad...
@Test public void shouldNotAllowNullProcessorSupplierWhenAddingProcessor() { assertThrows(NullPointerException.class, () -> topology.addProcessor("name", (ProcessorSupplier<Object, Object, Object, Object>) null)); }
public static void activateParams( VariableSpace childVariableSpace, NamedParams childNamedParams, VariableSpace parent, String[] listParameters, String[] mappingVariables, String[] inputFields ) { activateParams( childVariableSpace, childNamedParams, parent, listParameters, ...
@Test public void activateParamsTestWithNoParameterChild() throws Exception { String newParam = "newParamParent"; String parentValue = "parentValue"; TransMeta parentMeta = new TransMeta(); TransMeta childVariableSpace = new TransMeta(); String[] parameters = childVariableSpace.listParameters();...
protected String generateQueryString(MultiValuedTreeMap<String, String> parameters, boolean encode, String encodeCharset) throws ServletException { if (parameters == null || parameters.isEmpty()) { return null; } if (queryString != null) { return queryString; ...
@Test void queryString_generateQueryString_nullParameterIsEmpty() { AwsProxyHttpServletRequest request = new AwsProxyHttpServletRequest(queryStringNullValue, mockContext, null, config); String parsedString = null; try { parsedString = request.generateQueryString(request.getAwsPro...
@Override public void filter(ContainerRequestContext requestContext) { if (isInternalRequest(requestContext)) { log.trace("Skipping authentication for internal request"); return; } try { log.debug("Authenticating request"); BasicAuthCredential...
@Test public void testBadPassword() throws IOException { File credentialFile = setupPropertyLoginFile(true); JaasBasicAuthFilter jaasBasicAuthFilter = setupJaasFilter("KafkaConnect", credentialFile.getPath()); ContainerRequestContext requestContext = setMock("Basic", "user", "password1"); ...
public Nutrients calculateNutrients(BigDecimal grams) { if (grams == null || grams.doubleValue() <= 0) { return Nutrients.createEmptyNutrients(); } return new Nutrients(calculateCalories(grams), calculateCarbohydrates(grams), calculateProteins(grams), ...
@Test void calculateNutrients_nullValue() { Nutrients result = product.calculateNutrients(null); assertAll("Should return empty nutrients", () -> assertEquals(new BigDecimal("0"), result.getCalories().getTotalCalories()), () -> assertEquals(new BigDecimal("0"), result...
public static void main(String[] args) { if (args.length < 1 || args[0].equals("-h") || args[0].equals("--help")) { System.out.println(usage); return; } // Copy args, because CommandFormat mutates the list. List<String> argsList = new ArrayList<String>(Arrays.asList(args)); CommandForma...
@Test public void testHelpShort() { Classpath.main(new String[] { "-h" }); String strOut = new String(stdout.toByteArray(), UTF8); assertTrue(strOut.contains("Prints the classpath")); assertTrue(stderr.toByteArray().length == 0); }
public static String roundStr(double v, int scale) { return round(v, scale).toPlainString(); }
@Test public void roundStrTest() { final String roundStr = NumberUtil.roundStr(2.647, 2); assertEquals(roundStr, "2.65"); final String roundStr1 = NumberUtil.roundStr(0, 10); assertEquals(roundStr1, "0.0000000000"); }