focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
static Schema fromPubsubSchema(com.google.api.services.pubsub.model.Schema pubsubSchema) { if (!schemaTypeToConversionFnMap.containsKey(pubsubSchema.getType())) { throw new IllegalArgumentException( String.format( "Pub/Sub schema type %s is not supported at this time", pubsubSchema.get...
@Test public void fromPubsubSchema() { assertThrows( "null definition should throw an exception", NullPointerException.class, () -> PubsubClient.fromPubsubSchema( new com.google.api.services.pubsub.model.Schema().setType("AVRO"))); assertThrows( "nu...
public WorkflowInstanceActionResponse stop( String workflowId, long workflowInstanceId, long workflowRunId, User caller) { return terminate( workflowId, workflowInstanceId, workflowRunId, Actions.WorkflowInstanceAction.STOP, caller); }
@Test public void testStop() { when(instanceDao.tryTerminateQueuedInstance(any(), any(), any())).thenReturn(true); when(instance.getStatus()).thenReturn(WorkflowInstance.Status.CREATED); boolean res = actionHandler.stop("test-workflow", 1, 1, user).isCompleted(); assertTrue(res); verify(instanceDa...
public static ConfigurableResource parseResourceConfigValue(String value) throws AllocationConfigurationException { return parseResourceConfigValue(value, Long.MAX_VALUE); }
@Test public void testAbsoluteVcoresNegativeFractional() throws Exception { expectNegativeValueOfResource("vcores"); parseResourceConfigValue(" 5120.3 mb, -2.35 vcores "); }
@Override public void serialize(ModelLocalUriId value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeStartObject(); gen.writeStringField("model", value.model()); gen.writeStringField("basePath", decodedPath(value.basePath())); gen.writeStringField("ful...
@Test void serializeEncodedPath() throws IOException { String path = "/To+decode+first+part/To+decode+second+part/To+decode+third+part/"; LocalUri parsed = LocalUri.parse(path); ModelLocalUriId modelLocalUriId = new ModelLocalUriId(parsed); Writer jsonWriter = new StringWriter(); ...
public RegistryBuilder register(Boolean register) { this.register = register; return getThis(); }
@Test void register() { RegistryBuilder builder = new RegistryBuilder(); builder.register(true); Assertions.assertTrue(builder.build().isRegister()); }
@Override public MergedResult merge(final List<QueryResult> queryResults, final SQLStatementContext sqlStatementContext, final ShardingSphereDatabase database, final ConnectionContext connectionContext) throws SQLException { if (!(sqlStatementContext instanceof FetchStatementCo...
@Test void assertBuildTransparentMergedResult() throws SQLException { ShardingDDLResultMerger merger = new ShardingDDLResultMerger(); assertThat(merger.merge(createMultiQueryResults(), mock(SelectStatementContext.class), mock(ShardingSphereDatabase.class), mock(ConnectionContext.class)), ...
@Secured(resource = Commons.NACOS_CORE_CONTEXT_V2 + "/loader", action = ActionTypes.WRITE) @GetMapping("/reloadCurrent") public ResponseEntity<String> reloadCount(@RequestParam Integer count, @RequestParam(value = "redirectAddress", required = false) String redirectAddress) { connectionManag...
@Test void testReloadCount() { ResponseEntity<String> result = serverLoaderController.reloadCount(1, "1.1.1.1"); assertEquals("success", result.getBody()); }
public static UUnary create(Kind unaryOp, UExpression expression) { checkArgument( UNARY_OP_CODES.containsKey(unaryOp), "%s is not a recognized unary operation", unaryOp); return new AutoValue_UUnary(unaryOp, expression); }
@Test public void logicalNegation() { assertUnifiesAndInlines( "!false", UUnary.create(Kind.LOGICAL_COMPLEMENT, ULiteral.booleanLit(false))); }
@Override public void onClick(View v) { final AppCompatActivity activity = (AppCompatActivity) requireActivity(); switch (v.getId()) { case R.id.go_to_languages_action: startActivity( new Intent( Intent.ACTION_VIEW, Uri.parse(requireContext().getString...
@Test public void testGoToLanguagesOnClick() { final WizardPageDoneAndMoreSettingsFragment fragment = startFragment(); final ShadowApplication shadowApplication = Shadows.shadowOf((Application) getApplicationContext()); shadowApplication.clearNextStartedActivities(); final View clickView = fr...
public static boolean isP2WSH(Script script) { if (!isP2WH(script)) return false; List<ScriptChunk> chunks = script.chunks(); if (!chunks.get(0).equalsOpCode(OP_0)) return false; byte[] chunk1data = chunks.get(1).data; return chunk1data != null && chunk1da...
@Test public void testCreateP2WSHOutputScript() { assertTrue(ScriptPattern.isP2WSH( ScriptBuilder.createP2WSHOutputScript(new ScriptBuilder().build()) )); }
@Override public void apply(IntentOperationContext<FlowObjectiveIntent> intentOperationContext) { Objects.requireNonNull(intentOperationContext); Optional<IntentData> toUninstall = intentOperationContext.toUninstall(); Optional<IntentData> toInstall = intentOperationContext.toInstall(); ...
@Test public void testGroupChainElementMissingError() { // group chain element missing intentInstallCoordinator = new TestIntentInstallCoordinator(); installer.intentInstallCoordinator = intentInstallCoordinator; errors = ImmutableList.of(GROUPMISSING); installer.flowObjectiv...
public boolean contains(final Object value) { return contains((int)value); }
@Test void initiallyContainsNoBoxedElements() { for (int i = 0; i < 10_000; i++) { assertFalse(testSet.contains(Integer.valueOf(i))); } }
@Override public boolean rejoinNeededOrPending() { if (!subscriptions.hasAutoAssignedPartitions()) return false; // we need to rejoin if we performed the assignment and metadata has changed; // also for those owned-but-no-longer-existed partitions we should drop them as lost ...
@Test public void testNormalJoinGroupFollower() { final Set<String> subscription = singleton(topic1); final List<TopicPartition> owned = Collections.emptyList(); final List<TopicPartition> assigned = singletonList(t1p); subscriptions.subscribe(subscription, Optional.of(rebalanceList...
public boolean isGreaterThan(Version version) { return !version.isUnknown() && compareTo(version) > 0; }
@Test public void isGreaterThan() throws Exception { assertTrue(V3_0.isGreaterThan(of(2, 0))); assertFalse(V3_0.isGreaterThan(of(3, 0))); assertFalse(V3_0.isGreaterThan(of(4, 0))); }
public static Formatter forDates(@Nonnull String format) { return new DateFormat(format); }
@Test public void testDates() { Formatter f = forDates("FMDay, Mon FMDDth, FMYYYY"); check(LocalDate.of(2022, 9, 26), f, "Monday, Sep 26th, 2022"); f = forDates("FMDD FMMonth FMYYYY"); check(LocalDate.of(2022, 9, 26), f, "26 Eylül 2022", TR); f = forDates("YYYY-MM-DD FMHH:M...
public static ValueLabel formatClippedBitRate(long bytes) { return new ValueLabel(bytes * 8, BITS_UNIT).perSec().clipG(100.0); }
@Test public void formatClippedBitsMega() { vl = TopoUtils.formatClippedBitRate(3_123_123); assertEquals(AM_WL, "23.83 Mbps", vl.toString()); assertFalse(AM_CL, vl.clipped()); }
public int getInteger(HazelcastProperty property) { return Integer.parseInt(getString(property)); }
@Test public void setProperty_inheritDefaultValueOfParentProperty() { HazelcastProperty parent = new HazelcastProperty("parent", 1); HazelcastProperty child = new HazelcastProperty("child", parent); assertEquals(1, defaultProperties.getInteger(child)); }
static void verifyAddMissingValues(final List<KiePMMLMiningField> notTargetMiningFields, final PMMLRequestData requestData) { logger.debug("verifyMissingValues {} {}", notTargetMiningFields, requestData); Collection<ParameterInfo> requestParams = requestData.getReq...
@Test void verifyAddMissingValuesNotMissingReturnInvalid() { List<KiePMMLMiningField> miningFields = IntStream.range(0, 3).mapToObj(i -> { DATA_TYPE dataType = DATA_TYPE.values()[i]; return KiePMMLMiningField.builder("FIELD-" + i, null) .withDataType(dataType) ...
public static SparkAppResourceSpec buildResourceSpec( final SparkApplication app, final KubernetesClient client, final SparkAppSubmissionWorker worker) { Map<String, String> confOverrides = overrideDependencyConf(app); SparkAppResourceSpec resourceSpec = worker.getResourceSpec(app, client, con...
@Test void testBuildResourceSpecCoversBasicOverride() { SparkApplication app = new SparkApplication(); app.setMetadata( new ObjectMetaBuilder().withNamespace("foo").withName("bar-app").withUid("uid").build()); KubernetesClient mockClient = mock(KubernetesClient.class); Pod mockDriver = mock(Po...
@SuppressWarnings("checkstyle:magicnumber") public static long idFromString(String str) { if (str == null || !ID_PATTERN.matcher(str).matches()) { return -1; } str = StringUtil.removeCharacter(str, '-'); return Long.parseUnsignedLong(str, 16); }
@Test public void when_idFromString() { assertEquals(0, idFromString("0000-0000-0000-0000")); assertEquals(1, idFromString("0000-0000-0000-0001")); assertEquals(Long.MAX_VALUE, idFromString("7fff-ffff-ffff-ffff")); assertEquals(Long.MIN_VALUE, idFromString("8000-0000-0000-0000")); ...
public static void refreshSuperUserGroupsConfiguration() { //load server side configuration; refreshSuperUserGroupsConfiguration(new Configuration()); }
@Test public void testWildcardIP() { Configuration conf = new Configuration(); conf.set( DefaultImpersonationProvider.getTestProvider(). getProxySuperuserGroupConfKey(REAL_USER_NAME), StringUtils.join(",", Arrays.asList(GROUP_NAMES))); conf.set( DefaultImpersonationProvider.get...
@CanIgnoreReturnValue public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) { List<@Nullable Object> expected = (varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs); return containsExactlyElementsIn( expected, varargs != null && varargs.length == 1...
@Test public void iterableContainsExactlyWithElementsThatThrowWhenYouCallHashCodeOneMismatch() { HashCodeThrower one = new HashCodeThrower(); HashCodeThrower two = new HashCodeThrower(); expectFailureWhenTestingThat(asList(one, one)).containsExactly(one, two); }
@Override public Optional<DevOpsProjectCreator> getDevOpsProjectCreator(DbSession dbSession, Map<String, String> characteristics) { return delegates.stream() .flatMap(delegate -> delegate.getDevOpsProjectCreator(dbSession, characteristics).stream()) .findFirst(); }
@Test public void getDevOpsProjectDescriptor_whenNoDelegatesReturningACreator_shouldReturnEmptyOptional() { DelegatingDevOpsProjectCreatorFactory delegates = new DelegatingDevOpsProjectCreatorFactory(Set.of(mock(), mock())); Optional<DevOpsProjectCreator> devOpsProjectCreator = delegates.getDevOpsProjectCreat...
@Override public void setMonochrome(boolean monochrome) { formats = monochrome ? monochrome() : ansi(); }
@Test void should_print_error_message_for_after_hooks() { Feature feature = TestFeatureParser.parse("path/test.feature", "" + "Feature: feature name\n" + " Scenario: scenario name\n" + " Given first step\n"); ByteArrayOutputStream out = new ByteAr...
@Override public <T> Invoker<T> buildInvokerChain(final Invoker<T> originalInvoker, String key, String group) { Invoker<T> last = originalInvoker; URL url = originalInvoker.getUrl(); List<ModuleModel> moduleModels = getModuleModelsFromUrl(url); List<Filter> filters; if (modul...
@Test void testBuildInvokerChainForLocalReference() { DefaultFilterChainBuilder defaultFilterChainBuilder = new DefaultFilterChainBuilder(); // verify that no filter is built by default URL urlWithoutFilter = URL.valueOf("injvm://127.0.0.1/DemoService").addParameter(INTERFAC...
@Override public void setFlushBulkSize(int flushBulkSize) { }
@Test public void setFlushBulkSize() { mSensorsAPI.setFlushBulkSize(2000); Assert.assertEquals(100, mSensorsAPI.getFlushBulkSize()); }
@Override public boolean equals(CostModel otherModel) { boolean equality = false; if (this.getClass().equals(otherModel.getClass())) { equality = ((LinearBorrowingCostModel) otherModel).feePerPeriod == this.feePerPeriod; } return equality; }
@Test public void testEquality() { LinearBorrowingCostModel model = new LinearBorrowingCostModel(0.1); CostModel modelSameClass = new LinearBorrowingCostModel(0.2); CostModel modelSameFee = new LinearBorrowingCostModel(0.1); CostModel modelOther = new ZeroCostModel(); boolea...
static PythonEnvironment preparePythonEnvironment( ReadableConfig config, String entryPointScript, String tmpDir) throws IOException { PythonEnvironment env = new PythonEnvironment(); // 1. set the path of python interpreter. String pythonExec = config.getOptional(PY...
@Test void testPrepareEnvironmentWithEntryPointScript() throws IOException { File entryFile = new File(tmpDirPath + File.separator + "test.py"); // The file must actually exist entryFile.createNewFile(); String entryFilePath = entryFile.getAbsolutePath(); Configuration confi...
public static <T> AsIterable<T> asIterable() { return new AsIterable<>(); }
@Test public void testViewUnboundedAsIterableDirect() { testViewUnbounded(pipeline, View.asIterable()); }
public static int hashToIndex(int hash, int length) { checkPositive("length", length); if (hash == Integer.MIN_VALUE) { return 0; } return abs(hash) % length; }
@Test public void hashToIndex_whenHashPositive() { assertEquals(20, hashToIndex(20, 100)); assertEquals(20, hashToIndex(420, 100)); }
@Override public List<T> build(String consumer, List<T> provider) { return provider; }
@Test void testBuild() { NoneSelectorContextBuilder<Instance> contextBuilder = new NoneSelectorContextBuilder<>(); List<Instance> providers = Collections.emptyList(); assertEquals(providers, contextBuilder.build("1.1.1.1", providers)); }
static String determineOperatingSystemCompleteName() { try { useAgentTmpDirIfNecessary(); OperatingSystem os = newSystemInfo().getOperatingSystem(); return String.format("%s %s%s", os.getFamily(), os.getVersionInfo().getVersion(), ...
@Test public void shouldDisableUdevUsage() { SystemInfo.determineOperatingSystemCompleteName(); assertThat(GlobalConfig.get(OSHI_OS_LINUX_ALLOWUDEV, true)).isFalse(); }
public void queryMessage( final String addr, final QueryMessageRequestHeader requestHeader, final long timeoutMillis, final InvokeCallback invokeCallback, final Boolean isUnqiueKey ) throws RemotingException, MQBrokerException, InterruptedException { RemotingCommand r...
@Test public void testQueryMessage() throws MQBrokerException, RemotingException, InterruptedException { QueryMessageRequestHeader requestHeader = mock(QueryMessageRequestHeader.class); InvokeCallback callback = mock(InvokeCallback.class); mqClientAPI.queryMessage(defaultBrokerAddr, requestH...
public PTransform<InputT, OutputT> setDisplayData(@NonNull List<ItemSpec<?>> displayData) { this.displayData = displayData; return this; }
@Test public void testSetDisplayData() { PTransform<PCollection<String>, PCollection<String>> transform = new PTransform<PCollection<String>, PCollection<String>>() { @Override public PCollection<String> expand(PCollection<String> begin) { throw new IllegalArgumentException...
public static List<PreparableReporter> getPreparableReporters(Map<String, Object> daemonConf) { List<String> clazzes = (List<String>) daemonConf.get(DaemonConfig.STORM_DAEMON_METRICS_REPORTER_PLUGINS); List<PreparableReporter> reporterList = new ArrayList<>(); if (clazzes != null) { ...
@Test public void getPreparableReporters() { Map<String, Object> daemonConf = new HashMap<>(); List<PreparableReporter> reporters = MetricsUtils.getPreparableReporters(daemonConf); assertEquals(1, reporters.size()); assertTrue(reporters.get(0) instanceof JmxPreparableReporter); ...
public final Sink sink(final Sink sink) { return new Sink() { @Override public void write(Buffer source, long byteCount) throws IOException { boolean throwOnTimeout = false; enter(); try { sink.write(source, byteCount); throwOnTimeout = true; } catch (IOExce...
@Test public void wrappedThrowsWithTimeout() throws Exception { Sink sink = new ForwardingSink(new Buffer()) { @Override public void write(Buffer source, long byteCount) throws IOException { try { Thread.sleep(500); throw new IOException("exception and timeout"); } catch (I...
public static boolean areExceptionsPresentInChain(Throwable error, Class ... types) { while (error != null) { for (Class type : types) { if (type.isInstance(error)) { return true; } } error = error.getCause(); } ...
@Test public void testAreExceptionsPresentInChain5() { assertFalse(Exceptions.areExceptionsPresentInChain(new IllegalArgumentException(new IllegalArgumentException()), IllegalStateException.class)); }
@Override public double mean() { return (double) m * n / N; }
@Test public void testMean() { System.out.println("mean"); HyperGeometricDistribution instance = new HyperGeometricDistribution(100, 30, 70); instance.rand(); assertEquals(21, instance.mean(), 1E-7); instance = new HyperGeometricDistribution(100, 30, 80); instance.ran...
public FEELFnResult<String> invoke(@ParameterName("list") List<?> list, @ParameterName("delimiter") String delimiter) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } if (list.isEmpty()) { return ...
@Test void stringJoinFunctionEmptyList() { FunctionTestUtil.assertResult(stringJoinFunction.invoke(Collections.emptyList()), ""); FunctionTestUtil.assertResult(stringJoinFunction.invoke(Collections.emptyList(), "X"), ""); }
@SuppressWarnings("unchecked") public Chain<T> orderNodes() { List<T> chain = new ArrayList<>(); OrderedReadyNodes readyNodes = getReadyNodes(); while (!readyNodes.isEmpty() || popAllPhase(readyNodes) ) { Node candidate = readyNodes.pop(); candidate.removed(readyNod...
@Test void testRegular() throws Exception { ChainBuilder chainBuilder = createDependencyHandler(); addAtoG(chainBuilder); Chain<ChainedComponent> res = chainBuilder.orderNodes(); Iterator<ChainedComponent> i = res.components().iterator(); for (char j = 0; j < 'G' - 'A'; ++...
@Override public ConnectorPageSource createPageSource( ConnectorTransactionHandle transaction, ConnectorSession session, ConnectorSplit split, ConnectorTableLayoutHandle layout, List<ColumnHandle> columns, SplitContext splitContext, ...
@Test(expectedExceptions = PrestoException.class, expectedExceptionsMessageRegExp = "Partial aggregation pushdown is not supported when footer stats are unreliable. " + "Table testdb.table has file file://test with unreliable footer stats. " + "Set session property \\...
public static Counter upvoteCounter(MeterRegistry registry, String name) { return counter(registry, name, Tag.of(SCENE, UPVOTE_SCENE)); }
@Test void upvoteCounter() { MeterRegistry meterRegistry = new SimpleMeterRegistry(); MeterUtils.upvoteCounter(meterRegistry, "posts.content.halo.run/fake-post") .increment(2); RequiredSearch requiredSearch = meterRegistry.get("posts.content.halo.run/fake-post"); assertTh...
@Udf public String lpad( @UdfParameter(description = "String to be padded") final String input, @UdfParameter(description = "Target length") final Integer targetLen, @UdfParameter(description = "Padding string") final String padding) { if (input == null) { return null; } if (paddi...
@Test public void shouldReturnEmptyByteBufferForZeroLength() { final ByteBuffer result = udf.lpad(BYTES_123, 0, BYTES_45); assertThat(result, is(EMPTY_BYTES)); }
@Override public void rollJournal(long newName) throws JournalException { // Doesn't need to roll if current database contains no journals if (currentJournalDB.getDb().count() == 0) { return; } String currentDbName = currentJournalDB.getDb().getDatabaseName(); St...
@Test(expected = JournalException.class) public void testRollJournal(@Mocked CloseSafeDatabase closeSafeDatabase, @Mocked BDBEnvironment environment, @Mocked Database database) throws Exception { new Expectations(closeSafeDatabase) { ...
@Override public Optional<DispatchEvent> build(final DataChangedEvent event) { String instanceId = ComputeNode.getInstanceIdByComputeNode(event.getKey()); if (!Strings.isNullOrEmpty(instanceId)) { Optional<DispatchEvent> result = createInstanceDispatchEvent(event, instanceId); ...
@Test void assertCreateUpdateLabelsEvent() { Optional<DispatchEvent> actual = new ComputeNodeStateDispatchEventBuilder() .build(new DataChangedEvent("/nodes/compute_nodes/labels/foo_instance_id", YamlEngine.marshal(Arrays.asList("label_1", "label_2")), Type.UPDATED));...
@Override public long get(long key1, long key2) { return super.get0(key1, key2); }
@Test public void testGet() { final long key1 = randomKey(); final long key2 = randomKey(); final SlotAssignmentResult slot = insert(key1, key2); final long valueAddress2 = hsa.get(key1, key2); assertEquals(slot.address(), valueAddress2); }
public boolean hasMaterial(MaterialConfig materialConfig) { for (ConfigRepoConfig c : this) { if (c.getRepo().equals(materialConfig)) { return true; } } return false; }
@Test public void shouldReturnTrueThatHasMaterialWhenAddedConfigRepo() { repos.add(ConfigRepoConfig.createConfigRepoConfig(git("http://git"), "myplugin", "id")); assertThat(repos.hasMaterial(git("http://git")), is(true)); }
static boolean isValidEncodedValue(String name) { if (name.length() < 2 || name.startsWith("in_") || name.startsWith("backward_") || !isLowerLetter(name.charAt(0)) || SourceVersion.isKeyword(name)) return false; int underscoreCount = 0; for (int i = 1; i < name.lengt...
@Test public void testEncodedValueName() { for (String str : Arrays.asList("blup_test", "test", "test12", "car_test_test")) { assertTrue(isValidEncodedValue(str), str); } for (String str : Arrays.asList("Test", "12test", "test|3", "car__test", "small_car$average_speed", "tes$0",...
static JdbcIO.PreparedStatementSetCaller getPreparedStatementSetCaller( Schema.FieldType fieldType) { switch (fieldType.getTypeName()) { case ARRAY: case ITERABLE: return (element, ps, i, fieldWithIndex) -> { Collection<Object> value = element.getArray(fieldWithIndex.getIndex());...
@Test public void testGetPreparedStatementSetCaller() throws Exception { Schema wantSchema = Schema.builder() .addField("col1", Schema.FieldType.INT64) .addField("col2", Schema.FieldType.INT64) .addField("col3", Schema.FieldType.INT64) .build(); String ...
@Override public E computeIfAbsent(String key, Function<? super String, ? extends E> mappingFunction) { try { return cacheStore.invoke(key, new AtomicComputeProcessor<>(), mappingFunction); } catch (EntryProcessorException e) { throw new RuntimeException(e.getCause()); ...
@Test public void computeIfAbsent_cacheThrowsException_throwsUnwrappedEntryProcessorException() { Function<String, Integer> mappingFunction = s -> { throw new EntryProcessorException(new IllegalArgumentException()); }; doReturn(null).when(mutableEntryMock).getValue(); ent...
@Override public SchemaResult getValueSchema( final Optional<String> topicName, final Optional<Integer> schemaId, final FormatInfo expectedFormat, final SerdeFeatures serdeFeatures ) { return getSchema(topicName, schemaId, expectedFormat, serdeFeatures, false); }
@Test public void shouldReturnErrorFromGetValueSchemaIfNotFound() throws Exception { // Given: when(srClient.getLatestSchemaMetadata(any())) .thenThrow(notFoundException()); // When: final SchemaResult result = supplier.getValueSchema(Optional.of(TOPIC_NAME), Optional.empty(), expecte...
@Override public void audit(final QueryContext queryContext, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, final ShardingRule rule) { Collection<ShardingAuditStrategyConfiguration> auditStrategies = getShardingAuditStrategies(queryContext.getSqlStatementContext(), rule); ...
@Test void assertCheckFailed() { ShardingAuditAlgorithm auditAlgorithm = rule.getAuditors().get("auditor_1"); RuleMetaData globalRuleMetaData = mock(RuleMetaData.class); doThrow(new DMLWithoutShardingKeyException()).when(auditAlgorithm).check(sqlStatementContext, Collections.emptyList(), glo...
public double calculateDensity(Graph graph, boolean isGraphDirected) { double result; double edgesCount = graph.getEdgeCount(); double nodesCount = graph.getNodeCount(); double multiplier = 1; if (!isGraphDirected) { multiplier = 2; } result = (multi...
@Test public void testTwoConnectedNodesDensity() { GraphModel graphModel = GraphGenerator.generateCompleteUndirectedGraph(2); Graph graph = graphModel.getGraph(); GraphDensity d = new GraphDensity(); double density = d.calculateDensity(graph, false); assertEquals(density, 1.0...
@Override public void initialize(Map<String, String> props) { this.properties = SerializableMap.copyOf(props); this.s3FileIOProperties = new S3FileIOProperties(properties); this.createStack = PropertyUtil.propertyAsBoolean(props, "init-creation-stacktrace", true) ? Thread.currentThread...
@Test public void testResolvingFileIOLoadWithoutConf() { ResolvingFileIO resolvingFileIO = new ResolvingFileIO(); resolvingFileIO.initialize(ImmutableMap.of()); FileIO result = DynMethods.builder("io") .hiddenImpl(ResolvingFileIO.class, String.class) .build(resolvingFileIO)...
public FloatArrayAsIterable usingTolerance(double tolerance) { return new FloatArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_containsExactly_primitiveFloatArray_success() { assertThat(array(1.1f, TOLERABLE_2POINT2, 3.3f)) .usingTolerance(DEFAULT_TOLERANCE) .containsExactly(array(2.2f, 1.1f, 3.3f)); }
public boolean match(int left, int right) { return left == right; }
@Test public void integerShouldEqual() { Integer a = 334; Integer b = 334; boolean match = new NumberMatch().match(a, b); assertTrue(match); a = -123; b = -123; match = new NumberMatch().match(a, b); assertTrue(match); a = -122; b = -...
public static void addTestNode(Class<? extends ExecNode<?>> execNodeClass) { addToLookupMap(execNodeClass); }
@Test void testNoJsonCreator() { assertThatThrownBy(() -> ExecNodeMetadataUtil.addTestNode(DummyNodeNoJsonCreator.class)) .isInstanceOf(IllegalStateException.class) .hasMessage( "ExecNode: org.apache.flink.table.planner.plan.utils." ...
void handleTestStepFinished(TestStepFinished event) { if (event.getTestStep() instanceof PickleStepTestStep && event.getResult().getStatus().is(Status.PASSED)) { PickleStepTestStep testStep = (PickleStepTestStep) event.getTestStep(); addUsageEntry(event.getResult(), testStep); } ...
@Test void resultWithNullDuration() { OutputStream out = new ByteArrayOutputStream(); UsageFormatter usageFormatter = new UsageFormatter(out); PickleStepTestStep testStep = mockTestStep(); Result result = new Result(Status.PASSED, Duration.ZERO, null); usageFormatter ...
@SuppressWarnings("unchecked") @Override public ConnectResponse<List<String>> connectors() { try { LOG.debug("Issuing request to Kafka Connect at URI {} to list connectors", connectUri); final ConnectResponse<List<String>> connectResponse = withRetries(() -> Request .get(resolveUri(CONNEC...
@Test public void testList() throws JsonProcessingException { // Given: WireMock.stubFor( WireMock.get(WireMock.urlEqualTo(pathPrefix + "/connectors")) .withHeader(AUTHORIZATION.toString(), new EqualToPattern(AUTH_HEADER)) .withHeader(CUSTOM_HEADER_NAME, new EqualToPattern(CUST...
SubtaskCommittableManager<CommT> merge(SubtaskCommittableManager<CommT> other) { checkArgument(other.getSubtaskId() == this.getSubtaskId()); this.numExpectedCommittables += other.numExpectedCommittables; this.requests.addAll(other.requests); this.numDrained += other.numDrained; t...
@Test void testMerge() { final SubtaskCommittableManager<Integer> subtaskCommittableManager = new SubtaskCommittableManager<>( Collections.singletonList(new CommitRequestImpl<>(1, METRIC_GROUP)), 5, 1, ...
List<Token> tokenize() throws ScanException { List<Token> tokenList = new ArrayList<Token>(); StringBuilder buf = new StringBuilder(); while (pointer < patternLength) { char c = pattern.charAt(pointer); pointer++; switch (state) { case LITERAL_ST...
@Test public void simleVariable() throws ScanException { String input = "${abc}"; Tokenizer tokenizer = new Tokenizer(input); List<Token> tokenList = tokenizer.tokenize(); witnessList.add(Token.START_TOKEN); witnessList.add(new Token(Token.Type.LITERAL, "abc")); witne...
@Override public Local create(final Path file) { return this.create(new UUIDRandomStringService().random(), file); }
@Test public void testVersion() { final String temp = StringUtils.removeEnd(System.getProperty("java.io.tmpdir"), File.separator); final String s = System.getProperty("file.separator"); { final Path file = new Path("/p/f", EnumSet.of(Path.Type.file)); file.attributes(...
@Override public Schema getSourceSchema() { return sourceSchema; }
@Test public void renameBadlyFormattedSchemaTest() throws IOException { TypedProperties props = Helpers.setupSchemaOnDFS("streamer-config", "file_schema_provider_invalid.avsc"); props.put(SANITIZE_SCHEMA_FIELD_NAMES.key(), "true"); this.schemaProvider = new FilebasedSchemaProvider(props, jsc); assertE...
public VplsConfig vplsFromIface(String iface) { for (VplsConfig vpls : vplss()) { if (vpls.isAttached(iface)) { return vpls; } } return null; }
@Test public void getVplsFromInterface() { assertNotNull("VPLS not found", vplsAppConfig.vplsFromIface(IF1)); assertNull("VPLS unexpectedly found", vplsAppConfig.vplsFromIface(IF_NON_EXIST)); }
public static Builder builder() { return new Builder(); }
@Test public void processingHintsForbiddenInContentElementPayload() { assertThrows(IllegalArgumentException.class, () -> ContentElement.builder().addPayloadItem(StoreHint.INSTANCE)); }
@Override public SendResult send(final Message message) { return send(message, this.rocketmqProducer.getSendMsgTimeout()); }
@Test public void testSend_Not_OK() throws InterruptedException, RemotingException, MQClientException, MQBrokerException { SendResult sendResult = new SendResult(); sendResult.setSendStatus(SendStatus.FLUSH_DISK_TIMEOUT); when(rocketmqProducer.send(any(Message.class), anyLong())).thenReturn...
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldFindPreferredOneArgWithCast() { // Given: final KsqlScalarFunction[] functions = new KsqlScalarFunction[]{ function(OTHER, -1, LONG), function(EXPECTED, -1, INT), function(OTHER, -1, DOUBLE) }; Arrays.stream(functions).forEach(udfIndex::addFunction); ...
public List<HistoryKey> getCurrentHistory() { if (mLoadedKeys.size() == 0) // For a unknown reason, we cannot have 0 history emoji... mLoadedKeys.add(new HistoryKey(DEFAULT_EMOJI, DEFAULT_EMOJI)); return Collections.unmodifiableList(mLoadedKeys); }
@Test public void testLoad() { mSharedPreferences .getString(R.string.settings_key_quick_text_history, R.string.settings_default_empty) .set("1,2,3,4,5,6"); mUnderTest = new QuickKeyHistoryRecords(mSharedPreferences); List<QuickKeyHistoryRecords.HistoryKey> keys = mUnderTest.getCurrentHist...
@Override public FilteredMessage apply(Message msg) { try (var ignored = executionTime.time()) { return doApply(msg); } }
@Test void applyWithFilter(MessageFactory messageFactory) { final var filterRules = List.of( RuleDao.builder() .id("668cff8ed9f9636b4b629c29") .title("[668cff8ed9f9636b4b629c29] Test Filter 1") .source(""" ...
@PUT @Timed @Path("{configClass}") @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Update configuration in database") @RequiresPermissions({RestPermissions.CLUSTER_CONFIG_ENTRY_CREATE, RestPermissions.CLUSTER_CONFIG_ENTRY_EDIT}) @AuditEvent(type = AuditEventTypes.CLUSTER_CONFIGURATI...
@Test void putClassConsideredUnsafe(@TempDir Path tmpDir) throws IOException { final Path file = tmpDir.resolve("secrets.txt"); Files.writeString(file, "secret content"); final ClusterConfigResource resource = new ClusterConfigResource(clusterConfigService, new RestrictedCha...
public static MySQLCommandPacket newInstance(final MySQLCommandPacketType commandPacketType, final MySQLPacketPayload payload, final ConnectionSession connectionSession) { switch (commandPacketType) { case COM_QUIT: return new MySQLCom...
@Test void assertNewInstanceWithComCreateDbPacket() { assertThat(MySQLCommandPacketFactory.newInstance(MySQLCommandPacketType.COM_CREATE_DB, payload, connectionSession), instanceOf(MySQLUnsupportedCommandPacket.class)); }
Token<DelegationTokenIdentifier> delegationToken() throws IOException { String delegation = param(DelegationParam.NAME); if (delegation == null) { return null; } final Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>(); token.decodeFromUrlString(delegation); ...
@Test public void testDeserializeHAToken() throws IOException { Configuration conf = DFSTestUtil.newHAConfiguration(LOGICAL_NAME); final Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>(); QueryStringDecoder decoder = new QueryStringDecoder( WebHdfsHandler.WEBHDF...
public static int ipToInt(String ip) { try { return bytesToInt(ipToBytesByInet(ip)); } catch (Exception e) { throw new IllegalArgumentException(ip + " is invalid IP"); } }
@Test void testIpToInt() { assertEquals(2130706433, InternetAddressUtil.ipToInt("127.0.0.1")); assertEquals(-1062731775, InternetAddressUtil.ipToInt("192.168.0.1")); }
@Override public void writeTo(MysqlSerializer serializer) { MysqlCapability capability = CAPABILITY; if (supportSSL) { capability = new MysqlCapability(capability.getFlags() | MysqlCapability.Flag.CLIENT_SSL.getFlagBit()); } serializer.writeInt1(PROTO...
@Test public void testWrite() { MysqlHandshakePacket packet = new MysqlHandshakePacket(1090, false); MysqlSerializer serializer = MysqlSerializer.newInstance(capability); packet.writeTo(serializer); ByteBuffer buffer = serializer.toByteBuffer(); // assert protocol version ...
@Override protected int getJDBCPort() { return PostgreSQLContainer.POSTGRESQL_PORT; }
@Test public void testGetJDBCPortReturnsCorrectValue() { assertThat(testManager.getJDBCPort()).isEqualTo(PostgreSQLContainer.POSTGRESQL_PORT); }
@Override @Nullable public ExecutionGraphInfo get(JobID jobId) { try { return executionGraphInfoCache.get(jobId); } catch (ExecutionException e) { LOG.debug( "Could not load archived execution graph information for job id {}.", jobId, e); r...
@Test public void testUnknownGet() throws IOException { final File rootDir = temporaryFolder.newFolder(); try (final FileExecutionGraphInfoStore executionGraphStore = createDefaultExecutionGraphInfoStore( rootDir, new ScheduledExecutor...
public PolicyGenerator(Configuration conf, GPGContext context) { setConf(conf); init(context); }
@Test public void testPolicyGenerator() throws YarnException { policyGenerator = new TestablePolicyGenerator(); policyGenerator.setPolicy(mock(GlobalPolicy.class)); policyGenerator.run(); verify(policyGenerator.getPolicy(), times(1)) .updatePolicy("default", clusterInfos, null); verify(pol...
@Override public SendResult send( Message msg) throws MQClientException, RemotingException, MQBrokerException, InterruptedException { msg.setTopic(withNamespace(msg.getTopic())); if (this.getAutoBatch() && !(msg instanceof MessageBatch)) { return sendByAccumulator(msg, null, null...
@Test public void testSendMessage_NoNameSrv() throws RemotingException, InterruptedException, MQBrokerException { when(mQClientAPIImpl.getNameServerAddressList()).thenReturn(new ArrayList<>()); try { producer.send(message); failBecauseExceptionWasNotThrown(MQClientException.c...
@Override public KeyValueIterator<Windowed<Bytes>, byte[]> fetch(final Bytes key) { return wrapped().fetch(key); }
@Test public void shouldDelegateToUnderlyingStoreWhenFetching() { store.fetch(bytesKey); verify(inner).fetch(bytesKey); }
@Override public void onError(final Exception e) { LOG.error("websocket server[{}] is error.....", getURI(), e); }
@Test public void testOnError() { shenyuWebsocketClient = spy(shenyuWebsocketClient); Assertions.assertDoesNotThrow(() -> shenyuWebsocketClient.onError(new ShenyuException("test"))); }
@Override public EncodedMessage transform(ActiveMQMessage message) throws Exception { if (message == null) { return null; } long messageFormat = 0; Header header = null; Properties properties = null; Map<Symbol, Object> daMap = null; Map<Symbol, O...
@Test public void testConvertTextMessageToAmqpMessageWithNoBodyOriginalEncodingWasNull() throws Exception { ActiveMQTextMessage outbound = createTextMessage(); outbound.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_NULL); outbound.onSend(); outbound.storeContent(); JMSMa...
public <T> List<T> fromCurrentList(final String json, final Class<T> clazz) { return GSON.fromJson(json, TypeToken.getParameterized(CopyOnWriteArrayList.class, clazz).getType()); }
@Test public void testFromCurrentList() { Map<String, Object> map = ImmutableMap.of("id", "123", "name", "test", "data", "测试"); List<Map<String, Object>> list = ImmutableList.of(ImmutableMap.copyOf(map), ImmutableMap.copyOf(map), ImmutableMap.copyOf(map)); String json = "[{\"...
public static Builder custom() { return new Builder(); }
@Test(expected = IllegalArgumentException.class) public void testBuildWithIllegalMaxWait() { ThreadPoolBulkheadConfig.custom() .keepAliveDuration(Duration.ofMillis(-1)) .build(); }
public static Message parse(String in) { Message message = new Message(); if (in.startsWith("@")) { String[] tags = in.substring(1) .split(";"); for (String tag : tags) { int eq = tag.indexOf('='); if (eq == -1) continue; String key = tag.substring(0, eq); String value = tag.substri...
@Test public void testParse() { Message message = Message.parse("@badges=subscriber/0;color=;display-name=kappa_kid_;emotes=;id=6539b42a-e945-4a83-a5b7-018149ca9fa7;mod=0;room-id=27107346;subscriber=1;tmi-sent-ts=1535926830652;turbo=0;user-id=33390095;user-type= :kappa_kid_!kappa_kid_@kappa_kid_.tmi.twitch.tv PRIVM...
@Override public String loopbackEthOnu(String target) { DriverHandler handler = handler(); NetconfController controller = handler.get(NetconfController.class); MastershipService mastershipService = handler.get(MastershipService.class); DeviceId ncDeviceId = handler.data().deviceId();...
@Test public void testInvalidEthLoopbackOnuInput() throws Exception { String target; String reply; for (int i = ZERO; i < INVALID_ETHPORT_LOOPBACK_TCS.length; i++) { target = INVALID_ETHPORT_LOOPBACK_TCS[i]; reply = voltConfig.loopbackEthOnu(target); asse...
public boolean isNumGroupsLimitReached() { return _brokerResponse.has(NUM_GROUPS_LIMIT_REACHED) && _brokerResponse.get(NUM_GROUPS_LIMIT_REACHED).asBoolean(); }
@Test public void testIsNumGroupsLimitReached() { // Run the test final boolean result = _executionStatsUnderTest.isNumGroupsLimitReached(); // Verify the results assertTrue(result); }
public void appendDocument(PDDocument destination, PDDocument source) throws IOException { if (source.getDocument().isClosed()) { throw new IOException("Error: source PDF is closed."); } if (destination.getDocument().isClosed()) { throw new IOException...
@Test void testMergeBogusStructParents2() throws IOException { PDFMergerUtility pdfMergerUtility = new PDFMergerUtility(); try (PDDocument src = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4408.pdf")); PDDocument dst = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4408.pdf"))) ...
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
@Test public void copyMessages() { MessageIdsResponse response = bot.execute(new CopyMessages(chatId, chatId, new int[]{forwardMessageId}) .messageThreadId(0) .removeCaption(true) .disableNotification(true) .protectContent(true) ); ...
@Override public ParameterType<?> parameterType() { return parameterType; }
@Test void can_define_parameter_type_converters_with_one_capture_group() throws NoSuchMethodException { Method method = JavaParameterTypeDefinitionTest.class.getMethod("convert_one_capture_group_to_string", String.class); JavaParameterTypeDefinition definition = new JavaParameterTypeDefi...
@SuppressWarnings({"unchecked", "rawtypes"}) @Override public @Nullable <InputT> TransformEvaluator<InputT> forApplication( AppliedPTransform<?, ?, ?> application, CommittedBundle<?> inputBundle) throws IOException { return createEvaluator((AppliedPTransform) application); }
@Test public void boundedSourceEvaluatorProducesDynamicSplits() throws Exception { BoundedReadEvaluatorFactory factory = new BoundedReadEvaluatorFactory(context, options, 0L); when(context.createRootBundle()).thenReturn(bundleFactory.createRootBundle()); int numElements = 10; Long[] elems = new Long[...
@Override public boolean intersects(PointList pointList) { // similar code to LocationIndexTree.checkAdjacent int len = pointList.size(); if (len == 0) throw new IllegalArgumentException("PointList must not be empty"); double tmpLat = pointList.getLat(0); double ...
@Test public void testIntersectCircleBBox() { assertTrue(new Circle(10, 10, 120000).intersects(new BBox(9, 11, 8, 9))); assertFalse(new Circle(10, 10, 110000).intersects(new BBox(9, 11, 8, 9))); }
@SuppressWarnings("unchecked") @Override public void configure(Map<String, ?> configs, boolean isKey) { if (inner != null) { log.error("Could not configure ListSerializer as the parameter has already been set -- inner: {}", inner); throw new ConfigException("List serializer was a...
@Test public void testListKeySerializerNoArgConstructorsShouldThrowKafkaExceptionDueInvalidClass() { props.put(CommonClientConfigs.DEFAULT_LIST_KEY_SERDE_INNER_CLASS, new FakeObject()); final KafkaException exception = assertThrows( KafkaException.class, () -> listSerializer....
public synchronized TopologyDescription describe() { return internalTopologyBuilder.describe(); }
@Test public void tableNamedMaterializedCountShouldPreserveTopologyStructure() { final StreamsBuilder builder = new StreamsBuilder(); builder.table("input-topic") .groupBy((key, value) -> null) .count(Materialized.<Object, Long, KeyValueStore<Bytes, byte[]>>as("count-store") ...
@Override public void filter(final ContainerRequestContext request, final ContainerResponseContext response) throws IOException { String id = Optional.ofNullable(request.getHeaderString(REQUEST_ID)) .filter(header -> !header.isEmpty()) .orElseGet(() -> generateRandomUuid...
@Test void addsRandomRequestIdHeader() throws Exception { requestIdFilter.filter(request, response); String requestId = (String) headers.getFirst("X-Request-Id"); assertThat(requestId).isNotNull(); assertThat(UUID.fromString(requestId)).isNotNull(); verify(logger).trace("me...
public static boolean validKey(final String key) { return VALID_KEY_CHARS.matcher(key).matches(); }
@Test public void testValidKeys() throws Exception { assertTrue(Message.validKey("foo123")); assertTrue(Message.validKey("foo-bar123")); assertTrue(Message.validKey("foo_bar123")); assertTrue(Message.validKey("foo.bar123")); assertTrue(Message.validKey("foo@bar")); as...
@VisibleForTesting static Pattern convertToPattern(String scopeOrNameComponent) { final String[] split = scopeOrNameComponent.split(LIST_DELIMITER); final String rawPattern = Arrays.stream(split) .map(s -> s.replaceAll("\\.", "\\.")) ....
@Test void testConvertToPatternMultiple() { final Pattern pattern = DefaultMetricFilter.convertToPattern("numRecords*,numBytes*"); assertThat(pattern.toString()).isEqualTo("(numRecords.*|numBytes.*)"); assertThat(pattern.matcher("numRecordsIn").matches()).isTrue(); assertThat(pattern...
public static ShowResultSet execute(ShowStmt statement, ConnectContext context) { return GlobalStateMgr.getCurrentState().getShowExecutor().showExecutorVisitor.visit(statement, context); }
@Test public void testShowVariable2() throws AnalysisException, DdlException { ShowVariablesStmt stmt = new ShowVariablesStmt(SetType.VERBOSE, null); ShowResultSet resultSet = ShowExecutor.execute(stmt, ctx); Assert.assertEquals(4, resultSet.getMetaData().getColumnCount()); Assert.a...
public synchronized Topology addSource(final String name, final String... topics) { internalTopologyBuilder.addSource(null, name, null, null, null, topics); return this; }
@Test public void shouldNotAllowZeroTopicsWhenAddingSource() { assertThrows(TopologyException.class, () -> topology.addSource("source")); }
public static CreateSourceProperties from(final Map<String, Literal> literals) { try { return new CreateSourceProperties(literals, DurationParser::parse, false); } catch (final ConfigException e) { final String message = e.getMessage().replace( "configuration", "property" )...
@Test public void shouldThrowIfKeyFormatAndFormatProvided() { // When: final Exception e = assertThrows( KsqlException.class, () -> CreateSourceProperties.from( ImmutableMap.<String, Literal>builder() .putAll(MINIMUM_VALID_PROPS) .put(KEY_FORMAT_PROP...
public String transform() throws ScanException { StringBuilder stringBuilder = new StringBuilder(); compileNode(node, stringBuilder, new Stack<Node>()); return stringBuilder.toString(); }
@Test public void nestedVariable() throws ScanException { String input = "a${k${zero}}b"; Node node = makeNode(input); NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); assertEquals("av0b", nodeToStringTransformer.transform()); }