focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static Map<String, ShardingSphereSchema> build(final GenericSchemaBuilderMaterial material) throws SQLException { return build(getAllTableNames(material.getRules()), material); }
@Test void assertLoadWithExistedTableName() throws SQLException { Collection<String> tableNames = Collections.singletonList("data_node_routed_table1"); when(MetaDataLoader.load(any())).thenReturn(createSchemaMetaDataMap(tableNames, material)); assertFalse(GenericSchemaBuilder.build(tableName...
public void setLastColdReadTimeMills(Long lastColdReadTimeMills) { this.lastColdReadTimeMills = lastColdReadTimeMills; }
@Test public void testSetLastColdReadTimeMills() { long newLastColdReadTimeMills = System.currentTimeMillis() + 1000; accAndTimeStamp.setLastColdReadTimeMills(newLastColdReadTimeMills); assertEquals("Last cold read time should be set to new value", newLastColdReadTimeMills, accAndTimeStamp.g...
public void clear() { for (Section s : sections) { s.clear(); } }
@Test public void testClear() { ConcurrentLongPairSet map = ConcurrentLongPairSet.newBuilder() .expectedItems(2) .concurrencyLevel(1) .autoShrink(true) .mapIdleFactor(0.25f) .build(); assertTrue(map.capacity() == 4); ...
@Override protected void doProcess(Exchange exchange, MetricsEndpoint endpoint, MetricRegistry registry, String metricsName) throws Exception { Message in = exchange.getIn(); Counter counter = registry.counter(metricsName); Long increment = endpoint.getIncrement(); Long d...
@Test public void testProcessWithDecrementOnly() throws Exception { Object action = null; when(endpoint.getIncrement()).thenReturn(null); when(endpoint.getDecrement()).thenReturn(DECREMENT); when(in.getHeader(HEADER_COUNTER_DECREMENT, DECREMENT, Long.class)).thenReturn(DECREMENT); ...
@Override public long transferFrom(ReadableByteChannel src, long position, long count) throws IOException { checkNotNull(src); Util.checkNotNegative(position, "position"); Util.checkNotNegative(count, "count"); checkOpen(); checkWritable(); long transferred = 0; // will definitely either be a...
@Test public void testTransferFromNegative() throws IOException { FileChannel channel = channel(regularFile(0), READ, WRITE); try { channel.transferFrom(new ByteBufferChannel(10), -1, 0); fail(); } catch (IllegalArgumentException expected) { } try { channel.transferFrom(new Byt...
public static List<AclEntry> replaceAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); // Replacement is done separately for eac...
@Test(expected=AclException.class) public void testReplaceAclDefaultEntriesInputTooLarge() throws AclException { List<AclEntry> existing = new ImmutableList.Builder<AclEntry>() .add(aclEntry(DEFAULT, USER, ALL)) .add(aclEntry(DEFAULT, GROUP, READ)) .add(aclEntry(DEFAULT, OTHER, NONE)) .bui...
@Override public Map<String, Metric> getMetrics() { final Map<String, Metric> gauges = new HashMap<>(); gauges.put("total.init", (Gauge<Long>) () -> mxBean.getHeapMemoryUsage().getInit() + mxBean.getNonHeapMemoryUsage().getInit()); gauges.put("total.used", (Gauge<Long>) () -...
@Test public void hasAGaugeForMemoryPoolUsage() { final Gauge gauge = (Gauge) gauges.getMetrics().get("pools.Big-Pool.usage"); assertThat(gauge.getValue()) .isEqualTo(0.75); }
public static FileEntriesLayer extraDirectoryLayerConfiguration( Path sourceDirectory, AbsoluteUnixPath targetDirectory, List<String> includes, List<String> excludes, Map<String, FilePermissions> extraDirectoryPermissions, ModificationTimeProvider modificationTimeProvider) thro...
@Test public void testExtraDirectoryLayerConfiguration_globPermissions() throws URISyntaxException, IOException { Path extraFilesDirectory = Paths.get(Resources.getResource("core/layer").toURI()); Map<String, FilePermissions> permissionsMap = ImmutableMap.of( "/a", FilePe...
public void execute(){ logger.debug("[" + getOperationName() + "] Starting execution of paged operation. maximum time: " + maxTime + ", maximum pages: " + maxPages); long startTime = System.currentTimeMillis(); long executionTime = 0; int i = 0; int exceptionsSwallowedCount = 0; int operationsCompleted =...
@Test(timeout = 1000L) public void execute_npage(){ int n = 7; CountingPageOperation op = new CountingPageOperation(n,Long.MAX_VALUE); op.execute(); assertEquals(n*10L, op.counter); }
public Collection<QualifiedTable> getSingleTables(final Collection<QualifiedTable> qualifiedTables) { Collection<QualifiedTable> result = new LinkedList<>(); for (QualifiedTable each : qualifiedTables) { Collection<DataNode> dataNodes = singleTableDataNodes.getOrDefault(each.getTableName().t...
@Test void assertGetSingleTables() { SingleRule singleRule = new SingleRule(ruleConfig, DefaultDatabase.LOGIC_NAME, new H2DatabaseType(), dataSourceMap, Collections.singleton(mock(ShardingSphereRule.class, RETURNS_DEEP_STUBS))); Collection<QualifiedTable> tableNames = new LinkedList<>(); tab...
@VisibleForTesting public static JobGraph createJobGraph(StreamGraph streamGraph) { return new StreamingJobGraphGenerator( Thread.currentThread().getContextClassLoader(), streamGraph, null, Runnable::run) ...
@Test void testEnabledUnalignedCheckAndDisabledCheckpointing() { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.fromData(0).print(); StreamGraph streamGraph = env.getStreamGraph(); assertThat(streamGraph.getCheckpointConfig().isCheckpointin...
public static <K> PerKeyDigest<K> perKey() { return PerKeyDigest.<K>builder().build(); }
@Test public void perKey() { PCollection<KV<Double, Double>> col = tp.apply(Create.of(stream)) .apply(WithKeys.of(1)) .apply(TDigestQuantiles.<Integer>perKey().withCompression(compression)) .apply(Values.create()) .apply(ParDo.of(new RetrieveQuantiles(quanti...
public void clear() { data.clear(); inverse.clear(); }
@Test public void testClear() { map.clear(); assertSize(0); }
public MessagesRequestSpec simpleQueryParamsToFullRequestSpecification(final String query, final Set<String> streams, final String timerangeKeyword, ...
@Test void throwsExceptionOnEmptyGroups() { assertThrows(IllegalArgumentException.class, () -> toTest.simpleQueryParamsToFullRequestSpecification("*", Set.of(), "42d", List.of(), List.of("avg:joe"))); }
public DoubleArrayAsIterable usingTolerance(double tolerance) { return new DoubleArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_contains_failure() { expectFailureWhenTestingThat(array(1.1, INTOLERABLE_2POINT2, 3.3)) .usingTolerance(DEFAULT_TOLERANCE) .contains(2.2); assertFailureKeys("value of", "expected to contain", "testing whether", "but was"); assertFailureValue("value of", "ar...
public static Object convertAvroFormat( FieldType beamFieldType, Object avroValue, BigQueryUtils.ConversionOptions options) { TypeName beamFieldTypeName = beamFieldType.getTypeName(); if (avroValue == null) { if (beamFieldType.getNullable()) { return null; } else { throw new Il...
@Test public void testMilliPrecisionOk() { long millis = 123456789L; assertThat( BigQueryUtils.convertAvroFormat(FieldType.DATETIME, millis * 1000, REJECT_OPTIONS), equalTo(new Instant(millis))); }
public static InetSocketAddress createResolved(String hostname, int port) { return createInetSocketAddress(hostname, port, true); }
@Test void createResolvedBadValues() { assertThatExceptionOfType(NullPointerException.class) .isThrownBy(() -> AddressUtils.createResolved(null, 0)) .withMessage("hostname"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> AddressUtils.createResolved("hostname", -1)) .w...
private static GuardedByExpression bind(JCTree.JCExpression exp, BinderContext context) { GuardedByExpression expr = BINDER.visit(exp, context); checkGuardedBy(expr != null, String.valueOf(exp)); checkGuardedBy(expr.kind() != Kind.TYPE_LITERAL, "Raw type literal: %s", exp); return expr; }
@Test public void method() { assertThat( bind( "Test", "s.f.g().f.g().lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "import javax.annotation.concurrent.GuardedBy;", ...
public static @Nullable Type inferType(@Nullable Object value) { return Type.tryInferFrom(value); }
@Test public void testKnownTypeInference() { assertEquals(DisplayData.Type.INTEGER, DisplayData.inferType(1234)); assertEquals(DisplayData.Type.INTEGER, DisplayData.inferType(1234L)); assertEquals(DisplayData.Type.FLOAT, DisplayData.inferType(12.3)); assertEquals(DisplayData.Type.FLOAT, DisplayData.in...
@Override public DescribeProducersResult describeProducers(Collection<TopicPartition> topicPartitions, DescribeProducersOptions options) { AdminApiFuture.SimpleAdminApiFuture<TopicPartition, DescribeProducersResult.PartitionProducerState> future = DescribeProducersHandler.newFuture(topicPartitio...
@Test public void testDescribeProducers() throws Exception { try (AdminClientUnitTestEnv env = mockClientEnv()) { TopicPartition topicPartition = new TopicPartition("foo", 0); Node leader = env.cluster().nodes().iterator().next(); expectMetadataRequest(env, topicPartitio...
public Map<String, UserAuth> getUsers() { return users; }
@Test public void testPaths() { Map<String, UserAuth> users = config.getUsers(); UserAuth user = users.get("user1"); Assert.assertEquals("user1", user.getUsername()); Assert.assertEquals("user1pass", user.getPassword()); Assert.assertEquals(1, user.getPaths().size()); ...
@Override public void info(String msg) { logger.info(msg); logInfoToJobDashboard(msg); }
@Test void testInfoLoggingWithoutJob() { jobRunrDashboardLogger.info("simple message"); verify(slfLogger).info("simple message"); }
public static Criterion matchIPDscp(byte ipDscp) { return new IPDscpCriterion(ipDscp); }
@Test public void testMatchIPDscpMethod() { Criterion matchIPDscp = Criteria.matchIPDscp(ipDscp1); IPDscpCriterion ipDscpCriterion = checkAndConvert(matchIPDscp, Criterion.Type.IP_DSCP, IPDscpCriterion.class); as...
@Override public PermissionTicket createTicket(ResourceSet resourceSet, Set<String> scopes) { // check to ensure that the scopes requested are a subset of those in the resource set if (!scopeService.scopesMatch(resourceSet.getScopes(), scopes)) { throw new InsufficientScopeException("Scopes of resource set ar...
@Test public void testCreate_uuid() { PermissionTicket perm = permissionService.createTicket(rs1, scopes1); // we expect this to be a UUID UUID uuid = UUID.fromString(perm.getTicket()); assertNotNull(uuid); }
public int getKafkaSocketTimeout() { return _kafkaSocketTimeout; }
@Test public void testGetKafkaSocketTimeout() { // test default KafkaPartitionLevelStreamConfig config = getStreamConfig("topic", "host1", "", null); Assert.assertEquals(KafkaStreamConfigProperties.LowLevelConsumer.KAFKA_SOCKET_TIMEOUT_DEFAULT, config.getKafkaSocketTimeout()); config = getStr...
@InvokeOnHeader(Web3jConstants.SHH_POST) void shhPost(Message message) throws IOException { String fromAddress = message.getHeader(Web3jConstants.FROM_ADDRESS, configuration::getFromAddress, String.class); String toAddress = message.getHeader(Web3jConstants.TO_ADDRESS, configuration::getToAddress, S...
@Test public void shhPostTest() throws Exception { ShhPost response = Mockito.mock(ShhPost.class); Mockito.when(mockWeb3j.shhPost(any())).thenReturn(request); Mockito.when(request.send()).thenReturn(response); Mockito.when(response.messageSent()).thenReturn(Boolean.TRUE); Ex...
public void setTemplateEntriesForChild(CapacitySchedulerConfiguration conf, QueuePath childQueuePath) { setTemplateEntriesForChild(conf, childQueuePath, false); }
@Test public void testIgnoredWhenNoParent() { conf.set(getTemplateKey(ROOT, "capacity"), "6w"); AutoCreatedQueueTemplate template = new AutoCreatedQueueTemplate(conf, ROOT); template.setTemplateEntriesForChild(conf, ROOT); Assert.assertEquals("weight is set", -1f, conf.getNonLabeledQu...
public JmxCollector register() { return register(PrometheusRegistry.defaultRegistry); }
@Test public void tabularDataCompositeKeyTest() throws Exception { JmxCollector jc = new JmxCollector("---").register(prometheusRegistry); assertEquals( 1, getSampleValue( "org_exist_management_exist_ProcessReport_RunningQueries_id", ...
@Override public final Object unwrap() { return response; }
@Test void unwrap() { HttpServerResponse wrapper = HttpServletResponseWrapper.create(request, response, null); assertThat(wrapper.unwrap()) .isEqualTo(response); }
@Override public void execute(ComputationStep.Context context) { new PathAwareCrawler<>( FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) .buildFor(List.of(duplicationFormula))) .visit(treeRootHolder.getRoot()); }
@Test public void compute_duplicated_lines_counts_lines_from_original_and_InnerDuplicate() { TextBlock original = new TextBlock(1, 5); duplicationRepository.addDuplication(FILE_1_REF, original, new TextBlock(10, 11)); setNewLines(FILE_1); underTest.execute(new TestComputationStepContext()); asse...
public static Ip4Address valueOf(int value) { byte[] bytes = ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array(); return new Ip4Address(bytes); }
@Test(expected = IllegalArgumentException.class) public void testInvalidValueOfEmptyString() { Ip4Address ipAddress; String fromString = ""; ipAddress = Ip4Address.valueOf(fromString); }
@Override public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) { table.refresh(); if (lastPosition != null) { return discoverIncrementalSplits(lastPosition); } else { return discoverInitialSplits(); } }
@Test public void testTableScanThenIncrementalWithNonEmptyTable() throws Exception { appendTwoSnapshots(); ScanContext scanContext = ScanContext.builder() .startingStrategy(StreamingStartingStrategy.TABLE_SCAN_THEN_INCREMENTAL) .build(); ContinuousSplitPlannerImpl splitPla...
@Override public EventPublisher apply(final Class<? extends Event> eventType, final Integer maxQueueSize) { // Like ClientEvent$ClientChangeEvent cache by ClientEvent Class<? extends Event> cachedEventType = eventType.isMemberClass() ? (Class<? extends Event>) eventType.getEnclosingC...
@Test void testApply() { NamingEventPublisherFactory.getInstance().apply(TestEvent.TestEvent1.class, Byte.SIZE); NamingEventPublisherFactory.getInstance().apply(TestEvent.TestEvent2.class, Byte.SIZE); NamingEventPublisherFactory.getInstance().apply(TestEvent.class, Byte.SIZE); String...
@SuppressWarnings("MethodMayBeStatic") @Udf(description = "The 2 input points should be specified as (lat, lon) pairs, measured" + " in decimal degrees. An optional fifth parameter allows to specify either \"MI\" (miles)" + " or \"KM\" (kilometers) as the desired unit for the output measurement. Default i...
@Test public void shouldFailOutOfBoundsCoordinates() { // When: final Exception e = assertThrows( KsqlFunctionException.class, () -> distanceUdf.geoDistance(90.1, -122.1663, -91.5257, -0.1122) ); // Then: assertThat(e.getMessage(), containsString( "valid latitude values fo...
public double d(int[] x, int[] y) { if (x.length != y.length) throw new IllegalArgumentException(String.format("Arrays have different length: x[%d], y[%d]", x.length, y.length)); double dist = 0.0; if (weight == null) { for (int i = 0; i < x.length; i++) { ...
@Test public void testDistanceDouble() { System.out.println("distance"); double[] x = {-2.1968219, -0.9559913, -0.0431738, 1.0567679, 0.3853515}; double[] y = {-1.7781325, -0.6659839, 0.9526148, -0.9460919, -0.3925300}; assertEquals(4.485227, new ManhattanDistance().d(x, y), 1E-6)...
public static java.util.Date convertToDate(Schema schema, Object value) { if (value == null) { throw new DataException("Unable to convert a null value to a schema that requires a value"); } return convertToDate(Date.SCHEMA, schema, value); }
@Test public void shouldConvertDateValues() { java.util.Date current = new java.util.Date(); long currentMillis = current.getTime() % MILLIS_PER_DAY; long days = current.getTime() / MILLIS_PER_DAY; // java.util.Date - just copy java.util.Date d1 = Values.convertToDate(Date.S...
public static VersionRange parse(String rangeString) { validateRangeString(rangeString); Inclusiveness minVersionInclusiveness = rangeString.startsWith("[") ? Inclusiveness.INCLUSIVE : Inclusiveness.EXCLUSIVE; Inclusiveness maxVersionInclusiveness = rangeString.endsWith("]") ? Inclusiveness...
@Test public void parse_withRangeNotEndingWithParenthesis_throwsIllegalArgumentException() { IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> VersionRange.parse("(,1.0")); assertThat(exception) .hasMessageThat() .isEqualTo("Version range must end ...
@Override public ChannelFuture writeFrame(ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags, ByteBuf payload, ChannelPromise promise) { SimpleChannelPromiseAggregator promiseAggregator = new SimpleChannelPromiseAggregator(promise, ctx.channel(), ctx.execut...
@Test public void writeFrameZeroPayload() throws Exception { frameWriter.writeFrame(ctx, (byte) 0xf, 0, new Http2Flags(), Unpooled.EMPTY_BUFFER, promise); byte[] expectedFrameBytes = { (byte) 0x00, (byte) 0x00, (byte) 0x00, // payload length (byte) 0x0f, // payload t...
public static <T extends PipelineOptions> T validate(Class<T> klass, PipelineOptions options) { return validate(klass, options, false); }
@Test public void testWhenOptionIsDefinedInMultipleSuperInterfacesMeetsGroupRequirement() { RightOptions rightOpts = PipelineOptionsFactory.as(RightOptions.class); rightOpts.setFoo("true"); rightOpts.setBoth("bar"); LeftOptions leftOpts = PipelineOptionsFactory.as(LeftOptions.class); leftOpts.set...
@Override public double calcDist3D(double fromLat, double fromLon, double fromHeight, double toLat, double toLon, double toHeight) { double eleDelta = hasElevationDiff(fromHeight, toHeight) ? (toHeight - fromHeight) : 0; double len = calcDist(fromLat, fromLon, toLat, toL...
@Test public void testDistance3dEarthNaN() { DistanceCalc distCalc = new DistanceCalcEarth(); assertEquals(0, distCalc.calcDist3D( 0, 0, 0, 0, 0, Double.NaN ), 1e-6); assertEquals(0, distCalc.calcDist3D( 0, 0, Double.NaN, ...
static String encodeHex(byte[] bytes) { final char[] hex = new char[bytes.length * 2]; int i = 0; for (byte b : bytes) { hex[i++] = HEX_DIGITS[(b >> 4) & 0x0f]; hex[i++] = HEX_DIGITS[b & 0x0f]; } return String.valueOf(hex); }
@Test public void encodeHex_Success() throws Exception { byte[] input = {(byte) 0xFF, 0x00, (byte) 0xA5, 0x5A, 0x12, 0x23}; String expected = "ff00a55a1223"; assertEquals("Encoded hex should match expected", PubkeyUtils.encodeHex(input), expected); }
@Override public String doLayout(ILoggingEvent event) { StringWriter output = new StringWriter(); try (JsonWriter json = new JsonWriter(output)) { json.beginObject(); if (!"".equals(nodeName)) { json.name("nodename").value(nodeName); } json.name("process").value(processKey); ...
@Test public void test_simple_log() { LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level.WARN, "the message", null, new Object[0]); String log = underTest.doLayout(event); JsonLog json = new Gson().fromJson(log, JsonLog.class); assert...
@Override public void close(RemoteInputChannel inputChannel) throws IOException { clientHandler.removeInputChannel(inputChannel); if (closeReferenceCounter.updateAndGet(count -> Math.max(count - 1, 0)) == 0 && !canBeReused()) { closeConnection(); } else { ...
@TestTemplate void testDoublePartitionRequest() throws Exception { final CreditBasedPartitionRequestClientHandler handler = new CreditBasedPartitionRequestClientHandler(); final EmbeddedChannel channel = new EmbeddedChannel(handler); final PartitionRequestClient client = ...
public static Schema createNewSchemaFromFieldsWithReference(Schema schema, List<Schema.Field> fields) { if (schema == null) { throw new IllegalArgumentException("Schema must not be null"); } Schema newSchema = Schema.createRecord(schema.getName(), schema.getDoc(), schema.getNamespace(), schema.isError...
@Test public void testCreateNewSchemaFromFieldsWithReference_NullSchema() { // This test should throw an IllegalArgumentException assertThrows(IllegalArgumentException.class, () -> AvroSchemaUtils.createNewSchemaFromFieldsWithReference(null, Collections.emptyList())); }
public DeleteGranularity deleteGranularity() { String valueAsString = confParser .stringConf() .option(SparkWriteOptions.DELETE_GRANULARITY) .tableProperty(TableProperties.DELETE_GRANULARITY) .defaultValue(TableProperties.DELETE_GRANULARITY_DEFAULT) ...
@TestTemplate public void testDeleteGranularityDefault() { Table table = validationCatalog.loadTable(tableIdent); SparkWriteConf writeConf = new SparkWriteConf(spark, table, ImmutableMap.of()); DeleteGranularity value = writeConf.deleteGranularity(); assertThat(value).isEqualTo(DeleteGranularity.PART...
@VisibleForTesting public static BigDecimal average(LongDecimalWithOverflowAndLongState state, DecimalType type) { return average(state.getLong(), state.getOverflow(), state.getLongDecimal(), type.getScale()); }
@Test public void testUnderflow() { addToState(state, TWO.pow(126).negate()); assertEquals(state.getLong(), 1); assertEquals(state.getOverflow(), 0); assertEquals(state.getLongDecimal(), unscaledDecimal(TWO.pow(126).negate())); addToState(state, TWO.pow(126).negate()); ...
@Override public MaterializedWindowedTable windowed() { return new KsqlMaterializedWindowedTable(inner.windowed()); }
@Test public void shouldCallInnerWindowedWithCorrectParamsOnGet() { // Given: final MaterializedWindowedTable table = materialization.windowed(); givenNoopFilter(); when(project.apply(any(), any(), any())).thenReturn(Optional.of(transformed)); // When: table.get(aKey, partition, windowStartBo...
public static Schema fromTableSchema(TableSchema tableSchema) { return fromTableSchema(tableSchema, SchemaConversionOptions.builder().build()); }
@Test public void testFromTableSchema_flat() { Schema beamSchema = BigQueryUtils.fromTableSchema(BQ_FLAT_TYPE); assertEquals(FLAT_TYPE, beamSchema); }
@Override public List<AdminUserDO> getUserListByPostIds(Collection<Long> postIds) { if (CollUtil.isEmpty(postIds)) { return Collections.emptyList(); } Set<Long> userIds = convertSet(userPostMapper.selectListByPostIds(postIds), UserPostDO::getUserId); if (CollUtil.isEmpty(...
@Test public void testUserListByPostIds() { // 准备参数 Collection<Long> postIds = asSet(10L, 20L); // mock user1 数据 AdminUserDO user1 = randomAdminUserDO(o -> o.setPostIds(asSet(10L, 30L))); userMapper.insert(user1); userPostMapper.insert(new UserPostDO().setUserId(user1...
Boolean validateProduct() { try { ResponseEntity<Boolean> productValidationResult = restTemplateBuilder .build() .postForEntity("http://localhost:30302/product/validate", "validating product", Boolean.class); LOGGER.info("Product validation result: {}", productValidatio...
@Test void testValidateProduct() { // Arrange when(restTemplate.postForEntity(eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class))) .thenReturn(ResponseEntity.ok(true)); // Act Boolean result = orderService.validateProduct(); // Assert assertEquals(true, resul...
public static String readFile(String path) throws IOException { ClassPathResource classPathResource = new ClassPathResource(path); if (classPathResource.exists() && classPathResource.isReadable()) { try (InputStream inputStream = classPathResource.getInputStream()) { return StreamUtils.copyToString(inputSt...
@Test public void testReadNotExistedFile() throws IOException { String content = ResourceFileUtils.readFile("not_existed_test.txt"); assertThat(content).isEqualTo(""); }
public KsqlTarget target(final URI server) { return target(server, Collections.emptyMap()); }
@Test public void shouldOverrideAuthHeader() { // Given: setupExpectedResponse(); // When: KsqlTarget target = ksqlClient.target(serverUri).authorizationHeader("other auth"); target.postKsqlRequest("some ksql", Collections.emptyMap(), Optional.of(123L)); // Then: assertThat(server.getHe...
@Override public DescriptiveUrlBag toUrl(final Path file) { if(DescriptiveUrl.EMPTY == file.attributes().getLink()) { if(null == file.attributes().getFileId()) { return DescriptiveUrlBag.empty(); } final DescriptiveUrl share = toUrl(host, EueShareFeature.f...
@Test public void toUrl() { assertEquals(DescriptiveUrl.EMPTY, new EueShareUrlProvider(new Host(new EueProtocol()), new UserSharesModel()).toUrl( new Path("/f", EnumSet.of(Path.Type.file))).find(DescriptiveUrl.Type.signed)); }
public static int parseEightDigitsLittleEndian(final long bytes) { long val = bytes - 0x3030303030303030L; val = (val * 10) + (val >> 8); val = (((val & 0x000000FF000000FFL) * 0x000F424000000064L) + (((val >> 16) & 0x000000FF000000FFL) * 0x0000271000000001L)) >> 32; retur...
@Test void shouldParseEightDigitsFromAnAsciiEncodedNumberInLittleEndianByteOrder() { final int index = 3; final UnsafeBuffer buffer = new UnsafeBuffer(new byte[16]); for (int i = 10_000_000; i < 100_000_000; i += 111) { buffer.putIntAscii(index, i); final...
public static void executeWithRetry(RetryFunction function) throws Exception { executeWithRetry(maxAttempts, minDelay, function); }
@Test public void retryFunctionThatRecoversAfterBiggerDelay() throws Exception { startTimeMeasure = System.currentTimeMillis(); executeWithRetry(3, 2_000, IOITHelperTest::recoveringFunctionWithBiggerDelay); assertEquals(1, listOfExceptionsThrown.size()); }
public static ParamType getSchemaFromType(final Type type) { return getSchemaFromType(type, JAVA_TO_ARG_TYPE); }
@Test public void shouldGetGenericTriFunction() throws NoSuchMethodException { // Given: final Type genericType = getClass().getMethod("genericTriFunctionType").getGenericReturnType(); // When: final ParamType returnType = UdfUtil.getSchemaFromType(genericType); // Then: assertThat(returnTyp...
@Override public WindowStore<K, V> build() { if (storeSupplier.retainDuplicates() && enableCaching) { log.warn("Disabling caching for {} since store was configured to retain duplicates", storeSupplier.name()); enableCaching = false; } return new MeteredWindowStore<>(...
@Test public void shouldHaveCachingStoreWhenEnabled() { setUp(); final WindowStore<String, String> store = builder.withCachingEnabled().build(); final StateStore wrapped = ((WrappedStateStore) store).wrapped(); assertThat(store, instanceOf(MeteredWindowStore.class)); assertTh...
@Override public String toString() { StringBuilder sb = new StringBuilder("PartitionRuntimeState [" + stamp + "]{" + System.lineSeparator()); for (PartitionReplica replica : allReplicas) { sb.append(replica).append(System.lineSeparator()); } sb.append(", completedMigratio...
@Test public void toString_whenDeserializedTwice() throws UnknownHostException { PartitionRuntimeState state = createPartitionState(0, replica("127.0.0.1", 5701), replica("127.0.0.2", 5702) ); state = serializeAndDeserialize(state); state = serializeA...
@Override public boolean shouldFilter() { RequestContext ctx = RequestContext.getCurrentContext(); return ctx.getThrowable() != null; }
@Test public void testShouldFilter() { SentinelZuulErrorFilter sentinelZuulErrorFilter = new SentinelZuulErrorFilter(); RequestContext ctx = RequestContext.getCurrentContext(); ctx.setThrowable(new RuntimeException()); Assert.assertTrue(sentinelZuulErrorFilter.shouldFilter()); }
public boolean isScheduled() { return (future != null) && !future.isDone(); }
@Test public void isScheduled_doneFuture() { pacer.future = DisabledFuture.INSTANCE; assertThat(pacer.isScheduled()).isFalse(); }
public static void main(final String[] args) { final var nums = new int[]{1, 2, 3, 4, 5}; //Before migration final var oldSystem = new OldArithmetic(new OldSource()); oldSystem.sum(nums); oldSystem.mul(nums); //In process of migration final var halfSystem = new HalfArithmetic(new HalfSource(...
@Test void shouldExecuteWithoutException() { assertDoesNotThrow(() -> App.main(new String[]{})); }
public void isNotEqualTo(@Nullable Object unexpected) { standardIsNotEqualTo(unexpected); }
@Test public void isNotEqualToWithNulls() { Object o = null; assertThat(o).isNotEqualTo("a"); }
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); Assertions.assertEquals("av0b", nodeToStringTransformer.tran...
public static <S> RemoteIterator<S> filteringRemoteIterator( RemoteIterator<S> iterator, FunctionRaisingIOE<? super S, Boolean> filter) { return new FilteringRemoteIterator<>(iterator, filter); }
@Test public void testFiltering() throws Throwable { CountdownRemoteIterator countdown = new CountdownRemoteIterator(100); // only even numbers are passed through RemoteIterator<Integer> it = filteringRemoteIterator( countdown, i -> (i % 2) == 0); verifyInvoked(it, 50, c -> counter++);...
public static Builder newBuilder(PinotConfiguration pinotConfiguration) { Builder builder = new Builder(); String maxConns = pinotConfiguration.getProperty(MAX_CONNS_CONFIG_NAME); if (StringUtils.isNotEmpty(maxConns)) { builder.withMaxConns(Integer.parseInt(maxConns)); } String maxConnsPerRout...
@Test public void testNewBuilder() { // Ensure config values are picked up by the builder. PinotConfiguration pinotConfiguration = new PinotConfiguration(); pinotConfiguration.setProperty(HttpClientConfig.MAX_CONNS_CONFIG_NAME, "123"); pinotConfiguration.setProperty(HttpClientConfig.MAX_CONNS_PER_ROUT...
@POST @Path("/{connector}/restart") @Operation(summary = "Restart the specified connector") public Response restartConnector(final @PathParam("connector") String connector, final @Context HttpHeaders headers, final @DefaultValue("false") @Que...
@Test public void testRestartConnectorOwnerRedirect() throws Throwable { final ArgumentCaptor<Callback<Void>> cb = ArgumentCaptor.forClass(Callback.class); String ownerUrl = "http://owner:8083"; expectAndCallbackException(cb, new NotAssignedException("not owner test", ownerUrl)) ...
@RequiresApi(Build.VERSION_CODES.R) @Override public boolean onInlineSuggestionsResponse(@NonNull InlineSuggestionsResponse response) { final List<InlineSuggestion> inlineSuggestions = response.getInlineSuggestions(); if (inlineSuggestions.size() > 0) { mInlineSuggestionAction.onNewSuggestions(inline...
@Test public void testActionStripNotAddedIfEmptySuggestions() { simulateOnStartInputFlow(); Assert.assertNull( mAnySoftKeyboardUnderTest .getInputViewContainer() .findViewById(R.id.inline_suggestions_strip_root)); Assert.assertFalse(mAnySoftKeyboardUnderTest.onInlineSuggest...
public static List<FieldSchema> convert(Schema schema) { return schema.columns().stream() .map(col -> new FieldSchema(col.name(), convertToTypeString(col.type()), col.doc())) .collect(Collectors.toList()); }
@Test public void testSimpleSchemaConvertToHiveSchema() { assertThat(HiveSchemaUtil.convert(SIMPLE_ICEBERG_SCHEMA)).isEqualTo(SIMPLE_HIVE_SCHEMA); }
@Override public GeometryState createSingleState() { return new SingleGeometryState(); }
@Test public void testCreateSingleStatePresent() { GeometryState state = factory.createSingleState(); state.setGeometry(OGCGeometry.fromText("POINT (1 2)"), 0); assertEquals(OGCGeometry.fromText("POINT (1 2)"), state.getGeometry()); assertTrue(state.getEstimatedSize() > 0, format...
@Override public String getVersionId(final Path file) throws BackgroundException { if(StringUtils.isNotBlank(file.attributes().getVersionId())) { if(log.isDebugEnabled()) { log.debug(String.format("Return version %s from attributes for file %s", file.attributes().getVersionId(), ...
@Test public void getFileIdDirectory() throws Exception { final B2VersionIdProvider fileid = new B2VersionIdProvider(session); final Path bucket = new B2DirectoryFeature(session, fileid).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume))...
@Nonnull @Beta public JobConfig addCustomClasspaths(@Nonnull String name, @Nonnull List<String> paths) { throwIfLocked(); List<String> classpathItems = customClassPaths.computeIfAbsent(name, (k) -> new ArrayList<>()); classpathItems.addAll(paths); return this; }
@Test public void addCustomClasspaths() { JobConfig jobConfig = new JobConfig(); jobConfig.addCustomClasspaths("test", newArrayList("url1", "url2")); jobConfig.addCustomClasspath("test", "url3"); assertThat(jobConfig.getCustomClassPaths()).containsValue( newArrayList...
public RuntimeOptionsBuilder parse(String... args) { return parse(Arrays.asList(args)); }
@Test void disables_default_summary_printer() { RuntimeOptions options = parser .parse("--no-summary", "--glue", "somewhere") .addDefaultSummaryPrinterIfNotDisabled() .build(); Plugins plugins = new Plugins(new PluginFactory(), options); plugin...
public void validateAndMergeOutputParams(StepRuntimeSummary runtimeSummary) { Optional<String> externalJobId = extractExternalJobId(runtimeSummary); if (externalJobId.isPresent()) { Optional<OutputData> outputDataOpt = outputDataDao.getOutputDataForExternalJob(externalJobId.get(), ExternalJobTyp...
@Test public void testMismatchedOutputParameterType() { setupOutputDataDao(); runtimeSummary = runtimeSummaryBuilder() .artifacts(artifacts) .params( Collections.singletonMap( "str_param", LongParameter.builder() ...
public void notifyAllocation( AllocationID allocationId, FineGrainedTaskManagerSlot taskManagerSlot) { Preconditions.checkNotNull(allocationId); Preconditions.checkNotNull(taskManagerSlot); switch (taskManagerSlot.getState()) { case PENDING: ResourceProfil...
@Test void testNotifyAllocationWithoutEnoughResource() { final ResourceProfile totalResource = ResourceProfile.fromResources(1, 100); final FineGrainedTaskManagerRegistration taskManager = new FineGrainedTaskManagerRegistration( TASK_EXECUTOR_CONNECTION, total...
@Override public void onProgressChanged(SeekBar seek, int value, boolean fromTouch) { mValue = value + mMin; if (mValue > mMax) mValue = mMax; if (mValue < mMin) mValue = mMin; if (shouldPersist()) persistInt(mValue); callChangeListener(mValue); if (mCurrentValue != null) mCurrentValue...
@Test public void testValueTemplateChanges() { runTest( () -> { TextView templateView = mTestPrefFragment.getView().findViewById(R.id.pref_current_value); Assert.assertNotNull(templateView); Assert.assertEquals("23 milliseconds", templateView.getText().toString()); ...
Modification modificationFromDescription(String output, ConsoleResult result) throws P4OutputParseException { String[] parts = StringUtils.splitByWholeSeparator(output, SEPARATOR); Pattern pattern = Pattern.compile(DESCRIBE_OUTPUT_PATTERN, Pattern.MULTILINE); Matcher matcher = pattern.matcher(pa...
@Test void shouldParseChangesWithLotsOfFilesWithoutError() throws IOException, P4OutputParseException { final StringWriter writer = new StringWriter(); IOUtils.copy(new ClassPathResource("/BIG_P4_OUTPUT.txt").getInputStream(), writer, Charset.defaultCharset()); String output = writer.toStrin...
@Override public void finished(boolean allStepsExecuted) { if (postProjectAnalysisTasks.length == 0) { return; } ProjectAnalysisImpl projectAnalysis = createProjectAnalysis(allStepsExecuted ? SUCCESS : FAILED); for (PostProjectAnalysisTask postProjectAnalysisTask : postProjectAnalysisTasks) { ...
@Test public void project_uuid_key_and_name_come_from_CeTask() { underTest.finished(true); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); Project project = taskContextCaptor.getValue().getProjectAnalysis().getProject(); assertThat(project.getUuid()).isEqualTo(ceTask.getEntity...
public MetricName metricName(String name, Map<String, String> tags) { return explicitMetricName(this.pkg, this.simpleName, name, tags); }
@Test public void testConstructorWithPackageAndSimpleName() { String packageName = "testPackage"; String simpleName = "testSimple"; KafkaMetricsGroup group = new KafkaMetricsGroup(packageName, simpleName); MetricName metricName = group.metricName("metric-name", Collections.emptyMap()...
public TopicList getHasUnitSubUnUnitTopicList() { TopicList topicList = new TopicList(); try { this.lock.readLock().lockInterruptibly(); for (Entry<String, Map<String, QueueData>> topicEntry : this.topicQueueTable.entrySet()) { String topic = topicEntry.getKey(); ...
@Test public void testGetHasUnitSubUnUnitTopicList() { byte[] topicList = routeInfoManager.getHasUnitSubUnUnitTopicList().encode(); assertThat(topicList).isNotNull(); }
@Bean @ConditionalOnMissingBean(EtcdDataDataChangedListener.class) public DataChangedListener etcdDataChangedListener(final EtcdClient etcdClient) { return new EtcdDataDataChangedListener(etcdClient); }
@Test public void testEtcdDataChangedListener() { EtcdSyncConfiguration etcdListener = new EtcdSyncConfiguration(); EtcdClient client = mock(EtcdClient.class); assertNotNull(etcdListener.etcdDataChangedListener(client)); }
@Override public TableDataConsistencyCheckResult swapToObject(final YamlTableDataConsistencyCheckResult yamlConfig) { if (null == yamlConfig) { return null; } if (!Strings.isNullOrEmpty(yamlConfig.getIgnoredType())) { return new TableDataConsistencyCheckResult(TableDa...
@Test void assertSwapToObjectWithEmptyYamlTableDataConsistencyCheckResultMatched() { YamlTableDataConsistencyCheckResult yamlConfig = new YamlTableDataConsistencyCheckResult(); yamlConfig.setIgnoredType(""); TableDataConsistencyCheckResult result = yamlTableDataConsistencyCheckResultSwapper....
public static PlanNodeStatsEstimate computeAntiJoin(PlanNodeStatsEstimate sourceStats, PlanNodeStatsEstimate filteringSourceStats, VariableReferenceExpression sourceJoinVariable, VariableReferenceExpression filteringSourceJoinVariable) { return compute(sourceStats, filteringSourceStats, sourceJoinVariable, ...
@Test public void testAntiJoin() { // overlapping ranges assertThat(computeAntiJoin(inputStatistics, inputStatistics, u, x)) .variableStats(u, stats -> stats .lowValue(uStats.getLowValue()) .highValue(uStats.getHighValue()) ...
public static void trackJPushAppOpenNotification(String extras, String title, String content, String appPushChannel) { if (!isTrackPushEnabled()) return...
@Test public void trackJPushAppOpenNotification() { PushAutoTrackHelper.trackJPushAppOpenNotification("", "mock_jpush", "mock_content", "JPush"); }
public int read(final MessageHandler handler) { return read(handler, Integer.MAX_VALUE); }
@Test void shouldCopeWithExceptionFromHandler() { final int msgLength = 16; final int recordLength = HEADER_LENGTH + msgLength; final int alignedRecordLength = align(recordLength, ALIGNMENT); final long tail = alignedRecordLength * 2L; final long head = 0L; final ...
public static String toString(InputStream input, String encoding) throws IOException { if (input == null) { return StringUtils.EMPTY; } return (null == encoding) ? toString(new InputStreamReader(input, Constants.ENCODE)) : toString(new InputStreamReader(input, encodin...
@Test void testToStringWithNull() throws IOException { assertEquals("", IoUtils.toString(null, "UTF-8")); }
@Override public Boolean match(final List<ConditionData> conditionDataList, final ServerWebExchange exchange) { return conditionDataList .stream() .allMatch(condition -> PredicateJudgeFactory.judge(condition, buildRealData(condition, exchange))); }
@Test public void testMatch() { assertTrue(matchStrategy.match(conditionDataList, exchange)); }
@PostConstruct public void init() { if (!environment.getAgentStatusEnabled()) { LOG.info("Agent status HTTP API server has been disabled."); return; } InetSocketAddress address = new InetSocketAddress(environment.getAgentStatusHostname(), environment.getAgentStatusPor...
@Test void initShouldNotBlowUpIfServerDoesNotStart() { try (MockedStatic<HttpServer> mockedStaticHttpServer = mockStatic(HttpServer.class)) { setupAgentStatusParameters(); var serverSocket = new InetSocketAddress(hostName, port); var spiedHttpServer = spy(HttpServer.cla...
@Override public void post(final Transfer.Type type, final Map<TransferItem, TransferStatus> files, final ConnectionCallback callback) throws BackgroundException { final Map<TransferItem, TransferStatus> encrypted = new HashMap<>(files.size()); for(Map.Entry<TransferItem, TransferStatus> entry : fil...
@Test public void testPost() throws Exception { final Path vault = new Path("/vault", EnumSet.of(Path.Type.directory)); final NullSession session = new NullSession(new Host(new TestProtocol())) { @Override @SuppressWarnings("unchecked") public <T> T _getFeature(fi...
@VisibleForTesting boolean hasMenuEntries(MenuEntry[] menuEntries) { for (MenuEntry menuEntry : menuEntries) { MenuAction action = menuEntry.getType(); switch (action) { case CANCEL: case WALK: break; case EXAMINE_OBJECT: case EXAMINE_NPC: case EXAMINE_ITEM_GROUND: case EXAMI...
@Test public void testHasMenuEntries() { /* right click examine? right click object? move camera has object op Y Y N Y N N N ...
@Override public List<Intent> compile(PointToPointIntent intent, List<Intent> installable) { log.trace("compiling {} {}", intent, installable); ConnectPoint ingressPoint = intent.filteredIngressPoint().connectPoint(); ConnectPoint egressPoint = intent.filteredEgressPoint().connectPoint(); ...
@Test public void testForwardPathCompilation() { PointToPointIntent intent = makeIntent(new ConnectPoint(DID_1, PORT_1), new ConnectPoint(DID_8, PORT_1)); String[] hops = {S1, S2, S3, S4, S5, S6, S7, S8}; PointToPointIntentCompiler compiler = ...
public synchronized AlertResult send(String content) { SmsResponse smsResponse; if (supplierConfigLoader.isPresent() && supplierConfigLoader.get().getTemplateId() != null) { String templateId = supplierConfigLoader.get().getTemplateId(); smsResponse = smsSendFactory.massTexting(p...
@Ignore @Test public void testSendMsg() { SmsAlert weChatAlert = new SmsAlert(); AlertConfig alertConfig = new AlertConfig(); alertConfig.setType(SmsConstants.TYPE); alertConfig.setParam(SMS_CONFIG); weChatAlert.setConfig(alertConfig); AlertResult alertResult =...
public static String encodeChecked(Integer version, byte[] data) { return encode(addChecksum(version, data)); }
@Test public void encodeCheckedTest() { String a = "hello world"; String encode = Base58.encodeChecked(0, a.getBytes()); assertEquals(1 + "3vQB7B6MrGQZaxCuFg4oh", encode); // 无版本位 encode = Base58.encodeChecked(null, a.getBytes()); assertEquals("3vQB7B6MrGQZaxCuFg4oh", encode); }
static void fireChannelRead(ChannelHandlerContext ctx, List<Object> msgs, int numElements) { if (msgs instanceof CodecOutputList) { fireChannelRead(ctx, (CodecOutputList) msgs, numElements); } else { for (int i = 0; i < numElements; i++) { ctx.fireChannelRead(msgs...
@Test public void testRemoveWhileInCallDecode() { final Object upgradeMessage = new Object(); final ByteToMessageDecoder decoder = new ByteToMessageDecoder() { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { ...
public static ResourceId relativize(ResourceId base, ResourceId child) { checkArgument(child.nodeKeys().size() >= base.nodeKeys().size(), "%s path must be deeper than base prefix %s", child, base); @SuppressWarnings("rawtypes") Iterator<NodeKey> bIt = base.nodeKeys().iterat...
@Test public void testRelativizeEmpty() { ResourceId relDevices = ResourceIds.relativize(DEVICES, DEVICES); // equivalent of . in file path, expressed as ResourceId with empty assertTrue(relDevices.nodeKeys().isEmpty()); }
public Optional<Violation> validate(IndexSetConfig newConfig) { // Don't validate prefix conflicts in case of an update if (Strings.isNullOrEmpty(newConfig.id())) { final Violation prefixViolation = validatePrefix(newConfig); if (prefixViolation != null) { return...
@Test public void validate() throws Exception { final IndexSet indexSet = mock(IndexSet.class); when(indexSetRegistry.iterator()).thenReturn(Collections.singleton(indexSet).iterator()); when(indexSet.getIndexPrefix()).thenReturn("foo"); IndexSetConfig validConfig = testIndexSetConfig...
public static String unescape(String escaped) { boolean escaping = false; StringBuilder newString = new StringBuilder(); for (char c : escaped.toCharArray()) { if (!escaping) { if (c == ESCAPE_CHAR) { escaping = true; } else { newString.append(c); } } else { if (c == 'n') { n...
@Test public void testWithLineBreaks() { assertEquals("Hello\\nWorld!", StringUtil.unescape("Hello\\\\nWorld!")); assertEquals("Hello\nWorld!", StringUtil.unescape("Hello\\nWorld!")); assertEquals("Hello\\\nWorld!", StringUtil.unescape("Hello\\\\\\nWorld!")); assertEquals("\rHello\\\nWorld!", StringUtil.unesca...
@Override public Optional<PersistentQueryMetadata> getPersistentQuery(final QueryId queryId) { return Optional.ofNullable(persistentQueries.get(queryId)); }
@Test public void shouldCallListenerOnError() { // Given: final QueryMetadata.Listener queryListener = givenCreateGetListener(registry, "foo"); final QueryMetadata query = registry.getPersistentQuery(new QueryId("foo")).get(); final QueryError error = new QueryError(123L, "error", Type.USER); // ...
@Override public String getMethod() { return PATH; }
@Test public void testSetMyCommandsWithAllSet() { SetMyCommands setMyCommands = SetMyCommands .builder() .command(BotCommand.builder().command("test").description("Test description").build()) .languageCode("en") .scope(BotCommandScopeDefault.bu...
@Udf public <T> List<T> except( @UdfParameter(description = "Array of values") final List<T> left, @UdfParameter(description = "Array of exceptions") final List<T> right) { if (left == null || right == null) { return null; } final Set<T> distinctRightValues = new HashSet<>(right); fi...
@Test public void shouldExceptNulls() { final List<String> input1 = Arrays.asList("foo", null, "foo", "bar"); final List<String> input2 = Arrays.asList(null, "foo"); final List<String> result = udf.except(input1, input2); assertThat(result, contains("bar")); }
synchronized ActivateWorkResult activateWorkForKey(ExecutableWork executableWork) { ShardedKey shardedKey = executableWork.work().getShardedKey(); Deque<ExecutableWork> workQueue = activeWork.getOrDefault(shardedKey, new ArrayDeque<>()); // This key does not have any work queued up on it. Create one, insert...
@Test public void testActivateWorkForKey_matchingCacheTokens_newWorkTokenGreater_queuedWorkIsActive_QUEUED() { long cacheToken = 1L; long newWorkToken = 10L; long queuedWorkToken = newWorkToken / 2; ShardedKey shardedKey = shardedKey("someKey", 1L); ExecutableWork queuedWork = createWork(cr...