focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public boolean retryRequest( HttpRequest request, IOException exception, int execCount, HttpContext context) { if (execCount > maxRetries) { // Do not retry if over max retries return false; } if (nonRetriableExceptions.contains(exception.getClass())) { return false; ...
@Test public void noRetryOnConnect() { HttpGet request = new HttpGet("/"); assertThat(retryStrategy.retryRequest(request, new ConnectException(), 1, null)).isFalse(); }
@Override public Iterable<DiscoveryNode> discoverNodes() { try { Collection<AzureAddress> azureAddresses = azureClient.getAddresses(); logAzureAddresses(azureAddresses); List<DiscoveryNode> result = new ArrayList<>(); for (AzureAddress azureAddress : azureAddr...
@Test public void discoverNodes() { // given AzureAddress azureAddress1 = new AzureAddress("192.168.1.15", "38.146.24.2"); AzureAddress azureAddress2 = new AzureAddress("192.168.1.16", "38.146.28.15"); given(azureClient.getAddresses()).willReturn(asList(azureAddress1, azureAddress2))...
private void watchConfigKeyValues(final String watchPathRoot, final BiConsumer<String, String> updateHandler, final Consumer<String> deleteHandler) { try { Long currentIndex = this.consulIndexes.get(watchPathRoot); ...
@Test public void testWatchConfigKeyValues() throws NoSuchMethodException, IllegalAccessException, NoSuchFieldException { final Method watchConfigKeyValues = ConsulSyncDataService.class.getDeclaredMethod("watchConfigKeyValues", String.class, BiConsumer.class, Consumer.class); watchCo...
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 testCyclicGraphDensity() { GraphModel graphModel = GraphGenerator.generateCyclicUndirectedGraph(6); Graph graph = graphModel.getGraph(); GraphDensity d = new GraphDensity(); double density = d.calculateDensity(graph, false); assertEquals(density, 0.4); }
@Nonnull public static ToConverter getToConverter(QueryDataType type) { if (type.getTypeFamily() == QueryDataTypeFamily.OBJECT) { // User-defined types are subject to the same conversion rules as ordinary OBJECT. type = QueryDataType.OBJECT; } return Objects.requireNo...
@Test public void test_bigIntegerConversion() { Object converted = getToConverter(DECIMAL_BIG_INTEGER).convert(new BigDecimal("1")); assertThat(converted).isEqualTo(new BigInteger("1")); }
public static <T> Optional<T> getFieldValue(final Object target, final String fieldName) { return findField(fieldName, target.getClass()).map(optional -> getFieldValue(target, optional)); }
@Test void assertGetFieldValue() { assertThat(ReflectionUtils.getFieldValue(new ReflectionFixture(), "instanceValue").orElse(""), is("instance_value")); assertFalse(ReflectionUtils.getFieldValue(new ReflectionFixture(), "not_existed_field").isPresent()); }
public int poll(final FragmentHandler fragmentHandler, final int fragmentLimit) { if (isClosed) { return 0; } final long position = subscriberPosition.get(); return TermReader.read( activeTermBuffer(position), (int)position & termLengthMa...
@Test void shouldReportCorrectPositionOnReceptionWithNonZeroPositionInInitialTermId() { final int initialMessageIndex = 5; final int initialTermOffset = offsetForFrame(initialMessageIndex); final long initialPosition = computePosition( INITIAL_TERM_ID, initialTermOffset, POSI...
public Map<Consumer, List<EntryAndMetadata>> assign(final List<EntryAndMetadata> entryAndMetadataList, final int numConsumers) { assert numConsumers >= 0; consumerToPermits.clear(); final Map<Consumer, List<EntryAndMetadata>> consumerToEntr...
@Test public void testSingleConsumerMultiAssign() { // Only first 5 entries can be received because the number of permits is 5 final Consumer consumer = new Consumer("A", 5); roundRobinConsumerSelector.addConsumers(consumer); Map<Consumer, List<EntryAndMetadata>> result = assignor.a...
@Override public void onBeginFailure(GlobalTransaction tx, Throwable cause) { LOGGER.warn("Failed to begin transaction. ", cause); }
@Test void onBeginFailure() { RootContext.bind(DEFAULT_XID); DefaultGlobalTransaction tx = (DefaultGlobalTransaction)GlobalTransactionContext.getCurrentOrCreate(); FailureHandler failureHandler = new DefaultFailureHandlerImpl(); failureHandler.onBeginFailure(tx, new MyRuntimeExceptio...
public ArtifactResponse buildArtifactResponse(ArtifactResolveRequest artifactResolveRequest, String entityId, SignType signType) throws InstantiationException, ValidationException, ArtifactBuildException, BvdException { final var artifactResponse = OpenSAMLUtils.buildSAMLObject(ArtifactResponse.class); ...
@Test void validateAssertionIsPresent() throws ValidationException, SamlParseException, ArtifactBuildException, BvdException, InstantiationException, JsonProcessingException { when(bvdClientMock.retrieveRepresentationAffirmations(anyString())).thenReturn(getBvdResponse()); ArtifactResponse artifact...
static DataType getTargetDataType(final MiningFunction miningFunction, final MathContext mathContext) { switch (miningFunction) { case REGRESSION: return DataType.fromValue(mathContext.value()); case CLASSIFICATION: case CLUSTERING: return Data...
@Test void getTargetDataType() { MiningFunction miningFunction = MiningFunction.REGRESSION; MathContext mathContext = MathContext.DOUBLE; DataType retrieved = KiePMMLUtil.getTargetDataType(miningFunction, mathContext); assertThat(retrieved).isEqualTo(DataType.DOUBLE); mathCo...
@VisibleForTesting public Journal getJournal(String jid) { return journalsById.get(jid); }
@Test(timeout=100000) public void testJournalDefaultDirForOneNameSpace() { Collection<String> nameServiceIds = DFSUtilClient.getNameServiceIds(conf); setupStaticHostResolution(2, "journalnode"); String jid = "test-journalid-ns1"; Journal nsJournal = jn.getJournal(jid); JNStorage journalStorage = n...
@Override public QualityGate.Condition apply(Condition input) { String metricKey = input.getMetric().getKey(); ConditionStatus conditionStatus = statusPerConditions.get(input); checkState(conditionStatus != null, "Missing ConditionStatus for condition on metric key %s", metricKey); return builder ...
@Test @UseDataProvider("allOperatorValues") public void apply_converts_all_values_of_operator(Condition.Operator operator) { Condition condition = new Condition(newMetric(METRIC_KEY), operator.getDbValue(), ERROR_THRESHOLD); ConditionToCondition underTest = new ConditionToCondition(of(condition, SOME_CONDIT...
@Override public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext) { SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); if (sqlStatement instanceof ShowFunctionStatusStatement) { return Optional.of(new ShowFunctionStatusExecutor((ShowFu...
@Test void assertCreateWithSelectStatementFromPerformanceSchema() { initProxyContext(Collections.emptyMap()); SimpleTableSegment tableSegment = new SimpleTableSegment(new TableNameSegment(10, 13, new IdentifierValue("accounts"))); tableSegment.setOwner(new OwnerSegment(7, 8, new IdentifierVa...
@Override public void close() { RuntimeException firstException = null; for (Map.Entry<String, StateStore> entry : stores.entrySet()) { final StateStore store = entry.getValue(); if (log.isDebugEnabled()) { log.debug("Closing store {}", store.fqsn()); ...
@Test public void testClose() { final String fqsn1 = "t/ns/store-1"; StateStore store1 = mock(StateStore.class); when(store1.fqsn()).thenReturn(fqsn1); final String fqsn2 = "t/ns/store-2"; StateStore store2 = mock(StateStore.class); when(store2.fqsn()).thenReturn(fqsn...
public static <T> TypeInformation<T> of(Class<T> typeClass) { try { return TypeExtractor.createTypeInfo(typeClass); } catch (InvalidTypesException e) { throw new FlinkRuntimeException( "Cannot extract TypeInformation from Class alone, because generic parameter...
@Test void testOfGenericClassForFlink() { assertThatThrownBy(() -> TypeInformation.of(Tuple3.class)) .isInstanceOf(FlinkRuntimeException.class) .hasMessageContaining("TypeHint"); }
@Override public void write(final MySQLPacketPayload payload, final Object value) { if (value instanceof BigDecimal) { payload.writeInt4(((BigDecimal) value).intValue()); } else if (value instanceof Integer) { payload.writeInt4((Integer) value); } else { p...
@Test void assertWrite() { new MySQLInt4BinaryProtocolValue().write(payload, 1); verify(payload).writeInt4(1); }
public static String validIdentifier(String value, int maxLen, String name) { Check.notEmpty(value, name); if (value.length() > maxLen) { throw new IllegalArgumentException( MessageFormat.format("[{0}] = [{1}] exceeds max len [{2}]", name, value, maxLen)); } if (!IDENTIFIER_PATTERN.matcher...
@Test(expected = IllegalArgumentException.class) public void validIdentifierInvalid5() throws Exception { Check.validIdentifier("[a", 2, ""); }
public T add(String str) { requireNonNull(str, JVM_OPTION_NOT_NULL_ERROR_MESSAGE); String value = str.trim(); if (isInvalidOption(value)) { throw new IllegalArgumentException("a JVM option can't be empty and must start with '-'"); } checkMandatoryOptionOverwrite(value); options.add(value);...
@Test public void toString_prints_all_jvm_options() { underTest.add("-foo").add("-bar"); assertThat(underTest).hasToString("[-foo, -bar]"); }
@Override public Message receive() { Message message = delegate.receive(); handleReceive(message); return message; }
@Test void receive_creates_consumer_span() throws Exception { ActiveMQTextMessage message = new ActiveMQTextMessage(clientSession); receive(message); MutableSpan consumer = testSpanHandler.takeRemoteSpan(CONSUMER); assertThat(consumer.name()).isEqualTo("receive"); assertThat(consumer.name()).isEqua...
static ParseResult parse(String expression, NameValidator validator, ClassHelper helper) { ParseResult result = new ParseResult(); try { Parser parser = new Parser(new Scanner("ignore", new StringReader(expression))); Java.Atom atom = parser.parseConditionalExpression(); ...
@Test public void isValidAndSimpleCondition() { NameValidator validVariable = s -> Helper.toUpperCase(s).equals(s) || s.equals("road_class") || s.equals("toll") || s.equals("my_speed") || s.equals("backward_my_speed"); ParseResult result = parse("in_something", validVariable, k -> "...
static Iterator<Map<Integer, List<Data>>> toBatches(final Iterator<Entry<Integer, Data>> entries, final int maxBatch, Semaphore nodeWideLoadedKeyLimiter) { return new UnmodifiableIterator<>() { @Override public boolean hasNext() { ...
@Test public void test_toBatches_with_nodeWideLimit() { int nodeWideLimit = 7; int entryCount = 100; Semaphore nodeWideLoadedKeyLimiter = new Semaphore(nodeWideLimit); Iterator<Map<Integer, List<Data>>> batches = MapKeyLoaderUtil.toBatches(newIterator(entryCount), ...
public static UpdateRequirement fromJson(String json) { return JsonUtil.parse(json, UpdateRequirementParser::fromJson); }
@Test public void testAssertRefSnapshotIdToJsonWithNullSnapshotId() { String requirementType = UpdateRequirementParser.ASSERT_REF_SNAPSHOT_ID; String refName = "snapshot-name"; Long snapshotId = null; String json = String.format( "{\"type\":\"%s\",\"ref\":\"%s\",\"snapshot-id\":%d}...
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 shouldChooseVarArgsIfSpecificDoesntMatchMultipleArgs() { // Given: givenFunctions( function(OTHER, -1, STRING, STRING, STRING, STRING), function(EXPECTED, 0, STRING_VARARGS) ); // When: final KsqlScalarFunction fun = udfIndex.getFunction(ImmutableList.of(...
public double[][] test(DataFrame data) { DataFrame x = formula.x(data); int n = x.nrow(); int ntrees = models.length; double[][] prediction = new double[ntrees][n]; for (int j = 0; j < n; j++) { Tuple xj = x.get(j); double base = 0; for (int ...
@Test public void testAilerons() { test("ailerons", Ailerons.formula, Ailerons.data, 0.0002); }
@Override public PageResult<OperateLogDO> getOperateLogPage(OperateLogPageReqVO pageReqVO) { return operateLogMapper.selectPage(pageReqVO); }
@Test public void testGetOperateLogPage_dto() { // 构造操作日志 OperateLogDO operateLogDO = RandomUtils.randomPojo(OperateLogDO.class, o -> { o.setUserId(2048L); o.setBizId(999L); o.setType("订单"); }); operateLogMapper.insert(operateLogDO); // 测试 ...
@Override public String toString() { return "config builder of " + getConfigDefinition(); }
@Test public void require_that_builder_can_be_created_from_payload() throws IOException { Slime slime = new Slime(); Cursor root = slime.setObject(); root.setString("foo", "bar"); Cursor obj = root.setObject("foorio"); obj.setString("bar", "bam"); Cursor obj2 = obj.se...
@Override public String render(String text) { if (StringUtils.isBlank(text)) { return ""; } if (regex.isEmpty() || link.isEmpty()) { Comment comment = new Comment(); comment.escapeAndAdd(text); return comment.render(); } try { ...
@Test public void shouldRenderStringWithSpecifiedRegexAndLink1() throws Exception { String link = "http://mingle05/projects/cce/cards/${ID}"; String regex = "(?:Task |#|Bug )(\\d+)"; trackingTool = new DefaultCommentRenderer(link, regex); assertThat(trackingTool.render("Task 111: ch...
public static void validateImageInDaemonConf(Map<String, Object> conf) { List<String> allowedImages = getAllowedImages(conf, true); if (allowedImages.isEmpty()) { LOG.debug("{} is not configured; skip image validation", DaemonConfig.STORM_OCI_ALLOWED_IMAGES); } else { Str...
@Test public void validateImageInDaemonConfSkipped() { Map<String, Object> conf = new HashMap<>(); conf.put(DaemonConfig.STORM_OCI_IMAGE, "storm/rhel7:dev_test"); //this is essentially a no-op OciUtils.validateImageInDaemonConf(conf); }
@Override public void isEqualTo(@Nullable Object expected) { super.isEqualTo(expected); }
@Test @GwtIncompatible("gwt Arrays.equals(double[], double[])") public void isEqualTo_WithoutToleranceParameter_NaN_Success() { assertThat(array(2.2d, 5.4d, POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN, 0.0, -0.0)) .isEqualTo(array(2.2d, 5.4d, POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN, 0.0, -0.0)); }
public String decode(byte[] val) { return codecs[0].decode(val, 0, val.length); }
@Test public void testDecodeGreekPersonName() { assertEquals(GREEK_PERSON_NAME, iso8859_7().decode(GREEK_PERSON_NAME_BYTE)); }
public void updateAutoCommitTimer(final long currentTimeMs) { this.autoCommitState.ifPresent(t -> t.updateTimer(currentTimeMs)); }
@Test public void testPollEnsureAutocommitSent() { TopicPartition tp = new TopicPartition("t1", 1); subscriptionState.assignFromUser(Collections.singleton(tp)); subscriptionState.seek(tp, 100); CommitRequestManager commitRequestManager = create(true, 100); assertPoll(0, commi...
@Override public String buildQuery( String metricsAccountName, CanaryConfig canaryConfig, CanaryMetricConfig canaryMetricConfig, CanaryScope canaryScope) { WavefrontCanaryMetricSetQueryConfig queryConfig = (WavefrontCanaryMetricSetQueryConfig) canaryMetricConfig.getQuery(); St...
@Test public void testBuildQuery_NoScopeProvided() { CanaryScope canaryScope = createScope(""); CanaryMetricConfig canaryMetricSetQueryConfig = queryConfig(AGGREGATE); String query = wavefrontMetricsService.buildQuery("", null, canaryMetricSetQueryConfig, canaryScope); assertThat(query).isEqua...
@Override public void setConf(Configuration conf) { super.setConf(conf); getRawMapping().setConf(conf); }
@Test public void testFilenameMeansMultiSwitch() throws Throwable { Configuration conf = new Configuration(); conf.set(ScriptBasedMapping.SCRIPT_FILENAME_KEY, "any-filename"); ScriptBasedMapping mapping = createMapping(conf); assertFalse("Expected to be multi switch", mapping.isSingleSwitch()); ma...
@Override @MethodNotAvailable public CompletionStage<Void> setAsync(K key, V value) { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testSetAsyncWithTtl() { adapter.setAsync(42, "value", 1, TimeUnit.MILLISECONDS); }
@Override public void onProjectBranchesChanged(Set<Project> projects, Set<String> impactedBranches) { checkNotNull(projects, "projects can't be null"); if (projects.isEmpty()) { return; } Arrays.stream(listeners) .forEach(safelyCallListener(listener -> listener.onProjectBranchesChanged(pr...
@Test @UseDataProvider("oneOrManyProjects") public void onProjectBranchesChanged_calls_all_listeners_even_if_one_throws_an_Error(Set<Project> projects) { InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3); doThrow(new Error("Faking listener2 throwing an Error")) .when(listener2) ...
@Override public void handleData(String dataId, UserData userData) { if (dataId == null) { return; } this.lastUserData = userData; printUserData(dataId, userData); if (flag != null) { flag[0].compareAndSet(false, true); } if (canNot...
@Test public void handleData() throws Exception { Subscriber listSub = new MockSubscribe(5); Configurator attrSub = new MockConfigurator(2); final AtomicInteger ps = new AtomicInteger(0); ProviderInfoListener listener = new ProviderInfoListener() { @Override ...
public Location setY(double y) { return new Location(extent, position.withY(y), yaw, pitch); }
@Test public void testSetY() throws Exception { World world = mock(World.class); Location location1 = new Location(world, Vector3.ZERO); Location location2 = location1.setY(TEST_VALUE); assertEquals(0, location1.getY(), EPSILON); assertEquals(0, location2.getX(), EPSILON); ...
@Override public CompletableFuture<ResponseFuture> invokeImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis) { Stopwatch stopwatch = Stopwatch.createStarted(); String channelRemoteAddr = RemotingHelper.parseChannelRemoteAddr(channel); doBeforeRpcHooks...
@Test public void testInvokeImpl() throws ExecutionException, InterruptedException { remotingClient.registerRPCHook(rpcHookMock); Channel channel = new LocalChannel(); RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.PULL_MESSAGE, null); RemotingCommand resp...
@Override public List<AwsEndpoint> getClusterEndpoints() { if (clientConfig.shouldUseDnsForFetchingServiceUrls()) { if (logger.isInfoEnabled()) { logger.info("Resolving eureka endpoints via DNS: {}", getDNSName()); } return getClusterEndpointsFromDns(); ...
@Test public void testReadFromConfig() { List<AwsEndpoint> endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.size(), equalTo(6)); for (AwsEndpoint endpoint : endpoints) { if (endpoint.getZone().equals("us-east-1e")) { assertThat("secure was wrong", endpoint.isSecure(), is(tr...
boolean matchesNonValueField(final Optional<SourceName> source, final ColumnName column) { if (!source.isPresent()) { return sourceSchemas.values().stream() .anyMatch(schema -> SystemColumns.isPseudoColumn(column) || schema.isKeyColumn(column)); } final SourceName sourceName =...
@Test public void shouldNotMatchNonKeyFieldOnWrongSource() { assertThat(sourceSchemas.matchesNonValueField(Optional.of(ALIAS_2), K0), is(false)); }
@Internal public static String getFqName( String system, @Nullable String routine, Iterable<String> segments) { StringBuilder builder = new StringBuilder(system); if (!Strings.isNullOrEmpty(routine)) { builder.append(":").append(routine); } int idx = 0; for (String segment : segments) ...
@Test public void testGetFqName() { Map<String, String> testCases = ImmutableMap.<String, String>builder() .put("apache-beam", "apache-beam") .put("`apache-beam`", "`apache-beam`") .put("apache.beam", "`apache.beam`") .put("apache:beam", "`apache:beam`") ...
@Override public ComponentCreationData createProjectAndBindToDevOpsPlatform(DbSession dbSession, CreationMethod creationMethod, Boolean monorepo, @Nullable String projectKey, @Nullable String projectName) { String pat = findPersonalAccessTokenOrThrow(dbSession, almSettingDto); String workspace = ofNullab...
@Test void createProjectAndBindToDevOpsPlatform_whenRepositoryNotFound_shouldThrow() { mockPatForUser(); when(almSettingDto.getAppId()).thenReturn("workspace"); when(bitbucketCloudRestClient.getRepo(USER_PAT, "workspace", REPOSITORY_SLUG)).thenThrow(new IllegalStateException("Problem fetching repository f...
public static StatementExecutorResponse execute( final ConfiguredStatement<AssertSchema> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { return AssertExecutor.execute( statement.getMaskedStat...
@Test public void shouldAssertNotExistSchemaBySubjectAndId() { // Given final AssertSchema assertSchema = new AssertSchema(Optional.empty(), Optional.of("def"), Optional.of(100), Optional.empty(), false); final ConfiguredStatement<AssertSchema> statement = ConfiguredStatement .of(KsqlParser.Prepar...
public static Getter newMethodGetter(Object object, Getter parent, Method method, String modifier) throws Exception { return newGetter(object, parent, modifier, method.getReturnType(), method::invoke, (t, et) -> new MethodGetter(parent, method, modifier, t, et)); }
@Test public void newMethodGetter_whenExtractingFromNull_Array_AndReducerSuffixInNotEmpty_thenReturnNullGetter() throws Exception { OuterObject object = OuterObject.nullInner("name"); Getter getter = GetterFactory.newMethodGetter(object, null, innersArrayMethod, "[any]"); Class<...
@Override public boolean enableSendingOldValues(final boolean forceMaterialization) { if (queryableName != null) { sendOldValues = true; return true; } if (parent.enableSendingOldValues(forceMaterialization)) { sendOldValues = true; } retu...
@Test public void shouldNotSetSendOldValuesOnParentIfMaterialized() { new KTableTransformValues<>(parent, new NoOpValueTransformerWithKeySupplier<>(), QUERYABLE_NAME).enableSendingOldValues(true); verify(parent, never()).enableSendingOldValues(anyBoolean()); }
public NonClosedTracking<RAW, BASE> trackNonClosed(Input<RAW> rawInput, Input<BASE> baseInput) { NonClosedTracking<RAW, BASE> tracking = NonClosedTracking.of(rawInput, baseInput); // 1. match by rule, line, line hash and message match(tracking, LineAndLineHashAndMessage::new); // 2. match issues with ...
@Test public void match_issues_with_same_rule_key_on_project_level() { FakeInput baseInput = new FakeInput(); Issue base1 = baseInput.createIssue(RULE_MISSING_PACKAGE_INFO, "[com.test:abc] Missing package-info.java in package."); Issue base2 = baseInput.createIssue(RULE_MISSING_PACKAGE_INFO, "[com.test:ab...
public boolean isInRange(String ipAddress) throws UnknownHostException { InetAddress address = InetAddress.getByName(ipAddress); BigInteger start = new BigInteger(1, this.startAddress.getAddress()); BigInteger end = new BigInteger(1, this.endAddress.getAddress()); BigInteger target = new...
@Test void testIpv6() throws UnknownHostException { CIDRUtils cidrUtils = new CIDRUtils("234e:0:4567::3d/64"); Assertions.assertTrue(cidrUtils.isInRange("234e:0:4567::3e")); Assertions.assertTrue(cidrUtils.isInRange("234e:0:4567::ffff:3e")); Assertions.assertFalse(cidrUtils.isInRange...
@Override public List<ConnectorMetadataUpdateHandle> getPendingMetadataUpdateRequests() { ImmutableList.Builder<ConnectorMetadataUpdateHandle> result = ImmutableList.builder(); for (HiveMetadataUpdateHandle request : hiveMetadataRequestQueue) { result.add(request); } ...
@Test public void testEmptyMetadataUpdateRequestQueue() { HiveMetadataUpdater hiveMetadataUpdater = new HiveMetadataUpdater(EXECUTOR); assertEquals(hiveMetadataUpdater.getPendingMetadataUpdateRequests().size(), 0); }
@Override public String evaluate(EvaluationContext evaluationContext, String... args) { if (args == null || args.length == 0) { return ""; } return args[getRandom().nextInt(args.length)]; }
@Test void testSimpleEvaluation() { List<String> values = List.of("one", "two", "three"); // Compute evaluation. RandomValueELFunction function = new RandomValueELFunction(); String result = function.evaluate(null); assertEquals("", result); result = function.evaluate(null, "one...
public static DataMap bytesToDataMap(Map<String, String> headers, ByteString bytes) throws MimeTypeParseException, IOException { return getContentType(headers).getCodec().readMap(bytes); }
@Test public void testPSONByteStringToDataMap() throws MimeTypeParseException, IOException { DataMap expectedDataMap = createTestDataMap(); ByteString byteString = ByteString.copy(PSON_DATA_CODEC.mapToBytes(expectedDataMap)); DataMap dataMap = bytesToDataMap("application/x-pson", byteString); Assert...
public Optional<String> retrieve(final String shortCode) throws IOException { final URI uri = shortenerHost.resolve(shortCode); final HttpRequest request = HttpRequest.newBuilder().uri(uri).GET().build(); try { final HttpResponse<String> response = this.client.send(request, HttpResponse.BodyHandlers....
@Test public void testUriResolution() throws IOException, InterruptedException { final HttpClient httpClient = mock(HttpClient.class); final ShortCodeExpander expander = new ShortCodeExpander(httpClient, "https://www.example.org/shortener/"); when(httpClient .send(argThat(req -> req.uri().toString...
@VisibleForTesting void validateClientIdExists(Long id, String clientId) { OAuth2ClientDO client = oauth2ClientMapper.selectByClientId(clientId); if (client == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的客户端 if (id == null) { throw exception(OAUTH2_C...
@Test public void testValidateClientIdExists_withId() { // mock 数据 OAuth2ClientDO client = randomPojo(OAuth2ClientDO.class).setClientId("tudou"); oauth2ClientMapper.insert(client); // 准备参数 Long id = randomLongId(); String clientId = "tudou"; // 调用,不会报错 ...
public DataTable subTable(int fromRow, int fromColumn) { return subTable(fromRow, fromColumn, height(), width()); }
@Test void subTable_throws_for_large_to_row() { DataTable table = createSimpleTable(); assertThrows(IndexOutOfBoundsException.class, () -> table.subTable(0, 0, 4, 1)); }
public BundleProcessor getProcessor( BeamFnApi.ProcessBundleDescriptor descriptor, List<RemoteInputDestination> remoteInputDesinations) { checkState( !descriptor.hasStateApiServiceDescriptor(), "The %s cannot support a %s containing a state %s.", BundleProcessor.class.getSimpleNa...
@Test public void testRegister() throws Exception { ProcessBundleDescriptor descriptor1 = ProcessBundleDescriptor.newBuilder().setId("descriptor1").build(); List<RemoteInputDestination> remoteInputs = Collections.singletonList( RemoteInputDestination.of( (FullWindo...
@Override public int hashCode() { if (hashCodeCache == -1) { hashCodeCache = Objects.hash(urlAddress, urlParam); } return hashCodeCache; }
@Test void testHashcode() { URL url1 = URL.valueOf("consumer://30.225.20.150/org.apache.dubbo.rpc.service.GenericService?application=" + "dubbo-demo-api-consumer&category=consumers&check=false&dubbo=2.0.2&generic=true&interface=" + "org.apache.dubbo.demo.DemoService&pid=7375&...
@Override public O next() { if (!hasNext()) { throw new NoSuchElementException(); } O result = nextObject; nextObject = null; return result; }
@Test public void automatic_close_if_traversal_error() { FailureCloseableIterator it = new FailureCloseableIterator(); try { it.next(); fail(); } catch (IllegalStateException expected) { assertThat(expected).hasMessage("expected failure"); assertThat(it.isClosed).isTrue(); } ...
@Override public List<ConfigInfoWrapper> queryConfigInfoByNamespace(String tenant) { if (Objects.isNull(tenant)) { throw new IllegalArgumentException("tenantId can not be null"); } String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; try { ...
@Test void testQueryConfigInfoByNamespace() { //mock select config state List<ConfigInfoWrapper> mockConfigs = new ArrayList<>(); mockConfigs.add(createMockConfigInfoWrapper(0)); mockConfigs.add(createMockConfigInfoWrapper(1)); mockConfigs.add(createMockConfigInfoWra...
public List<List<ConfigInfoChanged>> splitList(List<ConfigInfoChanged> list, int count) { List<List<ConfigInfoChanged>> result = new ArrayList<>(count); for (int i = 0; i < count; i++) { result.add(new ArrayList<>()); } for (int i = 0; i < list.size(); i++) { Conf...
@Test void testSplitList() { String dataId = "dataID"; int count = 5; List<ConfigInfoChanged> configList = new ArrayList<>(); configList.add(create(dataId, 0)); configList.add(create(dataId, 1)); configList.add(create(dataId, 2)); configList.add(create(dataId,...
public static boolean fullyDeleteContents(final File dir) { return fullyDeleteContents(dir, false); }
@Test (timeout = 30000) public void testFailFullyDeleteContentsGrantPermissions() throws IOException { setupDirsAndNonWritablePermissions(); boolean ret = FileUtil.fullyDeleteContents(new MyFile(del), true); // this time the directories with revoked permissions *should* be deleted: validateAndSetWrita...
@Override public boolean equals(@Nullable Object object) { if (object instanceof MetricsContainerStepMap) { MetricsContainerStepMap metricsContainerStepMap = (MetricsContainerStepMap) object; return Objects.equals(metricsContainers, metricsContainerStepMap.metricsContainers) && Objects.equal...
@Test public void testEquals() { MetricsContainerStepMap metricsContainerStepMap = new MetricsContainerStepMap(); MetricsContainerStepMap equal = new MetricsContainerStepMap(); Assert.assertEquals(metricsContainerStepMap, equal); Assert.assertEquals(metricsContainerStepMap.hashCode(), equal.hashCode()...
public static String fromNamedReference(CharSequence s) { if (s == null) { return null; } final Integer code = SPECIALS.get(s.toString()); if (code != null) { return "&#" + code + ";"; } return null; }
@Test public void testFromNamedReference() { CharSequence s = null; String expResult = null; String result = XmlEntity.fromNamedReference(s); assertEquals(expResult, result); s = "somethingWrong"; expResult = null; result = XmlEntity.fromNamedReference(s); ...
public void updateFromOther(FeedItem other) { if (other.imageUrl != null) { this.imageUrl = other.imageUrl; } if (other.title != null) { title = other.title; } if (other.getDescription() != null) { description = other.getDescription(); ...
@Test public void testUpdateFromOther_feedItemImageRemoved() { feedItemImageRemoved(); original.updateFromOther(changedFeedItem); assertFeedItemImageWasNotUpdated(); }
@Override public Optional<RegistryAuthenticator> handleHttpResponseException( ResponseException responseException) throws ResponseException, RegistryErrorException { // Only valid for status code of '401 Unauthorized'. if (responseException.getStatusCode() != HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) { ...
@Test public void testHandleHttpResponseException_pass() throws RegistryErrorException, ResponseException, MalformedURLException { String authenticationMethod = "Bearer realm=\"https://somerealm\",service=\"someservice\",scope=\"somescope\""; Mockito.when(mockResponseException.getStatusCode()) ...
public Map<TopicPartition, Long> endOffsets(Set<TopicPartition> partitions) { if (partitions == null || partitions.isEmpty()) { return Collections.emptyMap(); } Map<TopicPartition, OffsetSpec> offsetSpecMap = partitions.stream().collect(Collectors.toMap(Function.identity(), tp -> Off...
@Test public void endOffsetsShouldFailWithNonRetriableWhenAuthorizationFailureOccurs() { String topicName = "myTopic"; TopicPartition tp1 = new TopicPartition(topicName, 0); Set<TopicPartition> tps = Collections.singleton(tp1); Long offset = null; // response should use error ...
static int evaluateLevenshteinDistance(LevenshteinDistance levenshteinDistance, String term, String text) { logger.debug("evaluateLevenshteinDistance {} {}", term, text); return levenshteinDistance.apply(term, text); }
@Test void evaluateLevenshteinDistanceSplitText() { String toSearch = "brown fox"; String toScan = "brown fox"; LevenshteinDistance levenshteinDistance = new LevenshteinDistance(0); assertThat(KiePMMLTextIndex.evaluateLevenshteinDistance(levenshteinDistance, toSearch, toScan)).isEqua...
public static List<UpdateRequirement> forCreateTable(List<MetadataUpdate> metadataUpdates) { Preconditions.checkArgument(null != metadataUpdates, "Invalid metadata updates: null"); Builder builder = new Builder(null, false); builder.require(new UpdateRequirement.AssertTableDoesNotExist()); metadataUpdat...
@Test public void emptyUpdatesForCreateTable() { assertThat(UpdateRequirements.forCreateTable(ImmutableList.of())) .hasSize(1) .hasOnlyElementsOfType(UpdateRequirement.AssertTableDoesNotExist.class); }
public static String getShardingSphereDataNodePath() { return String.join("/", "", ROOT_NODE, DATABASES_NODE); }
@Test void assertGetShardingSphereDataNodePath() { assertThat(ShardingSphereDataNode.getShardingSphereDataNodePath(), is("/statistics/databases")); }
public OffsetAndMetadata findNextCommitOffset(final String commitMetadata) { boolean found = false; long currOffset; long nextCommitOffset = committedOffset; for (KafkaSpoutMessageId currAckedMsg : ackedMsgs) { // complexity is that of a linear scan on a TreeMap currOffset ...
@Test public void testFindNextCommitOffsetWhenTooLowOffsetIsAcked() { OffsetManager startAtHighOffsetManager = new OffsetManager(testTp, 10); emitAndAckMessage(getMessageId(0)); OffsetAndMetadata nextCommitOffset = startAtHighOffsetManager.findNextCommitOffset(COMMIT_METADATA); asser...
@Override public String getName() { return "Snappy"; }
@Test public void testGetName() { SnappyCompressionProvider provider = (SnappyCompressionProvider) factory.getCompressionProviderByName( PROVIDER_NAME ); assertNotNull( provider ); assertEquals( PROVIDER_NAME, provider.getName() ); }
public static SourceConfig validateUpdate(SourceConfig existingConfig, SourceConfig newConfig) { SourceConfig mergedConfig = clone(existingConfig); if (!existingConfig.getTenant().equals(newConfig.getTenant())) { throw new IllegalArgumentException("Tenants differ"); } if (!ex...
@Test public void testMergeRuntimeFlags() { SourceConfig sourceConfig = createSourceConfig(); SourceConfig newFunctionConfig = createUpdatedSourceConfig("runtimeFlags", "-Dfoo=bar2"); SourceConfig mergedConfig = SourceConfigUtils.validateUpdate(sourceConfig, newFunctionConfig); asser...
@Override public void run() { try { backgroundJobServer.getJobSteward().notifyThreadOccupied(); MDCMapper.loadMDCContextFromJob(job); performJob(); } catch (Exception e) { if (isJobDeletedWhileProcessing(e)) { // nothing to do anymore a...
@Test @DisplayName("any exception other than InvocationTargetException stays unwrapped") void anyExceptionOtherThanInvocationTargetExceptionIsNotUnwrapped() throws Exception { var job = anEnqueuedJob().build(); var runner = mock(BackgroundJobRunner.class); doThrow(new RuntimeException("t...
void precheckMaxResultLimitOnLocalPartitions(String mapName) { // check if feature is enabled if (!isPreCheckEnabled) { return; } // limit number of local partitions to check to keep runtime constant PartitionIdSet localPartitions = mapServiceContext.getCachedOwnedPa...
@Test(expected = QueryResultSizeExceededException.class) public void testLocalPreCheckEnabledWitMorePartitionsThanPreCheckThresholdOverLimit() { int[] partitionSizes = {1200, 1000, Integer.MIN_VALUE}; populatePartitions(partitionSizes); initMocksWithConfiguration(200000, 2); limiter...
public Pair<Map<HostInfo, KsqlEntity>, Set<HostInfo>> fetchAllRemoteResults() { final Set<HostInfo> remoteHosts = DiscoverRemoteHostsUtil.getRemoteHosts( executionContext.getPersistentQueries(), sessionProperties.getKsqlHostInfo() ); if (remoteHosts.isEmpty() || sessionProperties.getInternal...
@Test public void testReturnsEmptyIfRequestIsInternal() { Pair<Map<HostInfo, KsqlEntity>, Set<HostInfo>> remoteResults = augmenter.fetchAllRemoteResults(); assertThat(remoteResults.getLeft().entrySet(), hasSize(0)); assertThat(remoteResults.getRight(), hasSize(0)); }
@Override public void init(final Properties props) { this.props = props; cryptographicAlgorithm = TypedSPILoader.getService(CryptographicAlgorithm.class, getType(), props); }
@Test void assertCreateNewInstanceWithEmptyDigestAlgorithm() { assertThrows(AlgorithmInitializationException.class, () -> encryptAlgorithm.init(PropertiesBuilder.build(new Property("aes-key-value", "123456abc"), new Property("digest-algorithm-name", "")))); }
@Deprecated public static RowMutationInformation of(MutationType mutationType, long sequenceNumber) { checkArgument(sequenceNumber >= 0, "sequenceNumber must be non-negative"); return new AutoValue_RowMutationInformation( mutationType, null, Long.toHexString(sequenceNumber)); }
@Test public void givenAddlSegmentTooLarge_throws() { IllegalArgumentException error = assertThrows( IllegalArgumentException.class, () -> RowMutationInformation.of( RowMutationInformation.MutationType.UPSERT, "0/12345678901234567")); assertE...
@Override public Image call() throws LayerPropertyNotFoundException { try (ProgressEventDispatcher ignored = progressEventDispatcherFactory.create("building image format", 1); TimerEventDispatcher ignored2 = new TimerEventDispatcher(buildContext.getEventHandlers(), DESCRIPTION)) { ...
@Test public void test_generateHistoryObjects() { Image image = new BuildImageStep( mockBuildContext, mockProgressEventDispatcherFactory, baseImage, baseImageLayers, applicationLayers) .call(); // Make sure hi...
protected Map<String, CanaryScopePair> buildRequestScopes( CanaryAnalysisExecutionRequest config, long interval, Duration intervalDuration) { Map<String, CanaryScopePair> scopes = new HashMap<>(); config .getScopes() .forEach( scope -> { ScopeTimeConfig scopeTim...
@Test public void test_that_buildRequestScopes_has_expected_start_and_end_when_control_offset_is_supplied() { int interval = 1; String startIso = "2018-12-17T20:56:39.689Z"; Duration lifetimeDuration = Duration.ofMinutes(3L); CanaryAnalysisExecutionRequest request = CanaryAnalysisExecuti...
@Override public boolean createReservation(ReservationId reservationId, String user, Plan plan, ReservationDefinition contract) throws PlanningException { LOG.info("placing the following ReservationRequest: " + contract); try { boolean res = planner.createReservation(reservationId, use...
@Test public void testAllImpossible() throws PlanningException { prepareBasicPlan(); // create an ALL request, with an impossible combination, it should be // rejected, and allocation remain unchanged ReservationDefinition rr = new ReservationDefinitionPBImpl(); rr.setArrival(100L); rr.setDead...
public boolean hasLateTransaction(long currentTimeMs) { long lastTimestamp = oldestTxnLastTimestamp; return lastTimestamp > 0 && (currentTimeMs - lastTimestamp) > maxTransactionTimeoutMs + ProducerStateManager.LATE_TRANSACTION_BUFFER_MS; }
@Test public void testHasLateTransaction() { long producerId1 = 39L; short epoch1 = 2; long producerId2 = 57L; short epoch2 = 9; // Start two transactions with a delay between them appendClientEntry(stateManager, producerId1, epoch1, defaultSequence, 100, true); ...
@Override public boolean supportsOpenCursorsAcrossCommit() { return false; }
@Test void assertSupportsOpenCursorsAcrossCommit() { assertFalse(metaData.supportsOpenCursorsAcrossCommit()); }
public static HttpClient create() { return new HttpClientConnect(new HttpConnectionProvider()); }
@Test void testConnectionNoLifeTimeElasticPoolHttp1() throws Exception { ConnectionProvider provider = ConnectionProvider.create("testConnectionNoLifeTimeElasticPoolHttp1", Integer.MAX_VALUE); try { ChannelId[] ids = doTestConnectionLifeTime(createServer(), createClient(provider, () -> disposableServer...
public static <T> Set<T> emptyIsNotFound(Set<T> item, String message) { if (item == null || item.isEmpty()) { log.error(message); throw new ItemNotFoundException(message); } return item; }
@Test(expected = ItemNotFoundException.class) public void testEmptyIsNotFoundNullThrow() { Tools.emptyIsNotFound(null, "Not found!"); fail("Should've thrown some thing"); }
@Override public List<AlarmId> unassignDeletedUserAlarms(TenantId tenantId, UserId userId, String userTitle, long unassignTs) { List<AlarmId> totalAlarmIds = new ArrayList<>(); PageLink pageLink = new PageLink(100, 0, null, new SortOrder("id", SortOrder.Direction.ASC)); while (true) { ...
@Test public void testUnassignDeletedUserAlarms() throws ThingsboardException { AlarmInfo alarm = new AlarmInfo(); alarm.setId(new AlarmId(UUID.randomUUID())); when(alarmService.findAlarmIdsByAssigneeId(any(), any(), any())) .thenReturn(new PageData<>(List.of(alarm.getId()),...
public static Builder builder() { return new Builder(); }
@Test public void testEquality() { Application a1 = baseBuilder.build(); Application a2 = DefaultApplication.builder(a1) .build(); Application a3 = DefaultApplication.builder(baseBuilder) .withFeaturesRepo(Optional.empty()) .build(); A...
@Override public String call() throws RemoteServiceException { var currentTime = System.nanoTime(); //Since currentTime and serverStartTime are both in nanoseconds, we convert it to //seconds by diving by 10e9 and ensure floating point division by multiplying it //with 1.0 first. We then check if it i...
@Test void testParameterizedConstructor() throws RemoteServiceException { var obj = new DelayedRemoteService(System.nanoTime()-2000*1000*1000,1); assertEquals("Delayed service is working",obj.call()); }
public static String jmxSanitize(String name) { return MBEAN_PATTERN.matcher(name).matches() ? name : ObjectName.quote(name); }
@Test public void testJmxSanitize() throws MalformedObjectNameException { int unquoted = 0; for (int i = 0; i < 65536; i++) { char c = (char) i; String value = "value" + c; String jmxSanitizedValue = Sanitizer.jmxSanitize(value); if (jmxSanitizedValue....
@Override public void close() { }
@Test public void shouldSucceed_justForwarded() throws ExecutionException, InterruptedException { // Given: when(pushRoutingOptions.getHasBeenForwarded()).thenReturn(true); final PushRouting routing = new PushRouting(); // When: final PushConnectionsHandle handle = handlePushRouting(routing); ...
@Override public Connection connect(String url, Properties info) throws SQLException { // calciteConnection is initialized with an empty Beam schema, // we need to populate it with pipeline options, load table providers, etc return JdbcConnection.initialize((CalciteConnection) super.connect(url, info)); ...
@Test public void testInternalConnect_boundedTable() throws Exception { CalciteConnection connection = JdbcDriver.connect(BOUNDED_TABLE, PipelineOptionsFactory.create()); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM test"); ass...
public String getFingerprint() { return fingerprint; }
@Test public void testIdenticalStreams() throws Exception { final StreamListFingerprint fingerprint1 = new StreamListFingerprint(Lists.newArrayList(stream1)); final StreamListFingerprint fingerprint2 = new StreamListFingerprint(Lists.newArrayList(stream1)); final StreamListFingerprint finger...
@Override public boolean match(Message msg, StreamRule rule) { Double msgVal = getDouble(msg.getField(rule.getField())); if (msgVal == null) { return false; } Double ruleVal = getDouble(rule.getValue()); if (ruleVal == null) { return false; } ...
@Test public void testSuccessfulMatchWithNegativeValue() { StreamRule rule = getSampleRule(); rule.setValue("-54354"); Message msg = getSampleMessage(); msg.addField("something", "-90000"); StreamRuleMatcher matcher = getMatcher(rule); assertTrue(matcher.match(msg, ...
public Optional<Node> localCorpusDispatchTarget() { if (localCorpusDispatchTarget == null) return Optional.empty(); // Only use direct dispatch if the local group has sufficient coverage Group localSearchGroup = groups.get(localCorpusDispatchTarget.group()); if ( ! localSearchGroup.hasS...
@Test void requireThatVipStatusIsDefaultDownButComesUpAfterPinging() { try (State test = new State("cluster.1", 2, "a", "b")) { assertTrue(test.searchCluster.localCorpusDispatchTarget().isEmpty()); assertFalse(test.vipStatus.isInRotation()); test.waitOneFullPingRound(); ...
public static <T extends NamedConfig> T getConfig(ConfigPatternMatcher configPatternMatcher, Map<String, T> configs, String name, Class clazz) { return getConfig(configPatternMatcher, configs, name, clazz...
@Test public void getNonExistingConfig() { QueueConfig newConfig = ConfigUtils.getConfig(configPatternMatcher, queueConfigs, "newConfig", QueueConfig.class); assertEquals("newConfig", newConfig.getName()); assertEquals(1, newConfig.getBackupCount()); assertEquals(2, queueConfigs.siz...
@Override public <OUT> ProcessConfigurableAndNonKeyedPartitionStream<OUT> process( OneInputStreamProcessFunction<T, OUT> processFunction) { validateStates( processFunction.usesStates(), new HashSet<>( Arrays.asList( ...
@Test void testStateErrorWithTwoOutputStream() throws Exception { ExecutionEnvironmentImpl env = StreamTestUtils.getEnv(); NonKeyedPartitionStreamImpl<Integer> stream = new NonKeyedPartitionStreamImpl<>( env, new TestingTransformation<>("t1", Types.INT, 1)); ...
public static BigDecimal cast(final Integer value, final int precision, final int scale) { if (value == null) { return null; } return cast(value.longValue(), precision, scale); }
@Test public void shouldNotCastDoubleTooBig() { // When: final Exception e = assertThrows( ArithmeticException.class, () -> cast(10.0, 2, 1) ); // Then: assertThat(e.getMessage(), containsString("Numeric field overflow")); }
@Override public YamlSingleRuleConfiguration swapToYamlConfiguration(final SingleRuleConfiguration data) { YamlSingleRuleConfiguration result = new YamlSingleRuleConfiguration(); result.getTables().addAll(data.getTables()); data.getDefaultDataSource().ifPresent(result::setDefaultDataSource);...
@Test void assertSwapToYaml() { assertThat(new YamlSingleRuleConfigurationSwapper().swapToYamlConfiguration(new SingleRuleConfiguration(Collections.emptyList(), "ds_0")).getDefaultDataSource(), is("ds_0")); }
@Override public void setControllers(List<ControllerInfo> controllers) { DeviceId deviceId = getDeviceId(); checkNotNull(deviceId, MSG_DEVICE_ID_NULL); MastershipService mastershipService = getHandler().get(MastershipService.class); checkNotNull(mastershipService, MSG_MASTERSHIP_NUL...
@Test public void testSetControllers() { // Get device handler DriverHandler driverHandler = null; try { driverHandler = driverService.createHandler(restDeviceId1); } catch (Exception e) { throw e; } assertThat(driverHandler, notNullValue()); ...
@Override @SuppressWarnings("unchecked") public <T> T getExtGroupRealization(Class<T> extensionType, String name) throws ExtensionException { if (name == null) { throw new ExtensionException("name can not be null"); } if (extensionType == null) { throw new Extensi...
@Test public void testGetExtGroupRealization() throws ExtensionException { ExtensionException exception; DefaultExtGroupRealizationManager manager = new DefaultExtGroupRealizationManager(); exception = assertThrows(ExtensionException.class, () -> manager.getExtGroupRealization(null, null));...
public String process(final Expression expression) { return formatExpression(expression); }
@Test public void shouldGenerateCorrectCodeForTime() { // Given: final TimeLiteral time = new TimeLiteral(new Time(185000)); // When: final String java = sqlToJavaVisitor.process(time); // Then: assertThat(java, is("00:03:05")); }
@Override public V put(K key, V value) { return map.put(key, value); }
@Test public void testPut() { map.put(42, "oldValue"); String oldValue = adapter.put(42, "newValue"); assertEquals("oldValue", oldValue); assertEquals("newValue", map.get(42)); }