Java Code Examples for org.mockito.ArgumentMatcher

The following examples show how to use org.mockito.ArgumentMatcher. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: vividus   Source File: DatabaseStepsTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void shouldCompareQueriesAndUseAllColumnValuesIfUserDoesntSpecifyKeys() throws InterruptedException,
    ExecutionException, TimeoutException, SQLException
{
    mockDataSource(QUERY, DB_KEY, mockResultSet(COL1, VAL1, COL2, null, COL3, VAL3));
    mockDataSource(QUERY, DB_KEY2, mockResultSet(COL1, VAL1, COL2, null, COL3, VAL3));
    when(softAssert.assertTrue(QUERY_RESULTS_ARE_EQUAL, true)).thenReturn(true);
    ArgumentMatcher<CharSequence> matcher = s ->
    {
        String toHash = s.toString();
        return toHash.contains(VAL1) && toHash.contains(VAL3) && !toHash.contains(VAL2);
    };
    when(hashFunction.hashString(argThat(matcher), eq(StandardCharsets.UTF_8))).thenReturn(HASH1);
    configureTimeout();
    mockRowsFilterAsNOOP();
    databaseSteps.compareData(QUERY, DB_KEY, QUERY, DB_KEY2, Set.of());
    verify(attachmentPublisher).publishAttachment(eq(QUERIES_STATISTICS_FTL),
            any(Map.class), eq(QUERIES_STATISTICS));
    verify(hashFunction, times(2)).hashString(argThat(matcher), eq(StandardCharsets.UTF_8));
}
 
Example 2
Source Project: sofa-jraft   Source File: ReadOnlyServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddRequest() throws Exception {
    final byte[] requestContext = TestUtils.getRandomBytes();
    this.readOnlyServiceImpl.addRequest(requestContext, new ReadIndexClosure() {

        @Override
        public void run(final Status status, final long index, final byte[] reqCtx) {

        }
    });
    this.readOnlyServiceImpl.flush();
    Mockito.verify(this.node).handleReadIndexRequest(Mockito.argThat(new ArgumentMatcher<ReadIndexRequest>() {

        @Override
        public boolean matches(final Object argument) {
            if (argument instanceof ReadIndexRequest) {
                final ReadIndexRequest req = (ReadIndexRequest) argument;
                return req.getGroupId().equals("test") && req.getServerId().equals("localhost:8081:0")
                       && req.getEntriesCount() == 1
                       && Arrays.equals(requestContext, req.getEntries(0).toByteArray());
            }
            return false;
        }

    }), Mockito.any());
}
 
Example 3
Source Project: flink   Source File: SessionWindowAssignerTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testMergeConsecutiveWindows() {
	MergingWindowAssigner.MergeCallback callback = mock(MergingWindowAssigner.MergeCallback.class);
	SessionWindowAssigner assigner = SessionWindowAssigner.withGap(Duration.ofMillis(5000));

	TreeSet<TimeWindow> sortedWindows = new TreeSet<>();
	sortedWindows.addAll(Arrays.asList(
			new TimeWindow(0, 1),
			new TimeWindow(2, 3),
			new TimeWindow(4, 5),
			new TimeWindow(7, 8)));
	assigner.mergeWindows(new TimeWindow(1, 2), sortedWindows, callback);

	verify(callback, times(1)).merge(
			eq(new TimeWindow(0, 3)),
			argThat((ArgumentMatcher<Collection<TimeWindow>>) timeWindows ->
					containsInAnyOrder(
							new TimeWindow(0, 1),
							new TimeWindow(1, 2),
							new TimeWindow(2, 3)).matches(timeWindows)));
}
 
Example 4
Source Project: flink   Source File: SessionWindowAssignerTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testMergeCoveringWindow() {
	MergingWindowAssigner.MergeCallback callback = mock(MergingWindowAssigner.MergeCallback.class);
	SessionWindowAssigner assigner = SessionWindowAssigner.withGap(Duration.ofMillis(5000));

	TreeSet<TimeWindow> sortedWindows = new TreeSet<>();
	sortedWindows.addAll(Arrays.asList(
			new TimeWindow(1, 4),
			new TimeWindow(5, 7),
			new TimeWindow(9, 10)));
	assigner.mergeWindows(new TimeWindow(3, 6), sortedWindows, callback);

	verify(callback, times(1)).merge(
			eq(new TimeWindow(1, 7)),
			argThat((ArgumentMatcher<Collection<TimeWindow>>) timeWindows ->
					containsInAnyOrder(
							new TimeWindow(1, 4),
							new TimeWindow(5, 7),
							new TimeWindow(3, 6)).matches(timeWindows)));
}
 
Example 5
Source Project: emodb   Source File: ClusterHintsPollerTest.java    License: Apache License 2.0 6 votes vote down vote up
private ArgumentMatcher<Statement> getHostStatementMatcher(final Host host, final String query)
        throws Exception {
    return new ArgumentMatcher<Statement>() {
        @Override
        public boolean matches(Object argument) {
            SelectedHostStatement statement = (SelectedHostStatement) argument;

            return ((SimpleStatement)statement.getStatement()).getQueryString().equals(query) &&
                    Objects.equals(statement.getHostCordinator().getAddress(), host.getAddress());
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(format("query:%s host:%s", query, host.getAddress().toString()));
        }
    };
}
 
Example 6
Source Project: teku   Source File: GetNewBlockTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void shouldPropagateChainDataUnavailableExceptionToGlobalExceptionHandlerWithGraffiti()
    throws Exception {
  final Map<String, List<String>> params =
      Map.of(
          RestApiConstants.SLOT,
          List.of("1"),
          RANDAO_REVEAL,
          List.of(signature.toHexString()),
          RestApiConstants.GRAFFITI,
          List.of(graffiti.toHexString()));
  when(context.queryParamMap()).thenReturn(params);
  when(provider.getUnsignedBeaconBlockAtSlot(ONE, signature, Optional.of(graffiti)))
      .thenReturn(SafeFuture.failedFuture(new ChainDataUnavailableException()));
  handler.handle(context);

  // Exception should just be propagated up via the future
  verify(context, never()).status(anyInt());
  verify(context)
      .result(
          argThat((ArgumentMatcher<SafeFuture<?>>) CompletableFuture::isCompletedExceptionally));
}
 
Example 7
Source Project: vespa   Source File: DocumentRetrieverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSendSingleMessage() throws DocumentRetrieverException {
    ClientParameters params = createParameters()
            .setDocumentIds(asIterator(DOC_ID_1))
            .setPriority(DocumentProtocol.Priority.HIGH_1)
            .setNoRetry(true)
            .setLoadTypeName("loadtype")
            .build();

    when(mockedSession.syncSend(any())).thenReturn(createDocumentReply(DOC_ID_1));

    LoadTypeSet loadTypeSet = new LoadTypeSet();
    loadTypeSet.addLoadType(1, "loadtype", DocumentProtocol.Priority.HIGH_1);
    DocumentRetriever documentRetriever = new DocumentRetriever(
            new ClusterList(),
            mockedFactory,
            loadTypeSet,
            params);
    documentRetriever.retrieveDocuments();

    verify(mockedSession, times(1)).syncSend(argThat((ArgumentMatcher<GetDocumentMessage>) o ->
            o.getPriority().equals(DocumentProtocol.Priority.HIGH_1) &&
            !o.getRetryEnabled() &&
            o.getLoadType().equals(new LoadType(1, "loadtype", DocumentProtocol.Priority.HIGH_1))));
    assertContainsDocument(DOC_ID_1);
}
 
Example 8
private ArgumentMatcher<PushApplicationManifestRequest> matchesManifest(ApplicationManifest expectedManifest) {
	return new ArgumentMatcher<PushApplicationManifestRequest>() {
		@Override
		public boolean matches(PushApplicationManifestRequest request) {
			if (request.getManifests().size() == EXPECTED_MANIFESTS) {
				return request.getManifests().get(0).equals(expectedManifest);
			}

			return false;
		}

		@Override
		public String toString() {
			return expectedManifest.toString();
		}
	};
}
 
Example 9
Source Project: swage   Source File: MXBeanPollerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void senses() throws Exception {
    final MetricRecorder recorder = new NullRecorder();

    final Sensor sensor1 = mock(Sensor.class);
    final Sensor sensor2 = mock(Sensor.class);
    when(sensor1.addContext(any(TypedMap.class))).then(invocation -> invocation.getArgument(0));
    when(sensor2.addContext(any(TypedMap.class))).then(invocation -> invocation.getArgument(0));

    List<Sensor> sensors = new ArrayList<>();
    sensors.add(sensor1);
    sensors.add(sensor2);

    MXBeanPoller poller = new MXBeanPoller(recorder, 1, sensors);
    Thread.sleep(1500); // wait for a poll to occur
    poller.shutdown();

    final ArgumentMatcher<TypedMap> dataMatch = new DataMatcher();
    verify(sensor1).addContext(argThat(dataMatch));
    verify(sensor2).addContext(argThat(dataMatch));
    verify(sensor1, atLeastOnce()).sense(any(MetricContext.class));
    verify(sensor2, atLeastOnce()).sense(any(MetricContext.class));
}
 
Example 10
@Test
public void testResolve() throws Exception {
    final Credential credential = mock(Credential.class);
    when(credential.getId()).thenReturn("input");

    final PrincipalResolver resolver1 = mock(PrincipalResolver.class);
    when(resolver1.supports(eq(credential))).thenReturn(true);
    when(resolver1.resolve((eq(credential)))).thenReturn(new SimplePrincipal("output"));

    final PrincipalResolver resolver2 = mock(PrincipalResolver.class);
    when(resolver2.supports(any(Credential.class))).thenReturn(false);
    when(resolver2.resolve(argThat(new ArgumentMatcher<Credential>() {
        @Override
        public boolean matches(final Object o) {
            return ((Credential) o).getId().equals("output");
        }
    }))).thenReturn(
            new SimplePrincipal("final", Collections.<String, Object>singletonMap("mail", "[email protected]")));

    final ChainingPrincipalResolver resolver = new ChainingPrincipalResolver();
    resolver.setChain(Arrays.asList(resolver1, resolver2));
    final Principal principal = resolver.resolve(credential);
    assertEquals("final", principal.getId());
    assertEquals("[email protected]", principal.getAttributes().get("mail"));
}
 
Example 11
Source Project: beam   Source File: ReadSpannerSchemaTest.java    License: Apache License 2.0 6 votes vote down vote up
private void prepareColumnMetadata(ReadOnlyTransaction tx, List<Struct> rows) {
  Type type =
      Type.struct(
          Type.StructField.of("table_name", Type.string()),
          Type.StructField.of("column_name", Type.string()),
          Type.StructField.of("spanner_type", Type.string()),
          Type.StructField.of("cells_mutated", Type.int64()));
  when(tx.executeQuery(
          argThat(
              new ArgumentMatcher<Statement>() {

                @Override
                public boolean matches(Statement argument) {
                  if (!(argument instanceof Statement)) {
                    return false;
                  }
                  Statement st = (Statement) argument;
                  return st.getSql().contains("information_schema.columns");
                }
              })))
      .thenReturn(ResultSets.forRows(type, rows));
}
 
Example 12
Source Project: codenvy   Source File: AdminUserCreatorTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void shouldCreateAdminUser() throws Exception {
  Injector injector = Guice.createInjector(new OrgModule());
  UserManager userManager = injector.getInstance(UserManager.class);
  when(userManager.getByName(NAME)).thenThrow(new NotFoundException("nfex"));
  when(userManager.create(any(UserImpl.class), anyBoolean())).thenReturn(user);
  injector.getInstance(AdminUserCreator.class);

  verify(userManager).getByName(NAME);
  verify(userManager).create(new UserImpl(NAME, EMAIL, NAME, PASSWORD, emptyList()), false);
  verify(permissionsManager)
      .storePermission(
          argThat(
              (ArgumentMatcher<SystemPermissionsImpl>)
                  argument -> argument.getUserId().equals("qwe")));
}
 
Example 13
Source Project: beam   Source File: ReadSpannerSchemaTest.java    License: Apache License 2.0 6 votes vote down vote up
private void preparePkMetadata(ReadOnlyTransaction tx, List<Struct> rows) {
  Type type =
      Type.struct(
          Type.StructField.of("table_name", Type.string()),
          Type.StructField.of("column_name", Type.string()),
          Type.StructField.of("column_ordering", Type.string()));
  when(tx.executeQuery(
          argThat(
              new ArgumentMatcher<Statement>() {

                @Override
                public boolean matches(Statement argument) {
                  if (!(argument instanceof Statement)) {
                    return false;
                  }
                  Statement st = (Statement) argument;
                  return st.getSql().contains("information_schema.index_columns");
                }
              })))
      .thenReturn(ResultSets.forRows(type, rows));
}
 
Example 14
Source Project: ShedLock   Source File: TestUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static LockConfiguration hasParams(String name, long lockAtMostFor, long lockAtLeastFor) {
    return argThat(new ArgumentMatcher<LockConfiguration>() {
        @Override
        public boolean matches(LockConfiguration c) {
            return name.equals(c.getName())
                && isNearTo(lockAtMostFor, c.getLockAtMostUntil())
                && isNearTo(lockAtLeastFor, c.getLockAtLeastUntil());
        }

        @Override
        public String toString() {
            Instant now = ClockProvider.now();
            return "hasParams(\"" + name + "\", " + now.plusMillis(lockAtMostFor) + ", " + now.plusMillis(lockAtLeastFor) + ")";
        }
    });
}
 
Example 15
@NonNull
private Throwable eqBackendError(final Class<? extends BackendBaseException> cls, final ApiIOException innerException, final Object content) {
    return argThat(new ArgumentMatcher<Throwable>() {
        @Override
        public boolean matches(Object argument) {
            if (!cls.isInstance(argument)) {
                return false;
            }

            BackendBaseException exception = (BackendBaseException) argument;
            if (!(exception.getCause() instanceof ApiIOException)) {
                return false;
            }

            ApiIOException ioException = (ApiIOException) exception.getCause();
            boolean isIoExceptionTheSameAsInnerException = ioException.toString().equals(innerException.toString());
            if (!(argument instanceof BackendCommunicationExceptionWithContent) || content == null) {
                return isIoExceptionTheSameAsInnerException;
            }

            BackendCommunicationExceptionWithContent exceptionWithContent = (BackendCommunicationExceptionWithContent) argument;
            return isIoExceptionTheSameAsInnerException && exceptionWithContent.getContent().equals(content);
        }
    });
}
 
Example 16
Source Project: bazel-buildfarm   Source File: ShardInstanceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void blobsAreMissingWhenWorkersAreEmpty() throws Exception {
  String workerName = "worker";
  when(mockInstanceLoader.load(eq(workerName))).thenReturn(mockWorkerInstance);

  ImmutableSet<String> workers = ImmutableSet.of(workerName);
  when(mockBackplane.getWorkers()).thenReturn(workers);

  Digest digest = Digest.newBuilder().setHash("hash").setSizeBytes(1).build();
  List<Digest> queryDigests = ImmutableList.of(digest);
  ArgumentMatcher<Iterable<Digest>> queryMatcher =
      (digests) -> Iterables.elementsEqual(digests, queryDigests);
  when(mockWorkerInstance.findMissingBlobs(
          argThat(queryMatcher), any(Executor.class), any(RequestMetadata.class)))
      .thenReturn(immediateFuture(queryDigests));
  Iterable<Digest> missingDigests =
      instance
          .findMissingBlobs(
              queryDigests, newDirectExecutorService(), RequestMetadata.getDefaultInstance())
          .get();
  verify(mockWorkerInstance, times(1))
      .findMissingBlobs(argThat(queryMatcher), any(Executor.class), any(RequestMetadata.class));
  assertThat(missingDigests).containsExactly(digest);
}
 
Example 17
@Test
public void updateSubscriptionEnableAlarm() throws Exception {
    // ****
    // Init, set repo to return a fully disabled alarm
    Alarm disabledAlarm = TestUtils.getDefaultAlarm();
    disabledAlarm.getSubscriptions().get(0).setEnabled(false);
    when(seyrenRepository.getAlarm(TestUtils.DEFAULT_ALARM_ID)).thenReturn(disabledAlarm);
    // ****

    Alarm alarm = TestUtils.getDefaultAlarm();
    Subscription subscription = alarm.getSubscriptions().get(0);
    subscription.setEnabled(true);

    subscriptionService.updateSubscription(subscription, TestUtils.DEFAULT_ALARM_ID);

    verify(seyrenRepository).updateSubscription(subscription, TestUtils.DEFAULT_ALARM_ID);
    verify(seyrenRepository).updateAlarm(argThat(new ArgumentMatcher<Alarm>() {
        @Override
        public boolean matches(Object argument) {
            Alarm argAlarm = (Alarm) argument;
            return argAlarm.getId().equals(alarm.getId()) && argAlarm.isEnabled();
        }
    }));
}
 
Example 18
Source Project: nomulus   Source File: DriveConnectionTest.java    License: Apache License 2.0 5 votes vote down vote up
private ArgumentMatcher<ByteArrayContent> hasByteArrayContent(final byte[] data) {
  return arg -> {
    try {
      return Arrays.equals(data, toByteArray(arg.getInputStream()));
    } catch (Exception e) {
      return false;
    }
  };
}
 
Example 19
Source Project: vividus   Source File: StepExamplesTableParserTests.java    License: Apache License 2.0 5 votes vote down vote up
private void mockStepCreation(ArgumentMatcher<Scenario> matcher)
{
    Step step = mock(Step.class);
    List<Step> steps = List.of(step);
    when(mockStepCollector().collectScenarioSteps(eq(mockCandidateSteps()), argThat(matcher), eq(Map.of()),
            any(MatchingStepMonitor.class))).thenReturn(steps);
}
 
Example 20
Source Project: pmq   Source File: ConsumerGroupServiceImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void createConsumerGroupSuc1Test() {
	when(userInfoHolder.getUserId()).thenReturn("1");
	List<ConsumerGroupEntity> consumerGroupEntities = new ArrayList<ConsumerGroupEntity>();
	ConsumerGroupEntity consumerGroupEntity = new ConsumerGroupEntity();
	consumerGroupEntity.setId(1L);
	consumerGroupEntity.setName("test");
	consumerGroupEntities.add(consumerGroupEntity);
	AtomicInteger counter = new AtomicInteger(0);
	when(consumerGroupRepository.getByNames(Mockito.argThat(new ArgumentMatcher<List<String>>() {
		@Override
		public boolean matches(Object names) {
			counter.incrementAndGet();
			return counter.get() == 2;
		}
	}))).thenReturn(consumerGroupEntities);
	ConsumerGroupCreateRequest consumerGroupCreateRequest = new ConsumerGroupCreateRequest();
	consumerGroupCreateRequest.setAlarmFlag(1);
	consumerGroupCreateRequest.setTraceFlag(1);
	consumerGroupCreateRequest.setMode(1);
	consumerGroupCreateRequest.setName("test");
	consumerGroupCreateRequest.setIpFlag(0);
	consumerGroupCreateRequest.setIpList("213");
	ArgumentCaptor<ConsumerGroupEntity> argument = ArgumentCaptor.forClass(ConsumerGroupEntity.class);
	consumerGroupServiceImpl.createConsumerGroup(consumerGroupCreateRequest);
	verify(consumerGroupRepository).insert(argument.capture());

	assertEquals("test", argument.getValue().getOriginName());
	assertEquals("213", argument.getValue().getIpWhiteList());
	assertEquals(null, argument.getValue().getIpBlackList());
}
 
Example 21
Source Project: beam   Source File: SpannerIOWriteTest.java    License: Apache License 2.0 5 votes vote down vote up
private Iterable<Mutation> iterableOfSize(final int size) {
  return argThat(
      new ArgumentMatcher<Iterable<Mutation>>() {

        @Override
        public boolean matches(Iterable<Mutation> argument) {
          return argument instanceof Iterable && Iterables.size((Iterable<?>) argument) == size;
        }

        @Override
        public String toString() {
          return "The size of the iterable must equal " + size;
        }
      });
}
 
Example 22
Source Project: pmq   Source File: ConsumerGroupServiceImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void editConsumerGroupNormalTest() {
	when(userInfoHolder.getUserId()).thenReturn("1");
	when(roleService.getRole(anyString(), anyString())).thenReturn(1);
	when(consumerGroupRepository.getById(anyLong())).thenReturn(buildConsumerGroupEntity());	
	List<ConsumerGroupEntity> consumerGroupEntities = new ArrayList<ConsumerGroupEntity>();
	ConsumerGroupEntity consumerGroupEntity = new ConsumerGroupEntity();
	consumerGroupEntity.setId(1L);
	consumerGroupEntity.setName("test");
	consumerGroupEntities.add(consumerGroupEntity);
	AtomicInteger counter = new AtomicInteger(0);
	when(consumerGroupRepository.getByNames(Mockito.argThat(new ArgumentMatcher<List<String>>() {
		@Override
		public boolean matches(Object names) {
			counter.incrementAndGet();
			return counter.get() == 2;
		}
	}))).thenReturn(consumerGroupEntities);
	ConsumerGroupCreateRequest consumerGroupCreateRequest = new ConsumerGroupCreateRequest();
	consumerGroupCreateRequest.setId("1");
	consumerGroupCreateRequest.setAppId("1234");
	consumerGroupCreateRequest.setAlarmFlag(1);
	consumerGroupCreateRequest.setTraceFlag(1);
	consumerGroupCreateRequest.setMode(1);
	consumerGroupCreateRequest.setName("test");
	consumerGroupCreateRequest.setIpFlag(0);
	consumerGroupCreateRequest.setIpList("213");
	ArgumentCaptor<ConsumerGroupEntity> argument = ArgumentCaptor.forClass(ConsumerGroupEntity.class);
	consumerGroupServiceImpl.createConsumerGroup(consumerGroupCreateRequest);
	verify(consumerGroupRepository).update(argument.capture()); 
	verify(topicService).updateFailTopic(any(ConsumerGroupEntity.class));
}
 
Example 23
private ArgumentMatcher<Collection<Agent>> collectionMatches(final Collection<Agent> values) {
    return new ArgumentMatcher<Collection<Agent>>() {
        @Override
        public boolean matches(Collection<Agent> argument) {
            return new ArrayList<>(argument).equals(new ArrayList<>(values));
        }
    };
}
 
Example 24
Source Project: big-c   Source File: TestContainer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verify container launch when all resources already cached.
 */
@Test
public void testLocalizationLaunch() throws Exception {
  WrappedContainer wc = null;
  try {
    wc = new WrappedContainer(8, 314159265358979L, 4344, "yak");
    assertEquals(ContainerState.NEW, wc.c.getContainerState());
    wc.initContainer();
    Map<Path, List<String>> localPaths = wc.localizeResources();

    // all resources should be localized
    assertEquals(ContainerState.LOCALIZED, wc.c.getContainerState());
    assertNotNull(wc.c.getLocalizedResources());
    for (Entry<Path, List<String>> loc : wc.c.getLocalizedResources()
        .entrySet()) {
      assertEquals(localPaths.remove(loc.getKey()), loc.getValue());
    }
    assertTrue(localPaths.isEmpty());

    final WrappedContainer wcf = wc;
    // verify container launch
    ArgumentMatcher<ContainersLauncherEvent> matchesContainerLaunch =
      new ArgumentMatcher<ContainersLauncherEvent>() {
        @Override
        public boolean matches(Object o) {
          ContainersLauncherEvent launchEvent = (ContainersLauncherEvent) o;
          return wcf.c == launchEvent.getContainer();
        }
      };
    verify(wc.launcherBus).handle(argThat(matchesContainerLaunch));
  } finally {
    if (wc != null) {
      wc.finished();
    }
  }
}
 
Example 25
Source Project: hop   Source File: CalculatorUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMissingFile() throws HopException {
  RowMeta inputRowMeta = new RowMeta();
  ValueMetaString pathMeta = new ValueMetaString( "Path" );
  inputRowMeta.addValueMeta( pathMeta );

  String filepath = "missingFile";
  Object[] rows = new Object[] { filepath };
  IRowSet inputRowSet = smh.getMockInputRowSet( rows );
  inputRowSet.setRowMeta( inputRowMeta );

  CalculatorMeta meta = new CalculatorMeta();
  CalculatorMetaFunction[] calculations = new CalculatorMetaFunction[] {
    new CalculatorMetaFunction( "result", CalculatorMetaFunction.CALC_MD5, "Path", null, null,
      IValueMeta.TYPE_STRING, 0, 0, false, "", "", "", "" ) };
  meta.setCalculation( calculations );
  meta.setFailIfNoFile( true );

  CalculatorData data = new CalculatorData();

  Calculator calculator = spy( new Calculator( smh.transformMeta, meta, data, 0, smh.pipelineMeta, smh.pipeline ) );
  calculator.addRowSetToInputRowSets( inputRowSet );
  calculator.setInputRowMeta( inputRowMeta );
  calculator.init();



  boolean processed = calculator.processRow();
  verify( calculator, times( 1 ) ).logError( argThat( new ArgumentMatcher<String>() {
    @Override
    public boolean matches( Object o ) {
      return ( (String) o ).contains( BaseMessages.getString( PKG, "Calculator.Log.NoFile" ) );
    }
  } ) );
  assertFalse( processed );
}
 
Example 26
Source Project: kylin-on-parquet-v2   Source File: KylinConnectionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testJdbcClientCalcitePropsInUrl() throws Exception {
    String sql = "select 1 as val";

    // mock client
    when(client.executeQuery(anyString(), Mockito.<List<Object>>any(), Mockito.<Map<String, String>>any())).thenReturn(getMockResult());
    Map<String, String> toggles = new HashMap<>();
    Properties info = new Properties();
    info.setProperty("caseSensitive", "false");
    info.setProperty("unquotedCasing", "UNCHANGED");
    try (KylinConnection conn = getConnectionWithMockClient("jdbc:kylin:test_url/test_db", info)) {
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        try (ResultSet resultSet = preparedStatement.executeQuery()) {
            verify(client).executeQuery(eq(sql), Mockito.<List<Object>>any(), argThat(new ArgumentMatcher<Map<String, String>>() {
                @Override
                public boolean matches(Map<String, String> argument) {
                    String propsStr = argument.get("JDBC_CLIENT_CALCITE_PROPS");
                    assertNotNull(propsStr);
                    Properties props = new Properties();
                    try {
                        props.load(new StringReader(propsStr));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    assertEquals("false", props.getProperty("caseSensitive"));
                    assertEquals("UNCHANGED", props.getProperty("unquotedCasing"));
                    return true;
                }
            }));

            assertTrue(resultSet.next());
            ResultSetMetaData metaData = resultSet.getMetaData();
            assertEquals("VAL", metaData.getColumnName(1));
            assertEquals(1, resultSet.getInt("VAL"));
        }
    }
}
 
Example 27
private ArgumentMatcher<HttpUriRequest> isHttpGetAndContainsCorrectURI() {
	return (httpGet) -> {
		boolean hasCorrectURI = httpGet.getURI().equals(CONFIG_ENDPOINT_URI);
		boolean correctMethod = httpGet.getMethod().equals(HttpMethod.GET.toString());
		return hasCorrectURI && correctMethod;
	};
}
 
Example 28
Source Project: localization_nifi   Source File: DataAuthorizableTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthorizedUser() {
    final NiFiUser user = new StandardNiFiUser(IDENTITY_1);
    testDataAuthorizable.authorize(testAuthorizer, RequestAction.READ, user, null);

    verify(testAuthorizer, times(1)).authorize(argThat(new ArgumentMatcher<AuthorizationRequest>() {
        @Override
        public boolean matches(Object o) {
            return IDENTITY_1.equals(((AuthorizationRequest) o).getIdentity());
        }
    }));
}
 
Example 29
Source Project: localization_nifi   Source File: DataAuthorizableTest.java    License: Apache License 2.0 5 votes vote down vote up
private void verifyAuthorizeForUser(final String identity) {
    verify(testAuthorizer, times(1)).authorize(argThat(new ArgumentMatcher<AuthorizationRequest>() {
        @Override
        public boolean matches(Object o) {
            return identity.equals(((AuthorizationRequest) o).getIdentity());
        }
    }));
}
 
Example 30
private ArgumentMatcher<DeployApplicationRequest> matchesRequest(String appName, String appArchive,
	Map<String, String> properties,
	Map<String, Object> environment,
	List<String> services) {
	return request ->
		request.getName().equals(appName) &&
			request.getPath().equals(appArchive) &&
			request.getProperties().equals(properties) &&
			request.getEnvironment().equals(environment) &&
			request.getServices().equals(services);
}