focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override @Transactional(rollbackFor = Exception.class) // 添加事务,异常则回滚所有导入 public UserImportRespVO importUserList(List<UserImportExcelVO> importUsers, boolean isUpdateSupport) { if (CollUtil.isEmpty(importUsers)) { throw exception(USER_IMPORT_LIST_IS_EMPTY); } UserImportRespVO...
@Test public void testImportUserList_02() { // 准备参数 UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> { o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围 o.setSex(randomEle(SexEnum.values()).getSex()); // 保证 sex 的范围 ...
static String getETag(String output) { return "W/" + hash(output.getBytes(UTF_8)); }
@Test public void getETag_should_return_same_value_for_same_input() { String input = randomAlphanumeric(200); assertThat(ETagUtils.getETag(input)).isEqualTo(ETagUtils.getETag(input)); }
@SuppressWarnings("unused") // Part of required API. public void execute( final ConfiguredStatement<InsertValues> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final InsertValues insertValues = s...
@Test public void shouldHandleRowTimeWithoutKey() { // Given: final ConfiguredStatement<InsertValues> statement = givenInsertValues( ImmutableList.of(SystemColumns.ROWTIME_NAME, COL0, COL1), ImmutableList.of( new LongLiteral(1234L), new StringLiteral("str"), ...
@Udf public List<String> keys(@UdfParameter final String jsonObj) { if (jsonObj == null) { return null; } final JsonNode node = UdfJsonMapper.parseJson(jsonObj); if (node.isMissingNode() || !node.isObject()) { return null; } final List<String> ret = new ArrayList<>(); node.fi...
@Test public void shouldReturnNullForNumber() { assertNull(udf.keys("123")); }
public String validate(final String xml) { final Source source = new SAXSource(reader, new InputSource(IOUtils.toInputStream(xml, Charset.defaultCharset()))); return validate(source); }
@Test public void testInValidXML() throws Exception { String payload = IOUtils.toString(ClassLoader.getSystemResourceAsStream("xml/article-2.xml"), Charset.defaultCharset()); logger.info("Validating payload: {}", payload); // validate String result = getProcessor("sc...
@SuppressWarnings("checkstyle:MissingSwitchDefault") @Override protected void doCommit(TableMetadata base, TableMetadata metadata) { int version = currentVersion() + 1; CommitStatus commitStatus = CommitStatus.FAILURE; /* This method adds no fs scheme, and it persists in HTS that way. */ final Stri...
@Test void testDoCommitAppendStageOnlySnapshotsExistingVersion() throws IOException { List<Snapshot> testSnapshots = IcebergTestUtil.getSnapshots(); List<Snapshot> testWapSnapshots = IcebergTestUtil.getWapSnapshots().subList(0, 2); // add 1 snapshot to the base metadata TableMetadata base = Ta...
static <T> T copy(T object, DataComplexTable alreadyCopied) throws CloneNotSupportedException { if (object == null) { return null; } else if (isComplex(object)) { DataComplex src = (DataComplex) object; @SuppressWarnings("unchecked") T found = (T) alreadyCopied.get(src); ...
@Test public void testCopy() throws CloneNotSupportedException { boolean copyOnWrite = ! CheckedMap.class.isAssignableFrom(DataMap.class); /* DataMap with only immutable types */ DataMap map1 = new DataMap(referenceMap1); DataMap map2 = map1.copy(); DataMap map3 = map2.copy(); assertTrue(!...
@Override public int run(String[] args) throws Exception { YarnConfiguration yarnConf = getConf() == null ? new YarnConfiguration() : new YarnConfiguration( getConf()); boolean isHAEnabled = yarnConf.getBoolean(YarnConfiguration.RM_HA_ENABLED, YarnConfiguration.DEFAULT_...
@Test public void testRefreshNodesGracefulInvalidArgs() throws Exception { // invalid graceful timeout parameter String[] invalidArgs = {"-refreshNodes", "-ginvalid", "invalid", "-client"}; assertEquals(-1, rmAdminCLI.run(invalidArgs)); // invalid timeout String[] invalidTimeoutArgs = {"-refreshN...
public static RestServerConfig forPublic(Integer rebalanceTimeoutMs, Map<?, ?> props) { return new PublicConfig(rebalanceTimeoutMs, props); }
@Test public void testInvalidSslClientAuthConfig() { Map<String, String> props = new HashMap<>(); props.put(BrokerSecurityConfigs.SSL_CLIENT_AUTH_CONFIG, "abc"); ConfigException ce = assertThrows(ConfigException.class, () -> RestServerConfig.forPublic(null, props)); assertTrue(ce.ge...
@Override public void setAttemptCount(JobVertexID jobVertexId, int subtaskIndex, int attemptNumber) { Preconditions.checkArgument(subtaskIndex >= 0); Preconditions.checkArgument(attemptNumber >= 0); final List<Integer> attemptCounts = vertexSubtaskToAttemptCounts.computeIfAb...
@Test void testSetAttemptCountRejectsNegativeAttemptCount() { final DefaultVertexAttemptNumberStore vertexAttemptNumberStore = new DefaultVertexAttemptNumberStore(); assertThatThrownBy(() -> vertexAttemptNumberStore.setAttemptCount(new JobVertexID(), 0, -1)) .isInsta...
@Override public Object run() { if (field != null) { field.setAccessible(true); } return field; }
@Test public void run() throws NoSuchFieldException { final Field testField = TestField.class.getDeclaredField("testField"); AccessController.doPrivileged(new FieldAccessAction(testField)); final Optional<Object> override = ReflectUtils.getFieldValue(testField, "override"); Assert.as...
@Override public RecoverableFsDataOutputStream open(Path path) throws IOException { LOGGER.trace("Opening output stream for path {}", path); Preconditions.checkNotNull(path); GSBlobIdentifier finalBlobIdentifier = BlobUtils.parseUri(path.toUri()); return new GSRecoverableFsDataOutpu...
@Test(expected = IllegalArgumentException.class) public void testOpenWithMissingObjectName() throws IOException { Path path = new Path("gs://foo"); writer.open(path); }
public static String toUriAuthority(NetworkEndpoint networkEndpoint) { return toHostAndPort(networkEndpoint).toString(); }
@Test public void toUriString_withIpV4AndPortEndpoint_returnsIpAddressAndPort() { NetworkEndpoint ipV4AndPortEndpoint = NetworkEndpoint.newBuilder() .setType(NetworkEndpoint.Type.IP_PORT) .setPort(Port.newBuilder().setPortNumber(8888)) .setIpAddress( IpA...
@Override public void upgrade() { if (configService.get(MigrationCompleted.class) != null) { LOG.debug("Migration already completed."); return; } var previousMigration = Optional.ofNullable(configService.get(V20191219090834_AddSourcesPage.MigrationCompleted.class)); ...
@Test @MongoDBFixtures({"V20230601104500_AddSourcesPageV2/previousMigration.json", "V20230601104500_AddSourcesPageV2/previousInstallationWithLocalModifications.json"}) void previousInstallationWithLocalModificationsIsKept() { previousMigrationHasRun(); thisMigrationHasNotRun(); when(noti...
@Override public boolean equals(Object o) { return o instanceof AddOn && TextUtils.equals(((AddOn) o).getId(), getId()) && ((AddOn) o).getApiVersion() == getApiVersion(); }
@Test public void testEquals() { TestableAddOn addOn1 = new TestableAddOn("id1", "name", 8); TestableAddOn addOn2 = new TestableAddOn("id2", "name", 8); TestableAddOn addOn11 = new TestableAddOn("id1", "name111", 8); TestableAddOn addOn1DifferentApiVersion = new TestableAddOn("id1", "name", 7); A...
@Override public Optional<KsqlConstants.PersistentQueryType> getPersistentQueryType() { if (!queryPlan.isPresent()) { return Optional.empty(); } // CREATE_AS and CREATE_SOURCE commands contain a DDL command and a Query plan. if (ddlCommand.isPresent()) { if (ddlCommand.get() instanceof Cr...
@Test public void shouldReturnCreateAsPersistentQueryTypeOnCreateTable() { // Given: final CreateTableCommand ddlCommand = Mockito.mock(CreateTableCommand.class); when(ddlCommand.getIsSource()).thenReturn(false); final KsqlPlanV1 plan = new KsqlPlanV1( "stmt", Optional.of(ddlCommand), ...
public Span nextSpan(Message message) { TraceContextOrSamplingFlags extracted = extractAndClearTraceIdProperties(processorExtractor, message, message); Span result = tracer.nextSpan(extracted); // Processor spans use the normal sampler. // When an upstream context was not present, lookup keys are unl...
@Test void nextSpan_uses_current_context() { Span child; try (Scope scope = tracing.currentTraceContext().newScope(parent)) { child = jmsTracing.nextSpan(message); } assertChildOf(child.context(), parent); }
static Set<String> getConfiguredSuperUsers(Map<String, ?> configs) { Object configValue = configs.get(SUPER_USERS_CONFIG); if (configValue == null) return Collections.emptySet(); String[] values = configValue.toString().split(";"); Set<String> result = new HashSet<>(); for (Strin...
@Test public void testGetConfiguredSuperUsers() { assertEquals(Collections.emptySet(), getConfiguredSuperUsers(Collections.emptyMap())); assertEquals(Collections.emptySet(), getConfiguredSuperUsers(Collections.singletonMap(SUPER_USERS_CONFIG, " "))); assertEquals(new ...
public void deleteByGroupUuid(DbSession dbSession, String groupUuid) { mapper(dbSession).deleteByGroupUuid(groupUuid); }
@Test void deleteFromGroupUuid_shouldNotFail_whenNoGroup() { assertThatCode(() -> scimGroupDao.deleteByGroupUuid(db.getSession(), randomAlphanumeric(6))).doesNotThrowAnyException(); }
@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_log_with_suppressed_throwable() { Exception exception = new Exception("BOOM"); exception.addSuppressed(new IllegalStateException("foo")); LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level.WARN, "the message", excepti...
@Override public void onMsg(TbContext ctx, TbMsg msg) { JsonObject json = JsonParser.parseString(msg.getData()).getAsJsonObject(); String tmp; if (msg.getOriginator().getEntityType() != EntityType.DEVICE) { ctx.tellFailure(msg, new RuntimeException("Message originator is not a de...
@Test public void givenRpcResponseWithoutError_whenOnMsg_thenSendsRpcRequest() { TbMsg outMsg = TbMsg.newMsg(TbMsgType.RPC_CALL_FROM_SERVER_TO_DEVICE, DEVICE_ID, TbMsgMetaData.EMPTY, TbMsg.EMPTY_JSON_OBJECT); given(ctxMock.getRpcService()).willReturn(rpcServiceMock); given(ctxMock.getTenant...
public static String getSelectQuery(@Nullable String table, @Nullable String query) { if (table != null && query != null) { throw new IllegalArgumentException("withTable() can not be used together with withQuery()"); } else if (table != null) { return "SELECT * FROM " + SingleStoreUtil.escapeIdentif...
@Test public void testGetSelectQueryNonNullQuery() { assertEquals( "SELECT * FROM table", SingleStoreUtil.getSelectQuery(null, "SELECT * FROM table")); }
@Override public Set<UnloadDecision> findBundlesForUnloading(LoadManagerContext context, Map<String, Long> recentlyUnloadedBundles, Map<String, Long> recentlyUnloadedBrokers) { final var conf = context.broker...
@Test public void testUnderloadOutlier() { UnloadCounter counter = new UnloadCounter(); TransferShedder transferShedder = new TransferShedder(counter); var ctx = setupContextLoadSkewedUnderload(100); var res = transferShedder.findBundlesForUnloading(ctx, Map.of(), Map.of()); ...
@Override public String getDocumentationLink(@Nullable String suffix) { return documentationBaseUrl + Optional.ofNullable(suffix).orElse(""); }
@Test public void getDocumentationLink_suffixProvided_withPropertyOverride() { String propertyValue = "https://new-url.sonarqube.org/"; when(configuration.get(DOCUMENTATION_BASE_URL)).thenReturn(Optional.of(propertyValue)); documentationLinkGenerator = new DefaultDocumentationLinkGenerator(sonarQubeVersio...
public Collection<RepositoryTuple> swapToRepositoryTuples(final YamlRuleConfiguration yamlRuleConfig) { RepositoryTupleEntity tupleEntity = yamlRuleConfig.getClass().getAnnotation(RepositoryTupleEntity.class); if (null == tupleEntity) { return Collections.emptyList(); } if (t...
@Test void assertSwapToRepositoryTuplesWithLeafYamlRuleConfiguration() { Collection<RepositoryTuple> actual = new RepositoryTupleSwapperEngine().swapToRepositoryTuples(new LeafYamlRuleConfiguration("foo")); assertThat(actual.size(), is(1)); RepositoryTuple actualTuple = actual.iterator().nex...
public void writeJndi(List<JndiBinding> jndiBindings, String path) throws IOException { try { document.open(); if (path.isEmpty()) { addParagraph(getString("Arbre_JNDI"), "jndi.png"); } else { addParagraph(getFormattedString("Arbre_JNDI_pour_contexte", path), "jndi.png"); } new PdfJndiReport(jn...
@Test public void testWriteJndi() throws NamingException, IOException { final String contextPath = "comp/env/"; final Context context = createNiceMock(Context.class); final NamingEnumeration<Binding> enumeration = createNiceMock(NamingEnumeration.class); expect(context.listBindings("java:" + contextPath)).andR...
@VisibleForTesting void handleResponse(DiscoveryResponseData response) { ResourceType resourceType = response.getResourceType(); switch (resourceType) { case NODE: handleD2NodeResponse(response); break; case D2_URI_MAP: handleD2URIMapResponse(response); break;...
@Test public void testHandleD2URIMapUpdateWithEmptyResponse() { XdsClientImplFixture fixture = new XdsClientImplFixture(); // Sanity check that the code handles empty responses fixture._xdsClientImpl.handleResponse(DISCOVERY_RESPONSE_WITH_EMPTY_URI_MAP_RESPONSE); fixture.verifyAckSent(1); }
@Override public String toString() { return "CacheConfig{" + "name='" + name + '\'' + ", managerPrefix='" + managerPrefix + '\'' + ", inMemoryFormat=" + inMemoryFormat + ", backupCount=" + backupCount + ", hotRestart=" + hotRest...
@Test public void cacheManagerByLocationFileTest() throws URISyntaxException { URI uri = new URI("MY-SCOPE"); String urlStr = configUrl1.toString(); assertEquals("file", urlStr.substring(0, 4)); Properties properties = new Properties(); properties.setProperty(HazelcastCachin...
int snapshottableSize(long epoch) { if (epoch == LATEST_EPOCH) { return baseSize(); } else { Iterator<Snapshot> iterator = snapshotRegistry.iterator(epoch); while (iterator.hasNext()) { Snapshot snapshot = iterator.next(); HashTier<T> t...
@Test public void testEmptyTable() { SnapshotRegistry registry = new SnapshotRegistry(new LogContext()); SnapshottableHashTable<TestElement> table = new SnapshottableHashTable<>(registry, 1); assertEquals(0, table.snapshottableSize(Long.MAX_VALUE)); }
@SuppressWarnings("unchecked") @Override public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request) throws YarnException, IOException { NodeStatus remoteNodeStatus = request.getNodeStatus(); /** * Here is the node heartbeat sequence... * 1. Check if it's a valid (i.e. not excl...
@Test public void testGracefulDecommissionWithApp() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, hostFile .getAbsolutePath()); writeToHostsFile(""); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode(...
@Override public void putTaskConfigs(final String connName, final List<Map<String, String>> configs, final Callback<Void> callback, InternalRequestSignature requestSignature) { log.trace("Submitting put task configuration request {}", connName); if (requestNotSignedProperly(requestSignature, callbac...
@Test public void putTaskConfigsWorkerStillStarting() { when(member.currentProtocolVersion()).thenReturn(CONNECT_PROTOCOL_V2); InternalRequestSignature signature = mock(InternalRequestSignature.class); when(signature.keyAlgorithm()).thenReturn("HmacSHA256"); Callback<Void> taskConf...
public static List<IntPair> intersectSortedRangeSets(List<List<IntPair>> sortedRangeSetList) { if (sortedRangeSetList == null || sortedRangeSetList.isEmpty()) { return Collections.emptyList(); } if (sortedRangeSetList.size() == 1) { return sortedRangeSetList.get(0); } // if any list is e...
@Test public void testComplex() { String rangeSet1 = "[[9148,10636], [18560,21885], [29475,32972], [34313,37642], [38008,47157], [50962,53911], " + "[59240,68238], [72458,83087], [92235,97593], [100690,103101], [111708,120102], [123212,124718], " + "[127544,134012], [134701,141314], [144966,146889...
public static void requireNotEmpty(final String str, final String name) { requireNotNull(str, name); if (str.isEmpty()) { throw new IllegalArgumentException(name + " is an empty string"); } }
@Test public void testNotEmptyWithNotEmptyString() { // This should not throw ArgumentUtil.requireNotEmpty("not empty string", "foo"); }
@Override protected void doStart() throws Exception { super.doStart(); LOG.debug("Creating connection to Azure ServiceBus"); client = getEndpoint().getServiceBusClientFactory().createServiceBusProcessorClient(getConfiguration(), this::processMessage, this::processError); ...
@Test void consumerSubmitsExchangeToProcessor() throws Exception { try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint, processor)) { consumer.doStart(); verify(client).start(); verify(clientFactory).createServiceBusProcessorClient(any(), any(), any()); ...
@PutMapping("/id/{id}") public ShenyuAdminResult updateTagRelation(@PathVariable("id") @Valid final String id, @Valid @RequestBody final TagRelationDTO tagRelationDTO) { tagRelationDTO.setId(id); Integer updateCount = tagRelationService.update(tagRelationDTO); ...
@Test public void testUpdateTagRelation() throws Exception { TagRelationDTO tagRelationDTO = buildTagRelationDTO(); given(tagRelationService.update(any())).willReturn(1); this.mockMvc.perform(MockMvcRequestBuilders.put("/tag-relation/id/123") .contentType(MediaType.AP...
public static DynamicVoters parse(String input) { input = input.trim(); List<DynamicVoter> voters = new ArrayList<>(); for (String voterString : input.split(",")) { if (!voterString.isEmpty()) { voters.add(DynamicVoter.parse(voterString)); } } ...
@Test public void testParsingInvalidStringWithDuplicateNodeIds() { assertEquals("Node id 1 was specified more than once.", assertThrows(IllegalArgumentException.class, () -> DynamicVoters.parse( "0@localhost:8020:K90IZ-0DRNazJ49kCZ1EMQ," + ...
SqlResult execute(CreateMappingPlan plan, SqlSecurityContext ssc) { catalog.createMapping(plan.mapping(), plan.replace(), plan.ifNotExists(), ssc); return UpdateSqlResultImpl.createUpdateCountResult(0); }
@Test @Parameters({ "true, false", "false, true" }) public void test_createMappingExecution(boolean replace, boolean ifNotExists) { // given Mapping mapping = mapping(); CreateMappingPlan plan = new CreateMappingPlan(planKey(), mapping, replace, ifNotExists, p...
@Override public int rename(String oldPath, String newPath, int flags) { return AlluxioFuseUtils.call(LOG, () -> renameInternal(oldPath, newPath, flags), FuseConstants.FUSE_RENAME, "oldPath=%s,newPath=%s,", oldPath, newPath); }
@Test public void renameNewExist() throws Exception { AlluxioURI oldPath = BASE_EXPECTED_URI.join("/old"); AlluxioURI newPath = BASE_EXPECTED_URI.join("/new"); doThrow(new FileAlreadyExistsException("File /new already exists")) .when(mFileSystem).rename(oldPath, newPath); when(mFileSystem.getS...
public static boolean isDataSourcesNode(final String path) { return Pattern.compile(getMetaDataNode() + DATABASE_DATA_SOURCES_NODE + "?", Pattern.CASE_INSENSITIVE).matcher(path).find(); }
@Test void assertIsDataSourcesNode() { assertTrue(DataSourceMetaDataNode.isDataSourcesNode("/metadata/logic_db/data_sources/foo_ds")); }
public static void print(Context context) { print(context, 0); }
@Test public void testWithException() { Status s0 = new ErrorStatus("test0", this); Status s1 = new InfoStatus("test1", this, new Exception("testEx")); Status s11 = new InfoStatus("test11", this); Status s12 = new InfoStatus("test12", this); s1.add(s11); s1.add(s12); Status s2 = new I...
@Override public void unSubscribeAllTransactionTopic(ProxyContext ctx, String group) { groupClusterData.remove(group); }
@Test public void testUnSubscribeAllTransactionTopic() { this.clusterTransactionService.addTransactionSubscription(ctx, GROUP, TOPIC); this.clusterTransactionService.unSubscribeAllTransactionTopic(ctx, GROUP); assertEquals(0, this.clusterTransactionService.getGroupClusterData().size()); ...
@Override public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException { try { final PathContainerService service = new DefaultPathContainerService(); if(service.isContainer(file)) { for(RootFolder r : session.roots()) { ...
@Test public void testFind() throws Exception { final StoregateIdProvider nodeid = new StoregateIdProvider(session); final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir( new Path(String.format("/My files/%s", new AlphanumericRandomStringService().random()), ...
@Override public Optional<ShardingConditionValue> generate(final BetweenExpression predicate, final Column column, final List<Object> params, final TimestampServiceRule timestampServiceRule) { ConditionValue betweenConditionValue = new ConditionValue(predicate.getBetweenExpr(), params); ConditionVal...
@SuppressWarnings("unchecked") @Test void assertGenerateConditionValueWithParameter() { ColumnSegment left = new ColumnSegment(0, 0, new IdentifierValue("id")); ParameterMarkerExpressionSegment between = new ParameterMarkerExpressionSegment(0, 0, 0); ParameterMarkerExpressionSegment and ...
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; DBSessions dbSes...
@Test public void does_nothing_when_not_initialized() throws Exception { underTest.doFilter(request, response, chain); verify(chain).doFilter(request, response); verifyNoInteractions(userSessionInitializer); }
public static VideosContainerResource mediaToVideo(MediaContainerResource mediaContainer) { return new VideosContainerResource( mediaContainer .getAlbums() .stream() .map(MediaAlbum::mediaToVideoAlbum) .collect(Collectors.toList()), mediaContainer.getV...
@Test public void verifyMediaToVideoContainer() { List<MediaAlbum> mediaAlbums = ImmutableList.of(new MediaAlbum("id1", "albumb1", "This:a fake album!")); List<VideoAlbum> videoAlbums = ImmutableList.of(new VideoAlbum("id1", "albumb1", "This:a fake album!")); List<VideoModel> videos = Immu...
public static void removeAll() { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet(); if (threadLocalMap == null) { return; } try { Object v = threadLocalMap.indexedVariable(VARIABLES_TO_REMOVE_INDEX); if (v != null && v != Inter...
@Test @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testRemoveAll() throws Exception { final AtomicBoolean removed = new AtomicBoolean(); final FastThreadLocal<Boolean> var = new FastThreadLocal<Boolean>() { @Override protected void onRemoval(Boolean v...
@Override public boolean createTopic( final String topic, final int numPartitions, final short replicationFactor, final Map<String, ?> configs, final CreateTopicsOptions createOptions ) { final Optional<Long> retentionMs = KafkaTopicClient.getRetentionMs(configs); if (isTopicE...
@Test public void shouldNotCreateTopicIfItAlreadyExistsWithMatchingDetails() { // Given: givenTopicExists("someTopic", 3, 2); givenTopicConfigs( "someTopic", overriddenConfigEntry(TopicConfig.RETENTION_MS_CONFIG, "8640000000") ); // When: kafkaTopicClient.createTopic("someTopi...
Proxy getProxy() { if (proxyHost == null) { return Proxy.NO_PROXY; } else { return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } }
@Test void testGetProxy() { DatadogHttpClient client = new DatadogHttpClient("anApiKey", "localhost", 123, DataCenter.US, false); assertThat(client.getProxy().address()).isInstanceOf(InetSocketAddress.class); InetSocketAddress proxyAddress = (InetSocketAddress) client.getPr...
public static Predicate parse(String expression) { final Stack<Predicate> predicateStack = new Stack<>(); final Stack<Character> operatorStack = new Stack<>(); final String trimmedExpression = TRIMMER_PATTERN.matcher(expression).replaceAll(""); final StringTokenizer tokenizer = new StringTokenizer(tr...
@Test(expectedExceptions = RuntimeException.class) public void testNotPredicate() { PredicateExpressionParser.parse("com.linkedin.restli.tools.data.PredicateExpressionParser"); }
public static <T> ListenableFuture<T> toListenableFuture(Task<T> task) { // Setup cancellation propagation from ListenableFuture -> Task. SettableFuture<T> listenableFuture = new SettableFuture<T>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return super.cancel(mayInt...
@Test public void testToListenableFuture() throws Exception { Task<String> task; final SettablePromise<String> p = Promises.settable(); task = Task.async("test", () -> p); ListenableFuture<String> future = ListenableFutureUtil.toListenableFuture(task); // Test cancel propagation from Listenable...
public static boolean isValidIdentifier(String str) { return notEmpty(str) && !isReserved(str) && VALID_JAVA_IDENTIFIER.matcher(str).matches(); }
@Test public void notValidIdentifiers() { assertThat(isValidIdentifier("1cls")).isFalse(); assertThat(isValidIdentifier("-cls")).isFalse(); assertThat(isValidIdentifier("A-cls")).isFalse(); }
@Override public void addBytesRead(long n) { if (currentCounter != null) { currentCounter.addValue(n); } }
@Test public void testAddBytesReadUpdatesCounter() { DataflowExecutionContext mockedExecutionContext = mock(DataflowExecutionContext.class); DataflowOperationContext mockedOperationContext = mock(DataflowOperationContext.class); final int siIndexId = 3; ExecutionStateTracker mockedExecutionStateTrack...
@VisibleForTesting public void validateDictTypeExists(String type) { DictTypeDO dictType = dictTypeService.getDictType(type); if (dictType == null) { throw exception(DICT_TYPE_NOT_EXISTS); } if (!CommonStatusEnum.ENABLE.getStatus().equals(dictType.getStatus())) { ...
@Test public void testValidateDictTypeExists_notExists() { assertServiceException(() -> dictDataService.validateDictTypeExists(randomString()), DICT_TYPE_NOT_EXISTS); }
@Override public ByteBuf writeShortLE(int value) { ensureWritable0(2); _setShortLE(writerIndex, value); writerIndex += 2; return this; }
@Test public void testWriteShortLEAfterRelease() { assertThrows(IllegalReferenceCountException.class, new Executable() { @Override public void execute() { releasedBuffer().writeShortLE(1); } }); }
public static List<String> split(String path) { // String[] pathelements = path.split("/"); List<String> dirs = new ArrayList<String>(pathelements.length); for (String pathelement : pathelements) { if (!pathelement.isEmpty()) { dirs.add(pathelement); } } return dirs; }
@Test public void testSplitting() throws Throwable { assertEquals(1, split("/a").size()); assertEquals(0, split("/").size()); assertEquals(3, split("/a/b/c").size()); assertEquals(3, split("/a/b/c/").size()); assertEquals(3, split("a/b/c").size()); assertEquals(3, split("/a/b//c").size()); ...
public Map<String, Map<String, String>> configAsMap() { Map<String, Map<String, String>> configMap = new HashMap<>(); for (ConfigurationProperty property : configuration) { Map<String, String> mapValue = new HashMap<>(); mapValue.put(VALUE_KEY, property.getValue()); i...
@Test public void testConfigAsMap() throws Exception { PluginConfiguration pluginConfiguration = new PluginConfiguration("test-plugin-id", "13.4"); GoCipher cipher = new GoCipher(); List<String> keys = List.of("Avengers 1", "Avengers 2", "Avengers 3", "Avengers 4"); List<String> val...
@Override public void decorateRouteContext(final RouteContext routeContext, final QueryContext queryContext, final ShardingSphereDatabase database, final ReadwriteSplittingRule rule, final ConfigurationProperties props, final ConnectionContext connectionContext) { Collec...
@Test void assertDecorateRouteContextToPrimaryDataSourceWithLock() { RouteContext actual = mockRouteContext(); MySQLSelectStatement selectStatement = mock(MySQLSelectStatement.class); when(sqlStatementContext.getSqlStatement()).thenReturn(selectStatement); when(selectStatement.getLoc...
@Override public void run(EnhancedPluginContext context) throws Throwable { if (!this.reportProperties.isEnabled()) { return; } EnhancedRequestContext request = context.getRequest(); ServiceInstance serviceInstance = Optional.ofNullable(context.getTargetServiceInstance()).orElse(new DefaultServiceInstance(...
@Test public void testRun() throws Throwable { EnhancedPluginContext context = mock(EnhancedPluginContext.class); // test not report exceptionCircuitBreakerReporter.run(context); verify(context, times(0)).getRequest(); doReturn(true).when(reporterProperties).isEnabled(); EnhancedPluginContext pluginConte...
public synchronized void refreshPartitionByEvent(HivePartitionName hivePartitionName, HiveCommonStats commonStats, Partition partition) { Map<String, HiveColumnStats> columnStats = get(partitionStatsCache, ...
@Test public void testRefreshPartitionByEvent() { CachingHiveMetastore cachingHiveMetastore = new CachingHiveMetastore( metastore, executor, expireAfterWriteSec, refreshAfterWriteSec, 1000, false); HiveCommonStats stats = new HiveCommonStats(10, 100); HivePartitionName hiveP...
@Override public SchemaAndValue get(final ProcessingLogConfig config) { final Struct struct = new Struct(ProcessingLogMessageSchema.PROCESSING_LOG_SCHEMA) .put(ProcessingLogMessageSchema.TYPE, MessageType.DESERIALIZATION_ERROR.getTypeId()) .put(ProcessingLogMessageSchema.DESERIALIZATION_ERROR, des...
@Test public void shouldBuildErrorWithKeyComponent() { // Given: final DeserializationError deserError = new DeserializationError( error, Optional.of(record), "topic", true ); // When: final SchemaAndValue msg = deserError.get(config); // Then: final Struc...
public static String checkRequiredProperty(Properties properties, String key) { if (properties == null) { throw new IllegalArgumentException("Properties are required"); } String value = properties.getProperty(key); return checkHasText(value, "Property '" + key + "' is require...
@Test public void test_checkRequiredProperty_when_null() { Assertions.assertThatThrownBy(() -> checkRequiredProperty(null, "some-key")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Properties are required"); }
@Override public Result unwrap() { return result; }
@Test void unwrap() { assertThat(response.unwrap()).isSameAs(result); }
@JsonIgnore public LongParamDefinition getCompletedByTsParam() { if (completedByTs != null) { return ParamDefinition.buildParamDefinition(PARAM_NAME, completedByTs); } if (completedByHour != null) { String timeZone = tz == null ? "WORKFLOW_CRON_TIMEZONE" : String.format("'%s'", tz); retu...
@Test public void testGetCompletedByTsParamWithCompletedByHour() { Tct tct = new Tct(); tct.setCompletedByHour(1); tct.setTz("UTC"); LongParamDefinition expected = LongParamDefinition.builder() .name("completed_by_ts") .expression( "tz_dateint_formatter ...
public static <K, V> Write<K, V> write() { return new AutoValue_CdapIO_Write.Builder<K, V>().build(); }
@Test public void testWriteWithCdapBatchSinkPlugin() throws IOException { List<KV<String, String>> data = new ArrayList<>(); for (int i = 0; i < EmployeeInputFormat.NUM_OF_TEST_EMPLOYEE_RECORDS; i++) { data.add(KV.of(String.valueOf(i), EmployeeInputFormat.EMPLOYEE_NAME_PREFIX + i)); } PCollectio...
public Map<Endpoint, CompletableFuture<Void>> futures() { return futures; }
@Test public void testImmediateCompletion() { EndpointReadyFutures readyFutures = new EndpointReadyFutures.Builder(). build(Optional.empty(), INFO); assertEquals(new HashSet<>(Arrays.asList(EXTERNAL, INTERNAL)), readyFutures.futures().keySet()); assertComplete...
private void setSpecifiedSimpleTypeProperty(Types type, String qualifiedName, Object propertyValue) { if (propertyValue == null) { // Search in properties to erase for (AbstractField child : getContainer().getAllProperties()) { if (child.getPropert...
@Test void testSetSpecifiedSimpleTypeProperty() throws Exception { String prop = "testprop"; String val = "value"; String val2 = "value2"; schem.setTextPropertyValueAsSimple(prop, val); assertEquals(val, schem.getUnqualifiedTextPropertyValue(prop)); schem.setTextP...
public void writeMBeans(List<MBeanNode> mbeans) throws IOException { try { document.open(); addParagraph(getString("MBeans"), "mbeans.png"); new PdfMBeansReport(mbeans, document).toPdf(); } catch (final DocumentException e) { throw createIOException(e); } document.close(); }
@Test public void testWriteMBeans() throws IOException, JMException { final ByteArrayOutputStream output = new ByteArrayOutputStream(); final PdfOtherReport pdfOtherReport = new PdfOtherReport(TEST_APP, output); final List<MBeanNode> allMBeanNodes = MBeans.getAllMBeanNodes(); pdfOtherReport.writeMBeans(allMBea...
public Set<Cookie> decode(String header) { Set<Cookie> cookies = new TreeSet<Cookie>(); decode(cookies, header); return cookies; }
@Test public void testDecodingOldRFC2965Cookies() { String source = "$Version=\"1\"; " + "Part_Number1=\"Riding_Rocket_0023\"; $Path=\"/acme/ammo\"; " + "Part_Number2=\"Rocket_Launcher_0001\"; $Path=\"/acme\""; Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(...
static Clustering clusteringFromJsonFields(String jsonStringClustering) { JsonElement jsonClustering = JsonParser.parseString(jsonStringClustering); checkArgument( jsonClustering.isJsonArray(), "Received an invalid Clustering json string: %s." + "Please provide a serialized json arr...
@Test public void testClusteringJsonConversion() { Clustering clustering = new Clustering().setFields(Arrays.asList("column1", "column2", "column3")); String jsonClusteringFields = "[\"column1\", \"column2\", \"column3\"]"; assertEquals(clustering, BigQueryHelpers.clusteringFromJsonFields(jsonClu...
public ProtocolBuilder threads(Integer threads) { this.threads = threads; return getThis(); }
@Test void threads() { ProtocolBuilder builder = new ProtocolBuilder(); builder.threads(20); Assertions.assertEquals(20, builder.build().getThreads()); }
@Override public void deleteTenantPackage(Long id) { // 校验存在 validateTenantPackageExists(id); // 校验正在使用 validateTenantUsed(id); // 删除 tenantPackageMapper.deleteById(id); }
@Test public void testDeleteTenantPackage_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> tenantPackageService.deleteTenantPackage(id), TENANT_PACKAGE_NOT_EXISTS); }
public static String join(final String... levels) { return join(Arrays.asList(levels)); }
@Test public void shouldJoinCorrectly() { assertThat(ProcessingLoggerUtil.join("foo", "bar"), equalTo("foo.bar")); }
public KsqlTarget target(final URI server) { return target(server, Collections.emptyMap()); }
@Test public void shouldHandleForbiddenOnGetRequests() { // Given: server.setErrorCode(403); // When: KsqlTarget target = ksqlClient.target(serverUri); RestResponse<ServerInfo> response = target.getServerInfo(); // Then: assertThat(server.getHttpMethod(), is(HttpMethod.GET)); assert...
@Override public List<RedisClientInfo> getClientList(RedisClusterNode node) { RedisClient entry = getEntry(node); RFuture<List<String>> f = executorService.readAsync(entry, StringCodec.INSTANCE, RedisCommands.CLIENT_LIST); List<String> list = syncFuture(f); return CONVERTER.convert(l...
@Test public void testGetClientList() { RedisClusterNode master = getFirstMaster(); List<RedisClientInfo> list = connection.getClientList(master); assertThat(list.size()).isGreaterThan(10); }
@Override public int statusCode() { int result = ServletRuntime.get().status(response); if (caught != null && result == 200) { // We may have a potentially bad status due to defaults // Servlet only seems to define one exception that has a built-in code. Logic in Jetty // defaults the status to 500 ...
@Test void statusCode() { when(response.getStatus()).thenReturn(200); HttpServerResponse wrapper = HttpServletResponseWrapper.create(request, response, null); assertThat(wrapper.statusCode()).isEqualTo(200); }
public static DualInputSemanticProperties createProjectionPropertiesDual( int[] fields, boolean[] isFromFirst, TypeInformation<?> inType1, TypeInformation<?> inType2) { DualInputSemanticProperties dsp = new DualInputSemanticProperties(); int[] sourceOffse...
@Test void testDualProjectionProperties() { int[] pMap = new int[] {4, 2, 0, 1, 3, 4}; boolean[] iMap = new boolean[] {true, true, false, true, false, false}; DualInputSemanticProperties sp = SemanticPropUtil.createProjectionPropertiesDual( pMap, iMap...
public static Config resolve(Config config) { var resolveSystemProperty = System.getenv("KORA_SYSTEM_PROPERTIES_RESOLVE_ENABLED"); if (resolveSystemProperty == null) { resolveSystemProperty = System.getProperty("kora.system.properties.resolve.enabled", "true"); } var ctx = ne...
@Test void testMultipleValues() { var config = fromMap(Map.of( "value", "value", "reference", "value: ${value}, nullableValue1: ${?value}, nullableValue2: ${?value2}, valueWithDefault: ${value:default}, valueWithDefault: ${value2:default} leftover" )).resolve(); asser...
@Override public boolean addReservation(ReservationAllocation reservation, boolean isRecovering) throws PlanningException { // Verify the allocation is memory based otherwise it is not supported InMemoryReservationAllocation inMemReservation = (InMemoryReservationAllocation) reservation; if ...
@Test public void testAddReservation() { Plan plan = new InMemoryPlan(queueMetrics, policy, agent, totalCapacity, 1L, resCalc, minAlloc, maxAlloc, planName, replanner, true, context); ReservationId reservationID = ReservationSystemTestUtil.getNewReservationId(); int[] alloc = { 10, 10, 10,...
@Override public GoViewProjectDO getProject(Long id) { return goViewProjectMapper.selectById(id); }
@Test public void testGetProject() { // mock 数据 GoViewProjectDO dbGoViewProject = randomPojo(GoViewProjectDO.class); goViewProjectMapper.insert(dbGoViewProject);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbGoViewProject.getId(); // 调用 GoViewProjectDO goViewProjec...
public static Map<String, String> parseToMap(String attributesModification) { if (Strings.isNullOrEmpty(attributesModification)) { return new HashMap<>(); } // format: +key1=value1,+key2=value2,-key3,+key4=value4 Map<String, String> attributes = new HashMap<>(); Stri...
@Test public void testParseBetweenStringAndMapWithoutDistortion() { List<String> testCases = Arrays.asList("-a", "+a=b,+c=d,+z=z,+e=e", "+a=b,-d", "+a=b", "-a,-b"); for (String testCase : testCases) { assertTrue(Maps.difference(AttributeParser.parseToMap(testCase), AttributeParser.parseT...
public void collectLog(LogEntry logEntry) { if (logEntry.getLevel() == null || minLogLevel == null) { LOGGER.warn("Log level or threshold level is null. Skipping."); return; } if (logEntry.getLevel().compareTo(minLogLevel) < 0) { LOGGER.debug("Log level below threshold. Skipping."); ...
@Test void whenThreeInfoLogsAreCollected_thenCentralLogStoreShouldStoreAllOfThem() { logAggregator.collectLog(createLogEntry(LogLevel.INFO, "Sample log message 1")); logAggregator.collectLog(createLogEntry(LogLevel.INFO, "Sample log message 2")); verifyNoInteractionsWithCentralLogStore(); logAggrega...
public static String dotToCamel(String param) { return formatCamel(param, DOT); }
@Test void dotToCamel() { assertThat(StringFormatUtils.dotToCamel(null)).isEqualTo(""); assertThat(StringFormatUtils.dotToCamel(" ")).isEqualTo(""); assertThat(StringFormatUtils.dotToCamel("abc.def.gh")).isEqualTo("abcDefGh"); }
public void decode(ByteBuf buffer) { boolean last; int statusCode; while (true) { switch(state) { case READ_COMMON_HEADER: if (buffer.readableBytes() < SPDY_HEADER_SIZE) { return; } ...
@Test public void testInvalidSpdySettingsFrameNumSettings() throws Exception { short type = 4; byte flags = 0; int numSettings = 2; int length = 8 * numSettings + 4; byte idFlags = 0; int id = RANDOM.nextInt() & 0x00FFFFFF; int value = RANDOM.nextInt(); ...
public static Expression invokeGenerated( CodegenContext ctx, SerializableSupplier<Expression> groupExpressionsGenerator, String methodPrefix) { List<Expression> cutPoint = ExpressionUtils.extractCapturedExpressions(groupExpressionsGenerator); return invokeGenerated( ctx, new H...
@Test public void testInvokeGenerated() throws Exception { CodegenContext ctx = new CodegenContext(); String clsName = "TestInvokeGenerated"; ctx.setClassName(clsName); ctx.setPackage("test"); Expression expression = ExpressionOptimizer.invokeGenerated( ctx, () -> new Return(ne...
public static void getSemanticPropsSingleFromString( SingleInputSemanticProperties result, String[] forwarded, String[] nonForwarded, String[] readSet, TypeInformation<?> inType, TypeInformation<?> outType) { getSemanticPropsSingleFromStrin...
@Test void testForwardedInvalidExpression() { String[] forwardedFields = {"f0"}; SingleInputSemanticProperties sp = new SingleInputSemanticProperties(); assertThatThrownBy( () -> { SemanticPropUtil.getSemanticPropsSingleFromString( ...
protected Pair<LIMEExplanation, List<Example<Regressor>>> explainWithSamples(Map<String, String> input) { Optional<Example<Label>> optExample = generator.generateExample(input,false); if (optExample.isPresent()) { Example<Label> example = optExample.get(); if ((textDomain.size() ...
@Test public void testBinarisedCategorical() throws URISyntaxException { Pair<RowProcessor<Label>,Dataset<Label>> pair = generateBinarisedDataset(); RowProcessor<Label> rp = pair.getA(); Dataset<Label> dataset = pair.getB(); XGBoostClassificationTrainer trainer = new XGBoostClassif...
public static Pipeline updateTransform( String urn, Pipeline originalPipeline, TransformReplacement compositeBuilder) { Components.Builder resultComponents = originalPipeline.getComponents().toBuilder(); for (Map.Entry<String, PTransform> pt : originalPipeline.getComponents().getTransformsMap().en...
@Test public void replacesMultiple() { RunnerApi.Pipeline p = Pipeline.newBuilder() .addAllRootTransformIds(ImmutableList.of("first", "second")) .setComponents( Components.newBuilder() .putTransforms( "first", ...
@Override @GuardedBy("getLock()") public PageInfo getPageInfo(PageId pageId) throws PageNotFoundException { if (!mPages.contains(INDEX_PAGE_ID, pageId)) { throw new PageNotFoundException(String.format("Page %s could not be found", pageId)); } PageInfo pageInfo = mPages.getFirstByField(INDEX_PAGE_I...
@Test public void getPageInfo() throws Exception { mMetaStore.addPage(mPage, mPageInfo); assertEquals(mPageInfo, mMetaStore.getPageInfo(mPage)); }
public String getSecurityCredentialsUrl() { if (securityCredentialsUrl == null && ramRoleName != null) { return RAM_SECURITY_CREDENTIALS_URL + ramRoleName; } return securityCredentialsUrl; }
@Test void testGetSecurityCredentialsUrl() { assertNull(StsConfig.getInstance().getSecurityCredentialsUrl()); String expect = "localhost"; StsConfig.getInstance().setSecurityCredentialsUrl(expect); assertEquals(expect, StsConfig.getInstance().getSecurityCredentialsUrl()); }
@Override public void handlerPlugin(final PluginData pluginData) { if (Objects.nonNull(pluginData) && Boolean.TRUE.equals(pluginData.getEnabled())) { TarsRegisterConfig tarsRegisterConfig = GsonUtils.getInstance().fromJson(pluginData.getConfig(), TarsRegisterConfig.class); TarsRegist...
@Test public void testHandlerPlugin() { final PluginData pluginData = new PluginData("id", "name", "{\"threadpool\":\"cached\",\"corethreads\":1,\"threads\":2,\"queues\":3}", "0", true, null); tarsPluginDataHandlerUnderTest.handlerPlugin(pluginData); assertTrue(pluginData.getName().endsWith(...
public static String getName(DistributedObject distributedObject) { /* * The motivation of this behaviour is that some distributed objects (`ICache`) can have prefixed name. * For example, for the point of view of cache, * it has pure name and full name which contains prefixes also. ...
@Test public void testGetName_withPrefixedDistributedObject() { PrefixedDistributedObject distributedObject = mock(PrefixedDistributedObject.class); when(distributedObject.getPrefixedName()).thenReturn("MockedPrefixedDistributedObject"); String name = DistributedObjectUtil.getName(distribut...
@Override public List<MenuDO> getMenuList() { return menuMapper.selectList(); }
@Test public void testGetMenuList_all() { // mock 数据 MenuDO menu100 = randomPojo(MenuDO.class); menuMapper.insert(menu100); MenuDO menu101 = randomPojo(MenuDO.class); menuMapper.insert(menu101); // 准备参数 // 调用 List<MenuDO> list = menuService.getMenuLis...
private void updateInputPartitions(final Map<TaskId, CompletableFuture<StateUpdater.RemovedTaskResult>> futures, final Map<TaskId, Set<TopicPartition>> newInputPartitions, final Map<TaskId, RuntimeException> failedTasks) { getNonFaile...
@Test public void shouldUpdateExistingStandbyTaskIfStandbyIsReassignedWithDifferentInputPartitionWithoutStateUpdater() { final StandbyTask standbyTask = standbyTask(taskId03, taskId03ChangelogPartitions) .inState(State.RUNNING) .withInputPartitions(taskId03Partitions).build(); ...
@Udf public <T> List<T> slice( @UdfParameter(description = "the input array") final List<T> in, @UdfParameter(description = "start index") final Integer from, @UdfParameter(description = "end index") final Integer to) { if (in == null) { return null; } try { // ...
@Test public void shouldOneElementSlice() { // Given: final List<String> list = Lists.newArrayList("a", "b", "c"); // When: final List<String> slice = new Slice().slice(list, 2, 2); // Then: assertThat(slice, is(Lists.newArrayList("b"))); }
String renderInstructionForDisplay(Instruction instr) { // special handling for Extension Instruction Wrappers... if (instr instanceof Instructions.ExtensionInstructionWrapper) { Instructions.ExtensionInstructionWrapper wrap = (Instructions.ExtensionInstructionWrapper) i...
@Test public void renderExtensionInstruction() { title("renderExtensionInstruction"); ExtensionTreatment extn = new Ofdpa3SetMplsType((short) 32); DeviceId devid = deviceId(DEV_OF_204); instr = Instructions.extension(extn, devid); string = instr.toString(); render =...
public abstract long observeWm(int queueIndex, long wmValue);
@Test public void when_i1HasWm_i2Idle_then_forwardedImmediately() { assertEquals(Long.MIN_VALUE, wc.observeWm(0, 100)); assertEquals(100, wc.observeWm(1, IDLE_MESSAGE.timestamp())); }
public static String readUtf8Str(String resource) { return getResourceObj(resource).readUtf8Str(); }
@Test public void fileResourceTest(){ final FileResource resource = new FileResource(FileUtil.file("test.xml")); assertEquals("test.xml", resource.getName()); assertTrue(StrUtil.isNotEmpty(resource.readUtf8Str())); }
public void free() { if (watcher != null) { watcher.stop(); } LOGGER.info("[{}] {} is freed", appName, this.getClass().getSimpleName()); }
@Test void testFree() throws NoSuchFieldException, IllegalAccessException { CredentialService credentialService1 = CredentialService.getInstance(); CredentialWatcher mockWatcher = mock(CredentialWatcher.class); Field watcherField = CredentialService.class.getDeclaredField("watcher"); ...
@Override public boolean isWriteable() throws FileSystemException { return resolvedFileObject.isWriteable(); }
@Test public void testDelegatesIsWritable() throws FileSystemException { when( resolvedFileObject.isWriteable() ).thenReturn( true ); assertTrue( fileObject.isWriteable() ); when( resolvedFileObject.isWriteable() ).thenReturn( false ); assertFalse( fileObject.isWriteable() ); verify( resolvedF...
public static void checkState(boolean b) { if (!b) { throw new IllegalStateException(); } }
@Test public void testPreconditionsMalformedState(){ //No %s: Preconditions.checkState(true, "This is malformed", "A", "B", "C"); try{ Preconditions.checkState(false, "This is malformed", "A", "B", "C"); } catch (IllegalStateException e){ assertEquals("This i...