focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Udf(description = "When transforming an array, "
+ "the function provided must have two arguments. "
+ "The two arguments for each function are in order: "
+ "the key and then the value. "
+ "The transformed array is returned."
)
public <T, R> List<R> transformArray(
@UdfParameter(de... | @Test
public void shouldReturnTransformedArray() {
assertThat(udf.transformArray(Collections.emptyList(), function1()), is(Collections.emptyList()));
assertThat(udf.transformArray(Arrays.asList(-5, -2, 0), function1()), is(Arrays.asList(0, 3, 5)));
assertThat(udf.transformArray(Collections.emptyList(), f... |
public static void initStaticGetter(final CompilationDTO<? extends Model> compilationDTO,
final ClassOrInterfaceDeclaration modelTemplate) {
final MethodDeclaration staticGetterMethod =
modelTemplate.getMethodsByName(GET_MODEL).get(0);
final BlockS... | @Test
void initStaticGetter() throws IOException {
final CompilationDTO compilationDTO = CommonCompilationDTO.fromGeneratedPackageNameAndFields(PACKAGE_NAME,
pmmlModel,
... |
public static Gson instance() {
return SingletonHolder.INSTANCE;
} | @Test
void rejectsSerializationOfAESCipherProvider() {
final AESCipherProvider acp = new AESCipherProvider(new TempSystemEnvironment());
try {
final IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () ->
Serialization.instance().toJson(acp));
... |
private RemotingCommand listAcl(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
ListAclsRequestHeader requestHeader = request.decodeCommandCustomHeader(ListAclsRequestHeader.class... | @Test
public void testListAcl() throws RemotingCommandException {
Acl aclInfo = Acl.of(User.of("abc"), Arrays.asList(Resource.of("Topic:*")), Arrays.asList(Action.PUB), Environment.of("192.168.0.1"), Decision.ALLOW);
when(authorizationMetadataManager.listAcl(any(), any())).thenReturn(CompletableFutu... |
public <T> T readValue(Class<T> type, InputStream entityStream) throws IOException {
ObjectReader reader = DeserializerStringCache.init(
Optional.ofNullable(objectReaderByClass.get(type)).map(Supplier::get).orElseGet(()->mapper.readerFor(type))
);
try {
return... | @Test
public void testApplicationXStreamEncodeJacksonDecode() throws Exception {
Application original = APPLICATION_1;
// Encode
ByteArrayOutputStream captureStream = new ByteArrayOutputStream();
new EntityBodyConverter().write(original, captureStream, MediaType.APPLICATION_JSON_TYP... |
public static boolean equivalent(
Expression left, Expression right, Types.StructType struct, boolean caseSensitive) {
return Binder.bind(struct, Expressions.rewriteNot(left), caseSensitive)
.isEquivalentTo(Binder.bind(struct, Expressions.rewriteNot(right), caseSensitive));
} | @Test
public void testIdenticalExpressionIsEquivalent() {
Expression[] exprs =
new Expression[] {
Expressions.isNull("data"),
Expressions.notNull("data"),
Expressions.isNaN("measurement"),
Expressions.notNaN("measurement"),
Expressions.lessThan("id", 5),
... |
@Udf(description = "Returns the sign of an INT value, denoted by 1, 0 or -1.")
public Integer sign(
@UdfParameter(
value = "value",
description = "The value to get the sign of."
) final Integer value
) {
return value == null
? null
: Integer.signum(value);
} | @Test
public void shouldHandlePositive() {
assertThat(udf.sign(1), is(1));
assertThat(udf.sign(1L), is(1));
assertThat(udf.sign(1.5), is(1));
} |
public static String jsonFromMap(Map<String, Object> jsonData) {
try {
JsonDocument json = new JsonDocument();
json.startGroup();
for (String key : jsonData.keySet()) {
Object data = jsonData.get(key);
if (data instanceof Map) {
... | @Test
void testMapAndList() {
Map<String, Object> jsonData = new LinkedHashMap<String, Object>();
jsonData.put("myKey", "myValue");
int[] numbers = {1, 2, 3, 4};
jsonData.put("myNumbers", numbers);
Map<String, Object> jsonData2 = new LinkedHashMap<String, Object>();
... |
@Override
public int write(ByteBuffer sourceBuffer) throws IOException {
if (!isOpen()) {
throw new ClosedChannelException();
}
int totalBytesWritten = 0;
while (sourceBuffer.hasRemaining()) {
int position = sourceBuffer.position();
int bytesWritten = Math.min(sourceBuffer.remaining... | @Test
public void write() throws IOException {
writeFromConfig(s3Config("s3"), false);
writeFromConfig(s3Config("s3"), true);
writeFromConfig(s3ConfigWithSSEAlgorithm("s3"), false);
writeFromConfig(s3ConfigWithSSECustomerKey("s3"), false);
writeFromConfig(s3ConfigWithSSEAwsKeyManagementParams("s3"... |
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 testReplaceAclEntriesMissingOther() throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, GROUP, READ))
.add(aclEntry(ACCESS, OTHER, NONE))
.build();
L... |
public static boolean isPeriodValid(String timeStr) {
try {
PERIOD_FORMATTER.parsePeriod(timeStr);
return true;
} catch (Exception e) {
return false;
}
} | @Test
public void testIsPeriodValid() {
Assert.assertTrue(TimeUtils.isPeriodValid("2d"));
Assert.assertTrue(TimeUtils.isPeriodValid(""));
Assert.assertTrue(TimeUtils.isPeriodValid("1m"));
Assert.assertTrue(TimeUtils.isPeriodValid("2h"));
Assert.assertTrue(TimeUtils.isPeriodValid("-2h"));
Asser... |
@ApiOperation(value = "Create Or Update Rule Chain (saveRuleChain)",
notes = "Create or update the Rule Chain. When creating Rule Chain, platform generates Rule Chain Id as " + UUID_WIKI_LINK +
"The newly created Rule Chain Id will be present in the response. " +
"Spe... | @Test
public void testSaveRuleChain() throws Exception {
RuleChain ruleChain = new RuleChain();
ruleChain.setName("RuleChain");
Mockito.reset(tbClusterService, auditLogService);
RuleChain savedRuleChain = doPost("/api/ruleChain", ruleChain, RuleChain.class);
Assert.assertNo... |
public ListNode2<T> enqueue(T value) {
ListNode2<T> node = new ListNode2<T>(value);
if (size++ == 0) {
head = node;
} else {
node.next = tail;
tail.prev = node;
}
tail = node;
return node;
} | @Test
public void testEnqueue() {
DoublyLinkedList<Integer> list = new DoublyLinkedList<Integer>();
list.enqueue(1);
assertFalse(list.isEmpty());
assertEquals(1, list.size());
assertArrayEquals(new Integer[]{1}, list.toArray());
list.enqueue(2);
assertFalse(li... |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
String s = new String(rawMessage.getPayload(), StandardCharsets.UTF_8);
LOG.trace("Received raw message: {}", s);
String timezoneID = configuration.getString(CK_TIMEZONE);
// previously existing PA input... | @Test
public void syslogValuesTest() {
// Test System message results
PaloAltoCodec codec = new PaloAltoCodec(Configuration.EMPTY_CONFIGURATION, messageFactory);
Message message = codec.decode(new RawMessage(SYSLOG_THREAT_MESSAGE_NO_HOST_DOUBLE_SPACE_DATE.getBytes(StandardCharsets.UTF_8)));... |
public DoubleValue increment(double increment) {
this.value += increment;
this.set = true;
return this;
} | @Test
public void multiples_calls_to_increment_double_increment_the_value() {
DoubleValue variationValue = new DoubleValue()
.increment(10.6)
.increment(95.4);
verifySetVariationValue(variationValue, 106);
} |
public MetadataReportBuilder timeout(Integer timeout) {
this.timeout = timeout;
return getThis();
} | @Test
void timeout() {
MetadataReportBuilder builder = new MetadataReportBuilder();
builder.timeout(1000);
Assertions.assertEquals(1000, builder.build().getTimeout());
} |
public static Builder builder() {
return new Builder();
} | @Test
public void testRoundTripSerDe() throws JsonProcessingException {
// Full request
String fullJson = "{\"removals\":[\"foo\",\"bar\"],\"updates\":{\"owner\":\"Hank\"}}";
assertRoundTripSerializesEquallyFrom(
fullJson,
UpdateNamespacePropertiesRequest.builder().updateAll(UPDATES).remov... |
@Override
public void onExit(Context context, ResourceWrapper rw, int acquireCount, Object... args) {
Entry curEntry = context.getCurEntry();
if (curEntry == null) {
return;
}
for (MetricExtension m : MetricExtensionProvider.getMetricExtensions()) {
if (curEnt... | @Test
public void advancedExtensionOnExit() {
try (MockedStatic<TimeUtil> mocked = super.mockTimeUtil()) {
FakeAdvancedMetricExtension extension = new FakeAdvancedMetricExtension();
MetricExtensionProvider.addMetricExtension(extension);
MetricExitCallback exitCallback = ... |
@Override
public void exportData(JsonWriter writer) throws IOException {
// version tag at the root
writer.name(THIS_VERSION);
writer.beginObject();
// clients list
writer.name(CLIENTS);
writer.beginArray();
writeClients(writer);
writer.endArray();
writer.name(GRANTS);
writer.beginArray();
wr... | @Test
public void testExportClients() throws IOException {
ClientDetailsEntity client1 = new ClientDetailsEntity();
client1.setId(1L);
client1.setAccessTokenValiditySeconds(3600);
client1.setClientId("client1");
client1.setClientSecret("clientsecret1");
client1.setRedirectUris(ImmutableSet.of("http://foo.c... |
public void generate() throws IOException
{
packageNameByTypes.clear();
generatePackageInfo();
generateTypeStubs();
generateMessageHeaderStub();
for (final List<Token> tokens : ir.messages())
{
final Token msgToken = tokens.get(0);
final List<... | @Test
void shouldGenerateBitSetCodecs() throws Exception
{
final UnsafeBuffer buffer = new UnsafeBuffer(new byte[4096]);
generator().generate();
final Object encoder = wrap(buffer, compileCarEncoder().getConstructor().newInstance());
final Object decoder = getCarDecoder(buffer,... |
@Override
public UfsStatus[] listStatus(String path) throws IOException {
return listInternal(path, ListOptions.defaults());
} | @Test
public void testListObjectStorageDescendantTypeNone() throws Throwable {
mObjectUFS = new MockObjectUnderFileSystem(new AlluxioURI("/"),
UnderFileSystemConfiguration.defaults(CONF)) {
final UfsStatus mF1Status = new UfsFileStatus("f1", "", 0L, 0L, "", "", (short) 0777, 0L);
final UfsStat... |
@Override
protected int poll() throws Exception {
// must reset for each poll
shutdownRunningTask = null;
pendingExchanges = 0;
List<software.amazon.awssdk.services.sqs.model.Message> messages = pollingTask.call();
// okay we have some response from aws so lets mark the cons... | @Test
void shouldRequest10MessagesWithSingleReceiveRequest() throws Exception {
// given
var expectedMessages = IntStream.range(0, 10).mapToObj(Integer::toString).toList();
expectedMessages.stream().map(this::message).forEach(sqsClientMock::addMessage);
try (var tested = createConsu... |
static Header[] extractHeaders(AirborneEvent record) {
//Kafka Header -VALUES-
String ifrVfrStatus = record.pairedIfrVfrStatus().toString();
String scoreAsString = Double.toString(record.score());
String epochTimeMs = Long.toString(record.time().toEpochMilli());
Headers headers... | @Test
public void kafkaHeaderContainCorrectSchemaNumber() throws Exception {
AirborneEvent event = AirborneEvent.parse(
new FileReader(getResourceFile("scaryTrackOutput.json"))
);
Header[] headers = extractHeaders(event);
Predicate<Header> isSchemaVerHeader = header ->... |
@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<>(... | @SuppressWarnings("unchecked")
@Test
public void shouldDisableCachingWithRetainDuplicates() {
supplier = Stores.persistentWindowStore("name", Duration.ofMillis(10L), Duration.ofMillis(10L), true);
final StoreBuilder<WindowStore<String, String>> builder = new WindowStoreBuilder<>(
sup... |
@Nullable static String getPropertyIfString(Message message, String name) {
try {
Object o = message.getObjectProperty(name);
if (o instanceof String) return o.toString();
return null;
} catch (Throwable t) {
propagateIfFatal(t);
log(t, "error getting property {0} from message {1}"... | @Test void getPropertyIfString() throws Exception {
message.setStringProperty("b3", "1");
assertThat(MessageProperties.getPropertyIfString(message, "b3"))
.isEqualTo("1");
} |
@Override
public void updateRemove(Object key, Object removedValue) {
int keyHash = key.hashCode();
int removedValueHash = removedValue.hashCode();
int leafOrder = MerkleTreeUtil.getLeafOrderForHash(keyHash, leafLevel);
int leafCurrentHash = getNodeHash(leafOrder);
int leafN... | @Test
public void testUpdateRemove() {
MerkleTree merkleTree = new ArrayMerkleTree(3);
merkleTree.updateAdd(1, 1);
merkleTree.updateAdd(2, 2);
merkleTree.updateAdd(3, 3);
merkleTree.updateRemove(2, 2);
int expectedHash = 0;
expectedHash = MerkleTreeUtil.addH... |
public static <K, V> Write<K, V> write() {
return new AutoValue_CdapIO_Write.Builder<K, V>().build();
} | @Test
public void testWriteObjectCreationFailsIfLockDirIsNull() {
assertThrows(
IllegalArgumentException.class,
() -> CdapIO.<String, String>write().withLocksDirPath(null));
} |
public static String format(String source, Object... parameters) {
String current = source;
for (Object parameter : parameters) {
if (!current.contains("{}")) {
return current;
}
current = current.replaceFirst("\\{\\}", String.valueOf(parameter));
... | @Test
public void testFormat1() {
String fmt = "Some string {} 2 3";
assertEquals("Some string 1 2 3", format(fmt, 1));
} |
@Override
public Mono<GetCurrencyConversionsResponse> getCurrencyConversions(final GetCurrencyConversionsRequest request) {
AuthenticationUtil.requireAuthenticatedDevice();
final CurrencyConversionEntityList currencyConversionEntityList = currencyManager
.getCurrencyConversions()
.orElseThrow... | @Test
void testGetCurrencyConversions() {
final long timestamp = System.currentTimeMillis();
when(currencyManager.getCurrencyConversions()).thenReturn(Optional.of(
new CurrencyConversionEntityList(List.of(
new CurrencyConversionEntity("FOO", Map.of(
"USD", new BigDecimal("2... |
public static Catalog loadIcebergCatalog(SparkSession spark, String catalogName) {
CatalogPlugin catalogPlugin = spark.sessionState().catalogManager().catalog(catalogName);
Preconditions.checkArgument(
catalogPlugin instanceof HasIcebergCatalog,
String.format(
"Cannot load Iceberg ca... | @Test
public void testLoadIcebergCatalog() throws Exception {
spark.conf().set("spark.sql.catalog.test_cat", SparkCatalog.class.getName());
spark.conf().set("spark.sql.catalog.test_cat.type", "hive");
Catalog catalog = Spark3Util.loadIcebergCatalog(spark, "test_cat");
assertThat(catalog)
.as("... |
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public void executeUpdate(final LockClusterStatement sqlStatement, final ContextManager contextManager) {
checkState(contextManager);
checkAlgorithm(sqlStatement);
LockContext lockContext = contextManager.getComputeNodeInstanceContex... | @Test
void assertExecuteUpdateWithLockedCluster() {
ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS);
when(contextManager.getStateContext().getClusterState()).thenReturn(ClusterState.UNAVAILABLE);
assertThrows(LockedClusterException.class, () -> executor.execute... |
public <T> void resolve(T resolvable) {
ParamResolver resolver = this;
if (ParamScope.class.isAssignableFrom(resolvable.getClass())) {
ParamScope newScope = (ParamScope) resolvable;
resolver = newScope.applyOver(resolver);
}
resolveStringLeaves(resolvable, resolve... | @Test
public void shouldResolveTopLevelAttribute() {
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("cruise", "dev", "ant");
pipelineConfig.setLabelTemplate("2.1-${COUNT}");
setField(pipelineConfig, PipelineConfig.LOCK_BEHAVIOR, "#{partial}Finished");
new P... |
public static DataMap getAnnotationsMap(Annotation[] as)
{
return annotationsToData(as, true);
} | @Test(description = "Non-empty annotation, scalar members, overridden values: data map with annotation + members")
public void succeedsOnSupportedScalarMembersWithOverriddenValues()
{
@SupportedScalarMembers(
annotationMember = @Key(name = "id", type = String.class),
booleanMember = !SupportedSc... |
@Override
public void startLeaderElection(LeaderContender contender) throws Exception {
Preconditions.checkNotNull(contender);
parentService.register(componentId, contender);
} | @Test
void testContenderRegistration() throws Exception {
final AtomicReference<String> componentIdRef = new AtomicReference<>();
final AtomicReference<LeaderContender> contenderRef = new AtomicReference<>();
final DefaultLeaderElection.ParentService parentService =
TestingAb... |
@Override
public void move(String noteId, String notePath, String newNotePath, AuthenticationInfo subject) throws IOException {
Preconditions.checkArgument(StringUtils.isNotEmpty(noteId));
BlobId sourceBlobId = makeBlobId(noteId, notePath);
BlobId destinationBlobId = makeBlobId(noteId, newNotePath);
t... | @Test
void testMoveFolder_nonexistent() throws Exception {
zConf.setProperty(ConfVars.ZEPPELIN_NOTEBOOK_GCS_STORAGE_DIR.getVarName(), DEFAULT_URL);
this.notebookRepo = new GCSNotebookRepo(zConf, noteParser, storage);
assertThrows(IOException.class, () -> {
notebookRepo.move("/name", "/name_new", AUT... |
void wakeUp(boolean taskOnly) {
// Synchronize to make sure the wake up only works for the current invocation of runOnce().
lock.lock();
try {
wakeUpUnsafe(taskOnly);
} finally {
lock.unlock();
}
} | @Test
public void testWakeup() throws InterruptedException {
final int numSplits = 3;
final int numRecordsPerSplit = 10_000;
final int wakeupRecordsInterval = 10;
final int numTotalRecords = numRecordsPerSplit * numSplits;
FutureCompletingBlockingQueue<RecordsWithSplitIds<in... |
public CompletableFuture<Void> acknowledgeOnClose(final Map<TopicIdPartition, Acknowledgements> acknowledgementsMap,
final long deadlineMs) {
final Cluster cluster = metadata.fetch();
final AtomicInteger resultCount = new AtomicInteger();
fin... | @Test
public void testAcknowledgeOnClose() {
buildRequestManager();
assignFromSubscribed(Collections.singleton(tp0));
// normal fetch
assertEquals(1, sendFetches());
assertFalse(shareConsumeRequestManager.hasCompletedFetches());
client.prepareResponse(fullFetchResp... |
@Override
public CloseableIterator<ScannerReport.Duplication> readComponentDuplications(int componentRef) {
ensureInitialized();
return delegate.readComponentDuplications(componentRef);
} | @Test
public void verify_readComponentDuplications_returns_Issues() {
writer.writeComponentDuplications(COMPONENT_REF, of(DUPLICATION));
try (CloseableIterator<ScannerReport.Duplication> res = underTest.readComponentDuplications(COMPONENT_REF)) {
assertThat(res.next()).isEqualTo(DUPLICATION);
ass... |
@SuppressWarnings("java:S2583")
public static boolean verify(@NonNull JWKSet jwks, @NonNull JWSObject jws) {
if (jwks == null) {
throw new IllegalArgumentException("no JWKS provided to verify JWS");
}
if (jwks.getKeys() == null || jwks.getKeys().isEmpty()) {
return false;
}
var head... | @Test
void verifyGarbageSignature() throws ParseException {
var jws = toJws(ECKEY, "test").serialize();
jws = garbageSignature(jws);
var in = JWSObject.parse(jws);
// when & then
assertFalse(JwsVerifier.verify(JWKS, in));
} |
@Override
public void run() {
try {
backgroundJobServer.getJobSteward().notifyThreadOccupied();
MDCMapper.loadMDCContextFromJob(job);
performJob();
} catch (Exception e) {
if (isJobDeletedWhileProcessing(e)) {
// nothing to do anymore a... | @Test
void onFailureAfterDeleteTheIllegalJobStateChangeIsCatchedAndLogged() throws Exception {
Job job = anEnqueuedJob().build();
mockBackgroundJobRunner(job, jobFromStorage -> {
jobFromStorage.delete("for testing");
jobFromStorage.delete("to throw exception that will bring ... |
static File getFileFromJar(URL retrieved) throws URISyntaxException, IOException {
logger.debug("getFileFromJar {}", retrieved);
String fileName = retrieved.getFile();
if (fileName.contains("/")) {
fileName = fileName.substring(fileName.lastIndexOf('/'));
}
String jar... | @Test
void getFileFromJar() throws URISyntaxException, IOException {
URL jarUrl = getJarUrl();
assertThat(jarUrl).isNotNull();
File retrieved = MemoryFileUtils.getFileFromJar(jarUrl);
assertThat(retrieved).isNotNull();
assertThat(retrieved).isInstanceOf(MemoryFile.class);
... |
public Exchange createDbzExchange(DebeziumConsumer consumer, final SourceRecord sourceRecord) {
final Exchange exchange;
if (consumer != null) {
exchange = consumer.createExchange(false);
} else {
exchange = super.createExchange();
}
final Message message... | @Test
void testIfCreatesExchangeFromSourceRecordOtherThanStruct() {
final SourceRecord sourceRecord = createStringRecord();
final Exchange exchange = debeziumEndpoint.createDbzExchange(null, sourceRecord);
final Message inMessage = exchange.getIn();
assertNotNull(exchange);
... |
public final void removeOutboundHandler() {
checkAdded();
outboundCtx.remove();
} | @Test
public void testOutboundRemoveBeforeAdded() {
final CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler> handler =
new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
new ChannelInboundHandlerAdapter(), new Cha... |
public static SchemaPairCompatibility checkReaderWriterCompatibility(final Schema reader, final Schema writer) {
final SchemaCompatibilityResult compatibility = new ReaderWriterCompatibilityChecker().getCompatibility(reader,
writer);
final String message;
switch (compatibility.getCompatibility()) {... | @Test
void unionReaderWriterSubsetIncompatibility() {
final Schema unionWriter = Schema.createUnion(list(INT_SCHEMA, STRING_SCHEMA, LONG_SCHEMA));
final Schema unionReader = Schema.createUnion(list(INT_SCHEMA, STRING_SCHEMA));
final SchemaPairCompatibility result = checkReaderWriterCompatibility(unionRead... |
@Override
public void run() {
// top-level command, do nothing
} | @Test
public void test_submit_job_with_hazelcast_classes() throws IOException {
Logger logger = (Logger) LogManager.getLogger(MainClassNameFinder.class);
Appender appender = mock(Appender.class);
when(appender.getName()).thenReturn("Mock Appender");
when(appender.isStarted()).thenRet... |
public static Impl join(By clause) {
return new Impl(new JoinArguments(clause));
} | @Test
@Category(NeedsRunner.class)
public void testFullOuterJoin() {
List<Row> pc1Rows =
Lists.newArrayList(
Row.withSchema(CG_SCHEMA_1).addValues("user1", 1, "us").build(),
Row.withSchema(CG_SCHEMA_1).addValues("user1", 2, "us").build(),
Row.withSchema(CG_SCHEMA_1).a... |
@SuppressWarnings("unchecked")
public static Class<? extends UuidGenerator> parseUuidGenerator(String cucumberUuidGenerator) {
Class<?> uuidGeneratorClass;
try {
uuidGeneratorClass = Class.forName(cucumberUuidGenerator);
} catch (ClassNotFoundException e) {
throw new ... | @Test
void parseUuidGenerator_not_a_class() {
// When
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> UuidGeneratorParser.parseUuidGenerator("java.lang.NonExistingClassName"));
// Then
assertThat(exception.getMessage(), Matchers.co... |
@Override
public Mono<AuthorizingVisitor> visitRules(Authentication authentication,
RequestInfo requestInfo) {
var roleNames = AuthorityUtils.authoritiesToRoles(authentication.getAuthorities());
var record = new AttributesRecord(authentication, requestInfo);
var visitor = new Authori... | @Test
void visitRules() {
when(roleService.listDependenciesFlux(Set.of("ruleReadPost")))
.thenReturn(Flux.just(mockRole()));
var fakeUser = new User("admin", "123456", createAuthorityList("ruleReadPost"));
var authentication = authenticated(fakeUser, fakeUser.getPassword(),
... |
public Canvas canvas() {
Canvas canvas = new Canvas(getLowerBound(), getUpperBound());
canvas.add(this);
if (name != null) {
canvas.setTitle(name);
}
return canvas;
} | @Test
public void testContour() throws Exception {
System.out.println("Contour");
var canvas = Heatmap.of(Z, 256).canvas();
canvas.add(Contour.of(Z));
canvas.window();
} |
public static Point<AriaCsvHit> parsePointFromAriaCsv(String rawCsvText) {
AriaCsvHit ariaHit = AriaCsvHit.from(rawCsvText);
Position pos = new Position(ariaHit.time(), ariaHit.latLong(), ariaHit.altitude());
return new Point<>(pos, null, ariaHit.linkId(), ariaHit);
} | @Test
public void exampleParsing_withExtraData() {
String rawCsv = "PRIMARY_PARTITION,SECONDARY_PARTITION,2018-03-24T14:41:09.371Z,vehicleIdNumber,42.9525,-83.7056,2700,EXTRA_FIELD_A,EXTRA_FIELD_B";
Point<AriaCsvHit> pt = AriaCsvHits.parsePointFromAriaCsv(rawCsv);
assertThat(pt.time(), is... |
void resolveSelectors(EngineDiscoveryRequest request, CucumberEngineDescriptor engineDescriptor) {
Predicate<String> packageFilter = buildPackageFilter(request);
resolve(request, engineDescriptor, packageFilter);
filter(engineDescriptor, packageFilter);
pruneTree(engineDescriptor);
} | @Test
void resolveRequestWithUniqueIdSelectorFromJarUri() {
String root = Paths.get("").toAbsolutePath().toUri().getSchemeSpecificPart();
URI uri = URI.create("jar:file:" + root + "/src/test/resources/feature.jar!/single.feature");
DiscoverySelector resource = selectUri(uri);
Engine... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
if(containerService.isContainer(file)) {
final PathAttributes attributes = new PathAttributes();
... | @Test(expected = NotfoundException.class)
public void testDetermineRegionVirtualHostStyle() throws Exception {
final S3AttributesFinderFeature f = new S3AttributesFinderFeature(virtualhost, new S3AccessControlListFeature(virtualhost));
final Path file = new Path(new AlphanumericRandomStringService()... |
public TargetAssignmentResult build() throws PartitionAssignorException {
Map<String, MemberSubscriptionAndAssignmentImpl> memberSpecs = new HashMap<>();
// Prepare the member spec for all members.
members.forEach((memberId, member) ->
memberSpecs.put(memberId, createMemberSubscript... | @Test
public void testUpdateMember() {
TargetAssignmentBuilderTestContext context = new TargetAssignmentBuilderTestContext(
"my-group",
20
);
Uuid fooTopicId = context.addTopicMetadata("foo", 6, Collections.emptyMap());
Uuid barTopicId = context.addTopicMetad... |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatLongLiteral() {
assertThat(ExpressionFormatter.formatExpression(new LongLiteral(1)), equalTo("1"));
} |
public SerializableFunction<T, Row> getToRowFunction() {
return toRowFunction;
} | @Test
public void testRepeatedProtoToRow() throws InvalidProtocolBufferException {
ProtoDynamicMessageSchema schemaProvider =
schemaFromDescriptor(RepeatPrimitive.getDescriptor());
SerializableFunction<DynamicMessage, Row> toRow = schemaProvider.getToRowFunction();
assertEquals(REPEATED_ROW, toRow... |
public FactMapping addFactMapping(int index, FactMapping toClone) {
FactMapping toReturn = toClone.cloneFactMapping();
factMappings.add(index, toReturn);
return toReturn;
} | @Test
public void addFactMapping_byFactIdentifierAndExpressionIdentifier_fail() {
modelDescriptor.addFactMapping(factIdentifier, expressionIdentifier);
assertThatIllegalArgumentException().isThrownBy(() -> modelDescriptor.addFactMapping(factIdentifier, expressionIdentifier));
} |
@Subscribe
public void onGameTick(GameTick event)
{
final Player local = client.getLocalPlayer();
final Duration waitDuration = Duration.ofMillis(config.getIdleNotificationDelay());
lastCombatCountdown = Math.max(lastCombatCountdown - 1, 0);
if (client.getGameState() != GameState.LOGGED_IN
|| local == nul... | @Test
public void testSpecRegen()
{
when(config.getSpecNotification()).thenReturn(Notification.ON);
when(config.getSpecEnergyThreshold()).thenReturn(50);
when(client.getVarpValue(eq(VarPlayer.SPECIAL_ATTACK_PERCENT))).thenReturn(400); // 40%
plugin.onGameTick(new GameTick()); // once to set lastSpecEnergy to... |
public static String getMaskedStatement(final String query) {
try {
final ParseTree tree = DefaultKsqlParser.getParseTree(query);
return new Visitor().visit(tree);
} catch (final Exception | StackOverflowError e) {
return fallbackMasking(query);
}
} | @Test
public void shouldMaskFallbackInsertStatement() {
// Given
final String query = "--this is a comment. \n"
+ "INSERT INTO foo (KEY_COL, COL_A) VALUES"
+ "(\"key\", 0.125, '{something}', 1, C, 2.3E);";
// When
final String maskedQuery = QueryMask.getMaskedStatement(query);
//... |
public Host parse(final String uri) throws HostParserException {
final Host host = new HostParser(factory).get(uri);
if(input.hasOption(TerminalOptionsBuilder.Params.region.name())) {
host.setRegion(input.getOptionValue(TerminalOptionsBuilder.Params.region.name()));
}
final P... | @Test
public void testProfile() throws Exception {
final CommandLineParser parser = new PosixParser();
final CommandLine input = parser.parse(new Options(), new String[]{});
final ProtocolFactory factory = new ProtocolFactory(new LinkedHashSet<>(Collections.singleton(new SwiftProtocol())));
... |
public static FlinkPod loadPodFromTemplateFile(
FlinkKubeClient kubeClient, File podTemplateFile, String mainContainerName) {
final KubernetesPod pod = kubeClient.loadPodFromTemplateFile(podTemplateFile);
final List<Container> otherContainers = new ArrayList<>();
Container mainContai... | @Test
void testLoadPodFromTemplateAndCheckInitContainer() {
final FlinkPod flinkPod =
KubernetesUtils.loadPodFromTemplateFile(
flinkKubeClient,
KubernetesPodTemplateTestUtils.getPodTemplateFile(),
KubernetesPodTemplateTe... |
public void append(AbortedTxn abortedTxn) throws IOException {
lastOffset.ifPresent(offset -> {
if (offset >= abortedTxn.lastOffset())
throw new IllegalArgumentException("The last offset of appended transactions must increase sequentially, but "
+ abortedTxn.lastO... | @Test
public void testLastOffsetCannotDecrease() throws IOException {
index.append(new AbortedTxn(1L, 5, 15, 13));
assertThrows(IllegalArgumentException.class, () -> index.append(new AbortedTxn(0L, 0,
10, 11)));
} |
public String failureMessage(
int epoch,
OptionalLong deltaUs,
boolean isActiveController,
long lastCommittedOffset
) {
StringBuilder bld = new StringBuilder();
if (deltaUs.isPresent()) {
bld.append("event failed with ");
} else {
bld.a... | @Test
public void testNullPointerExceptionFailureMessageWhenInactive() {
assertEquals("event failed with NullPointerException (treated as UnknownServerException) " +
"at epoch 123 in 40 microseconds. The controller is already in standby mode.",
NULL_POINTER.failureMessage(123, Op... |
@Override
public AvailabilityWithBacklog getAvailabilityAndBacklog(boolean isCreditAvailable) {
synchronized (lock) {
try {
cacheBuffer();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (cachedBuffers.isEmpty()) {... | @Test
void testGetAvailabilityAndBacklog() throws IOException {
view0.notifyDataAvailable();
view1.notifyDataAvailable();
ResultSubpartitionView.AvailabilityWithBacklog availabilityAndBacklog1 =
view.getAvailabilityAndBacklog(false);
assertThat(availabilityAndBacklog... |
private UiLinkId(ElementId a, PortNumber pa, ElementId b, PortNumber pb) {
elementA = a;
portA = pa;
elementB = b;
portB = pb;
regionA = null;
regionB = null;
boolean isEdgeLink = (a instanceof HostId);
// NOTE: for edgelinks, hosts are always element A... | @Test
public void sameDevsDiffPorts() {
title("sameDevsDiffPorts");
UiLinkId one = UiLinkId.uiLinkId(LINK_X1_TO_Y2);
UiLinkId other = UiLinkId.uiLinkId(LINK_X1_TO_Y3);
print("link one: %s", one);
print("link other: %s", other);
assertNotEquals("equiv?", one, other);
... |
@Override
Class<?> getReturnType() {
return null;
} | @Test
public void test_getReturnType() {
Class<?> returnType = NullMultiValueGetter.NULL_MULTIVALUE_GETTER.getReturnType();
assertNull(returnType);
} |
public static ChangesRequiringRestart getChangesRequiringRestart(ConfigInstance from, ConfigInstance to) {
Class<?> clazz = from.getClass();
if (!clazz.equals(to.getClass())) {
throw new IllegalArgumentException(String.format("%s != %s", clazz, to.getClass()));
}
try {
... | @Test
void requireThatGetChangesRequiringRestartValidatesParameterTypes() {
assertThrows(IllegalArgumentException.class, () -> {
ReflectionUtil.getChangesRequiringRestart(new RestartConfig(), new NonRestartConfig());
});
} |
public static int compareVersions(String firstVersion, String secondVersion) {
if (firstVersion.equals(secondVersion)) {
return 0;
}
return getVersionFromStr(firstVersion).compareTo(getVersionFromStr(secondVersion));
} | @Test
public void testVersionComparison() throws Exception {
assertTrue(TransformUpgrader.compareVersions("2.53.0", "2.53.0") == 0);
assertTrue(TransformUpgrader.compareVersions("2.53.0", "2.55.0") < 0);
assertTrue(TransformUpgrader.compareVersions("2.53.0", "2.55.0-SNAPSHOT") < 0);
assertTrue(Transf... |
@Override
public InsertValuesToken generateSQLToken(final InsertStatementContext insertStatementContext) {
Optional<SQLToken> insertValuesToken = findPreviousSQLToken(InsertValuesToken.class);
if (insertValuesToken.isPresent()) {
processPreviousSQLToken(insertStatementContext, (InsertVal... | @Test
void assertGenerateSQLTokenFromPreviousSQLTokens() {
generator.setDatabaseName("db-001");
generator.setPreviousSQLTokens(EncryptGeneratorFixtureBuilder.getPreviousSQLTokens());
generator.setDatabaseName("db_schema");
assertThat(generator.generateSQLToken(EncryptGeneratorFixture... |
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 shouldFindNonVarargWithNullValues() {
// Given:
givenFunctions(
function(EXPECTED, -1, STRING)
);
// When:
final KsqlScalarFunction fun = udfIndex.getFunction(Collections.singletonList(null));
// Then:
assertThat(fun.name(), equalTo(EXPECTED));
} |
static void removeAllFromManagers(Iterable<DoFnLifecycleManager> managers) throws Exception {
Collection<Exception> thrown = new ArrayList<>();
for (DoFnLifecycleManager manager : managers) {
thrown.addAll(manager.removeAll());
}
if (!thrown.isEmpty()) {
Exception overallException = new Exce... | @Test
public void whenManagersSucceedSucceeds() throws Exception {
PipelineOptions options = PipelineOptionsFactory.create();
DoFnLifecycleManager first = DoFnLifecycleManager.of(new EmptyFn(), options);
DoFnLifecycleManager second = DoFnLifecycleManager.of(new EmptyFn(), options);
DoFnLifecycleManage... |
@GET
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Get prekey count",
description = "Gets the number of one-time prekeys uploaded for this device and still available")
@ApiResponse(responseCode = "200", description = "Body contains the number of available one-time prekeys for the device.", use... | @Test
void checkKeysIncorrectDigestLength() {
try (final Response response =
resources.getJerseyTest()
.target("/v2/keys/check")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.post(Entity.enti... |
protected void stopServices() {
this.statusBackingStore.stop();
this.configBackingStore.stop();
this.worker.stop();
this.connectorExecutor.shutdown();
Utils.closeQuietly(this.connectorClientConfigOverridePolicy, "connector client config override policy");
} | @Test
public void testConnectorClientConfigOverridePolicyClose() {
SampleConnectorClientConfigOverridePolicy noneConnectorClientConfigOverridePolicy = new SampleConnectorClientConfigOverridePolicy();
AbstractHerder herder = testHerder(noneConnectorClientConfigOverridePolicy);
herder.stopSe... |
protected int getDiffSize() {
return brokerConfigDiff.size();
} | @Test
public void testChangedKRaftControllerConfig() {
List<ConfigEntry> desiredControllerConfig = singletonList(new ConfigEntry("controller.quorum.election.timeout.ms", "5000"));
List<ConfigEntry> currentControllerConfig = singletonList(new ConfigEntry("controller.quorum.election.timeout.ms", "1000... |
@Override
public List<MenuDO> getMenuList() {
return menuMapper.selectList();
} | @Test
public void testGetMenuList_ids() {
// mock 数据
MenuDO menu100 = randomPojo(MenuDO.class);
menuMapper.insert(menu100);
MenuDO menu101 = randomPojo(MenuDO.class);
menuMapper.insert(menu101);
// 准备参数
Collection<Long> ids = Collections.singleton(menu100.getI... |
public SearchResults<GroupInformation> search(DbSession dbSession, GroupSearchRequest groupSearchRequest) {
GroupDto defaultGroup = defaultGroupFinder.findDefaultGroup(dbSession);
GroupQuery query = toGroupQuery(groupSearchRequest);
int limit = dbClient.groupDao().countByQuery(dbSession, query);
if (gr... | @Test
public void search_whenSeveralGroupFound_returnsThem() {
GroupDto groupDto1 = mockGroupDto("1");
GroupDto groupDto2 = mockGroupDto("2");
GroupDto defaultGroup = mockDefaultGroup();
when(dbClient.groupDao().selectByQuery(eq(dbSession), queryCaptor.capture(), eq(5), eq(24)))
.thenReturn(Lis... |
public static String decode(InputStream qrCodeInputStream) {
BufferedImage image = null;
try{
image = ImgUtil.read(qrCodeInputStream);
return decode(image);
} finally {
ImgUtil.flush(image);
}
} | @Test
@Disabled
public void decodeTest2() {
// 条形码
final String decode = QrCodeUtil.decode(FileUtil.file("d:/test/90.png"));
//Console.log(decode);
} |
@Override
public void checkTopicAccess(
final KsqlSecurityContext securityContext,
final String topicName,
final AclOperation operation
) {
final Set<AclOperation> authorizedOperations = securityContext.getServiceContext()
.getTopicClient().describeTopic(topicName).authorizedOperations... | @Test
public void shouldAllowIfAuthorizedOperationsIsNull() {
// Checks compatibility with unsupported Kafka authorization checks
// Given:
givenTopicPermissions(TOPIC_1, null);
// When/Then:
accessValidator.checkTopicAccess(securityContext, TOPIC_NAME_1, AclOperation.READ);
} |
protected String[] getQueryParamValues(MultiValuedTreeMap<String, String> qs, String key, boolean isCaseSensitive) {
List<String> value = getQueryParamValuesAsList(qs, key, isCaseSensitive);
if (value == null){
return null;
}
return value.toArray(new String[0]);
} | @Test
void queryParamValues_getQueryParamValues_caseInsensitive() {
AwsProxyHttpServletRequest request = new AwsProxyHttpServletRequest(new AwsProxyRequest(), mockContext, null);
MultiValuedTreeMap<String, String> map = new MultiValuedTreeMap<>();
map.add("test", "test");
map.add("te... |
public String getString(String key, String _default) {
Object object = map.get(key);
return object instanceof String ? (String) object : _default;
} | @Test
public void keyCannotHaveAnyCasing() {
PMap subject = new PMap("foo=valueA|bar=valueB");
assertEquals("valueA", subject.getString("foo", ""));
assertEquals("", subject.getString("Foo", ""));
} |
@Override
synchronized int numBuffered() {
return wrapped.numBuffered();
} | @Test
public void testNumBuffered() {
final int numBuffered = 1;
when(wrapped.numBuffered()).thenReturn(numBuffered);
final int result = synchronizedPartitionGroup.numBuffered();
assertEquals(numBuffered, result);
verify(wrapped, times(1)).numBuffered();
} |
public static Version value2Version(int value) {
int length = Version.values().length;
if (value >= length) {
return Version.values()[length - 1];
}
return Version.values()[value];
} | @Test
public void testValue2Version_HigherVersion() throws Exception {
assertThat(MQVersion.value2Version(Integer.MAX_VALUE)).isEqualTo(MQVersion.Version.HIGHER_VERSION);
} |
public static RestSettingBuilder get(final String id) {
return get(eq(checkId(id)));
} | @Test
public void should_get_resource_by_id_with_request_config() throws Exception {
Plain resource1 = new Plain();
resource1.code = 1;
resource1.message = "hello";
Plain resource2 = new Plain();
resource2.code = 2;
resource2.message = "world";
server.resour... |
@Override
public void onDisConnect(Connection connection) {
connected = false;
LogUtils.NAMING_LOGGER.warn("Grpc connection disconnect, mark to redo");
synchronized (registeredInstances) {
registeredInstances.values().forEach(instanceRedoData -> instanceRedoData.setRegistered(fal... | @Test
void testOnDisConnect() {
redoService.onConnected(new TestConnection(new RpcClient.ServerInfo()));
redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance());
redoService.instanceRegistered(SERVICE, GROUP);
redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER);
... |
public abstract VoiceInstructionValue getConfigForDistance(
double distance,
String turnDescription,
String thenVoiceInstruction); | @Test
public void germanFixedDistanceInitialVICMetricTest() {
FixedDistanceVoiceInstructionConfig configMetric = new FixedDistanceVoiceInstructionConfig(IN_HIGHER_DISTANCE_PLURAL.metric,
trMap, Locale.GERMAN, 2000, 2);
compareVoiceInstructionValues(
2000,
... |
public static <T> AsList<T> asList() {
return new AsList<>(null, false);
} | @Test
@Category(ValidatesRunner.class)
public void testListWithRandomAccessSideInput() {
final PCollectionView<List<Integer>> view =
pipeline
.apply("CreateSideInput", Create.of(11, 13, 17, 23))
.apply(View.<Integer>asList().withRandomAccess());
PCollection<Integer> output ... |
static MessageListener create(MessageListener delegate, JmsTracing jmsTracing) {
if (delegate == null) return null;
if (delegate instanceof TracingMessageListener) return delegate;
return new TracingMessageListener(delegate, jmsTracing, true);
} | @Test void null_listener_if_delegate_is_null() {
assertThat(TracingMessageListener.create(null, jmsTracing))
.isNull();
} |
@Override
public synchronized void stateChanged(CuratorFramework client, ConnectionState newState) {
if (circuitBreaker.isOpen()) {
handleOpenStateChange(newState);
} else {
handleClosedStateChange(newState);
}
} | @Test
public void testResetsAfterReconnect() throws Exception {
RecordingListener recordingListener = new RecordingListener();
TestRetryPolicy retryPolicy = new TestRetryPolicy();
CircuitBreakingConnectionStateListener listener =
new CircuitBreakingConnectionStateListener(dum... |
@Override
public Collection<DatabasePacket> execute() throws SQLException {
switch (packet.getType()) {
case 'S':
return describePreparedStatement();
case 'P':
return Collections.singleton(portalContext.get(packet.getName()).describe());
de... | @Test
void assertDescribePreparedStatementInsertWithReturningClause() throws SQLException {
when(packet.getType()).thenReturn('S');
final String statementId = "S_2";
when(packet.getName()).thenReturn(statementId);
String sql = "insert into t_order (k, c, pad) values (?, ?, ?) "
... |
public Future<KafkaVersionChange> reconcile() {
return getVersionFromController()
.compose(i -> getPods())
.compose(this::detectToAndFromVersions)
.compose(i -> prepareVersionChange());
} | @Test
public void testNoopWithCustomMetadataVersion(VertxTestContext context) {
String kafkaVersion = VERSIONS.defaultVersion().version();
String interBrokerProtocolVersion = VERSIONS.defaultVersion().protocolVersion();
String logMessageFormatVersion = VERSIONS.defaultVersion().messageVersio... |
@Override
public String convert(ILoggingEvent event) {
int nanos = event.getNanoseconds();
int millis_and_micros = nanos / 1000;
int micros = millis_and_micros % 1000;
if (micros >= 100)
return Integer.toString(micros);
else if (micros >= 10)
return "... | @Test
public void smoke() {
LoggingEvent le = new LoggingEvent();
Instant instant = Instant.parse("2011-12-03T10:15:30Z");
instant = instant.plusNanos(123_456_789);
le.setInstant(instant);
String result = mc.convert(le);
assertEquals("456", result);
} |
@Restricted(NoExternalUse.class)
public boolean supportsQuickRecursiveListing() {
return false;
} | @Test
public void testSupportsQuickRecursiveListing_AbstractBase() {
VirtualFile root = new VirtualFileMinimalImplementation();
assertFalse(root.supportsQuickRecursiveListing());
} |
public static Schema getPinotSchemaFromAvroSchemaWithComplexTypeHandling(org.apache.avro.Schema avroSchema,
@Nullable Map<String, FieldSpec.FieldType> fieldTypeMap, @Nullable TimeUnit timeUnit, List<String> fieldsToUnnest,
String delimiter, ComplexTypeConfig.CollectionNotUnnestedToJson collectionNotUnnested... | @Test
public void testGetPinotSchemaFromAvroSchemaWithComplexType()
throws IOException {
// do not unnest collect
org.apache.avro.Schema avroSchema =
new org.apache.avro.Schema.Parser().parse(ClassLoader.getSystemResourceAsStream(AVRO_NESTED_SCHEMA));
Map<String, FieldSpec.FieldType> fieldSp... |
public static URI parse(String featureIdentifier) {
requireNonNull(featureIdentifier, "featureIdentifier may not be null");
if (featureIdentifier.isEmpty()) {
throw new IllegalArgumentException("featureIdentifier may not be empty");
}
// Legacy from the Cucumber Eclipse plug... | @Test
@EnabledOnOs(WINDOWS)
void can_parse_windows_file_path_with_standard_file_separator() {
URI uri = FeaturePath.parse("C:/path/to/file.feature");
assertAll(
() -> assertThat(uri.getScheme(), is("file")),
() -> assertThat(uri.getSchemeSpecificPart(), is("/C:/path/to/f... |
public boolean matchExcludeTable(@NotNull String tableName) {
return matchTable(tableName, this.getExclude());
} | @Test
void matchExcludeTableTest() {
StrategyConfig.Builder strategyConfigBuilder = GeneratorBuilder.strategyConfigBuilder();
strategyConfigBuilder.addExclude("system", "user_1", "test[a|b]");
StrategyConfig strategyConfig = strategyConfigBuilder.build();
Assertions.assertTrue(strate... |
@Override
public void updateDiyPage(DiyPageUpdateReqVO updateReqVO) {
// 校验存在
validateDiyPageExists(updateReqVO.getId());
// 校验名称唯一
validateNameUnique(updateReqVO.getId(), updateReqVO.getTemplateId(), updateReqVO.getName());
// 更新
DiyPageDO updateObj = DiyPageConvert.... | @Test
public void testUpdateDiyPage_success() {
// mock 数据
DiyPageDO dbDiyPage = randomPojo(DiyPageDO.class);
diyPageMapper.insert(dbDiyPage);// @Sql: 先插入出一条存在的数据
// 准备参数
DiyPageUpdateReqVO reqVO = randomPojo(DiyPageUpdateReqVO.class, o -> {
o.setId(dbDiyPage.getI... |
@Override
public int hashCode() {
return Objects.hash(targetImage, imageDigest, imageId, tags, imagePushed);
} | @Test
public void testEquality_differentTags() {
JibContainer container1 = new JibContainer(targetImage1, digest1, digest1, tags1, true);
JibContainer container2 = new JibContainer(targetImage1, digest1, digest1, tags2, true);
Assert.assertNotEquals(container1, container2);
Assert.assertNotEquals(con... |
ImmutableMap<PCollection<?>, FieldAccessDescriptor> getPCollectionFieldAccess() {
return ImmutableMap.copyOf(pCollectionFieldAccess);
} | @Test
public void testFieldAccessUnknownMainInput() {
Pipeline p = Pipeline.create();
FieldAccessVisitor fieldAccessVisitor = new FieldAccessVisitor();
Schema schema =
Schema.of(Field.of("field1", FieldType.STRING), Field.of("field2", FieldType.STRING));
PCollection<Row> source =
p.app... |
@Override
public SerializationServiceBuilder setVersion(byte version) {
byte maxVersion = BuildInfoProvider.getBuildInfo().getSerializationVersion();
if (version > maxVersion) {
throw new IllegalArgumentException(
"Configured serialization version is higher than the m... | @Test(expected = IllegalArgumentException.class)
public void test_exceptionThrown_whenVersionGreaterThanMax() {
getSerializationServiceBuilder().setVersion(Byte.MAX_VALUE);
} |
@Override
public AbstractWALEvent decode(final ByteBuffer data, final BaseLogSequenceNumber logSequenceNumber) {
AbstractWALEvent result;
byte[] bytes = new byte[data.remaining()];
data.get(bytes);
String dataText = new String(bytes, StandardCharsets.UTF_8);
if (decodeWithTX)... | @Test
void assertDecodeWitTinyint() {
MppTableData tableData = new MppTableData();
tableData.setTableName("public.test");
tableData.setOpType("INSERT");
tableData.setColumnsName(new String[]{"data"});
tableData.setColumnsType(new String[]{"tinyint"});
tableData.setCol... |
@JsonCreator
public static WindowInfo of(
@JsonProperty(value = "type", required = true) final WindowType type,
@JsonProperty(value = "size") final Optional<Duration> size,
@JsonProperty(value = "emitStrategy") final Optional<OutputRefinement> emitStrategy) {
return new WindowInfo(type, size, em... | @Test(expected = IllegalArgumentException.class)
public void shouldThrowIfSizeNegative() {
WindowInfo.of(TUMBLING, Optional.of(Duration.ofSeconds(-1)), Optional.empty());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.