org.mockito.Matchers Java Examples

The following examples show how to use org.mockito.Matchers. 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 check out the related API usage on the sidebar.
Example #1
Source File: GeoServerRestClientTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
private WebTarget mockedWebTarget() {
  final WebTarget webTarget = Mockito.mock(WebTarget.class);
  final Invocation.Builder invBuilder = Mockito.mock(Invocation.Builder.class);
  final Response response = Mockito.mock(Response.class);

  Mockito.when(webTarget.path(Matchers.anyString())).thenReturn(webTarget);
  Mockito.when(
      webTarget.queryParam(Matchers.eq("quietOnNotFound"), Matchers.anyBoolean())).thenReturn(
          webTarget);
  Mockito.when(webTarget.request()).thenReturn(invBuilder);

  Mockito.when(invBuilder.get()).thenReturn(response);
  Mockito.when(invBuilder.delete()).thenReturn(response);
  Mockito.when(invBuilder.post(Matchers.any(Entity.class))).thenReturn(response);

  return webTarget;
}
 
Example #2
Source File: SeyrenRepositoryTest.java    From cerebro with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testAddSubscription_ko() {

    ResponseEntity<Object> response = new ResponseEntity(HttpStatus.CONFLICT);
    Subscription subscription = new Subscription();

    when(restTemplate.postForEntity(anyString(),anyObject(),Matchers.<Class<Object>>any())).thenReturn(response);
    try{
        repository.addSubscription(subscription,"alarmid");
        verify(restTemplate).postForEntity(DEFAULT_SEYREN_URL + SeyrenRepository.API_ALARMS+"/alarmid/subscriptions/", subscription, Object.class);
        fail();
    }
    catch(SeyrenException e){
        assertEquals(e.getHttpStatus(),HttpStatus.CONFLICT.value());
        assertEquals(e.getAction(),"addSubscription");
    }

}
 
Example #3
Source File: ESManagerTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "static-access" })
@Test 
public void createIndexTest() throws Exception{
    
    HttpEntity jsonEntity = new StringEntity("{}", ContentType.APPLICATION_JSON);
    when(response.getEntity()).thenReturn(jsonEntity);
    when(restClient.performRequest(anyString(), anyString(), anyMap(), any(HttpEntity.class),
    Matchers.<Header>anyVararg())).thenReturn(response);
    ReflectionTestUtils.setField(esManager, "restClient", restClient);
    when(sl.getStatusCode()).thenReturn(100);
    when(response.getStatusLine()).thenReturn(sl);
    
    esManager.createIndex("index", new ArrayList<>());
    
    when(sl.getStatusCode()).thenReturn(200);
    when(response.getStatusLine()).thenReturn(sl);
    
    esManager.createIndex("index", new ArrayList<>());
    
    when(restClient.performRequest(anyString(), anyString(), anyMap(), any(HttpEntity.class),
    Matchers.<Header>anyVararg())).thenThrow(new IOException());
    ReflectionTestUtils.setField(esManager, "restClient", restClient);
    esManager.createIndex("index", new ArrayList<>());
}
 
Example #4
Source File: StackTraceSampleCoordinatorTest.java    From flink with Apache License 2.0 6 votes vote down vote up
private ExecutionVertex mockExecutionVertex(
		ExecutionAttemptID executionId,
		ExecutionState state,
		boolean sendSuccess) {

	Execution exec = Mockito.mock(Execution.class);
	CompletableFuture<StackTraceSampleResponse> failedFuture = new CompletableFuture<>();
	failedFuture.completeExceptionally(new Exception("Send failed."));

	Mockito.when(exec.getAttemptId()).thenReturn(executionId);
	Mockito.when(exec.getState()).thenReturn(state);
	Mockito.when(exec.requestStackTraceSample(Matchers.anyInt(), Matchers.anyInt(), Matchers.any(Time.class), Matchers.anyInt(), Matchers.any(Time.class)))
		.thenReturn(
			sendSuccess ?
				CompletableFuture.completedFuture(Mockito.mock(StackTraceSampleResponse.class)) :
				failedFuture);

	ExecutionVertex vertex = Mockito.mock(ExecutionVertex.class);
	Mockito.when(vertex.getJobvertexId()).thenReturn(new JobVertexID());
	Mockito.when(vertex.getCurrentExecutionAttempt()).thenReturn(exec);

	return vertex;
}
 
Example #5
Source File: LocalCapabilitiesDirectoryTest.java    From joynr with Apache License 2.0 6 votes vote down vote up
private void testLookupByDomainInterfaceIsProperlyRejected(DiscoveryError expectedError) throws InterruptedException {
    String domain = "domain";
    String[] domains = new String[]{ domain };
    String interfaceName = "interface";
    DiscoveryQos discoveryQos = new DiscoveryQos();
    discoveryQos.setDiscoveryScope(DiscoveryScope.GLOBAL_ONLY);

    doAnswer(createAddAnswerWithDiscoveryError(expectedError)).when(globalCapabilitiesDirectoryClient)
                                                              .lookup(Matchers.<CallbackWithModeledError<List<GlobalDiscoveryEntry>, DiscoveryError>> any(),
                                                                      eq(domains),
                                                                      eq(interfaceName),
                                                                      anyLong(),
                                                                      Matchers.<String[]> any());

    Promise<Lookup1Deferred> promise = localCapabilitiesDirectory.lookup(domains, interfaceName, discoveryQos);

    verify(globalCapabilitiesDirectoryClient).lookup(Matchers.<CallbackWithModeledError<List<GlobalDiscoveryEntry>, DiscoveryError>> any(),
                                                     eq(domains),
                                                     eq(interfaceName),
                                                     anyLong(),
                                                     Matchers.<String[]> any());

    checkPromiseErrorInProviderRuntimeException(promise, expectedError);
}
 
Example #6
Source File: AltsHandshakerClientTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void startClientHandshakeWithOptions() throws Exception {
  when(mockStub.send(Matchers.<HandshakerReq>any()))
      .thenReturn(MockAltsHandshakerResp.getOkResponse(0));

  ByteBuffer outFrame = handshaker.startClientHandshake();
  assertEquals(ByteString.copyFrom(outFrame), MockAltsHandshakerResp.getOutFrame());

  HandshakerReq req =
      HandshakerReq.newBuilder()
          .setClientStart(
              StartClientHandshakeReq.newBuilder()
                  .setHandshakeSecurityProtocol(HandshakeProtocol.ALTS)
                  .addApplicationProtocols(AltsHandshakerClient.getApplicationProtocol())
                  .addRecordProtocols(AltsHandshakerClient.getRecordProtocol())
                  .setTargetName(TEST_TARGET_NAME)
                  .addTargetIdentities(
                      Identity.newBuilder().setServiceAccount(TEST_TARGET_SERVICE_ACCOUNT))
                  .build())
          .build();
  verify(mockStub).send(req);
}
 
Example #7
Source File: SubscriptionServicePaymentTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test(expected = TechnicalServiceNotAliveException.class)
public void modifySubscriptionPaymentData_SuspendedTechnicalServiceNotAliveException()
        throws Exception {
    Mockito.doThrow(new TechnicalServiceNotAliveException())
            .when(applicationServiceMock)
            .activateInstance(Matchers.eq(subscription));
    try {
        setPaymentTypesForProduct(subscription.getProduct(),
                paymentInfoCreditCard.getPaymentType());
        subscriptionServiceBean.modifySubscriptionPaymentData(sub, bc,
                piCreditCard);
    } finally {
        Mockito.verify(applicationServiceMock, Mockito.times(1))
                .activateInstance(Matchers.eq(subscription));
        Assert.assertEquals(SubscriptionStatus.SUSPENDED,
                subscription.getStatus());
        Mockito.verify(sessionContextMock, Mockito.times(1))
                .setRollbackOnly();
    }
}
 
Example #8
Source File: AccountServiceBillingContactTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void delete_SubscriptionsChargeableActive_TechnicalServiceOperationException()
        throws Exception {
    Set<Subscription> subs = createSubs(SubscriptionStatus.ACTIVE);
    Subscription sub = subs.iterator().next();
    sub.getPriceModel().setType(PriceModelType.PRO_RATA);
    // ensure that exception is not thrown
    Mockito.doThrow(new TechnicalServiceOperationException())
            .when(applicationServiceMock)
            .deactivateInstance(Matchers.eq(sub));
    billingContact.setSubscriptions(subs);
    accountServiceBean.deleteBillingContact(bc);
    // verify that setRollbackOnly has been called never
    Mockito.verify(sessionContextMock, Mockito.never()).setRollbackOnly();
    Assert.assertNull(sub.getBillingContact());
    Assert.assertEquals(SubscriptionStatus.SUSPENDED, sub.getStatus());
    Mockito.verify(applicationServiceMock, Mockito.times(1))
            .deactivateInstance(Matchers.eq(sub));
}
 
Example #9
Source File: DocumentManagerBeanTest.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
/**
 *
 * This test will check if the ACL is null when removing it from a document
 *
 */

@Test
public void removeACLFromDocument() throws Exception {

    user = new User(workspace, new Account(DocumentUtil.USER_1_LOGIN, DocumentUtil.USER_1_NAME, DocumentUtil.USER1_MAIL, DocumentUtil.LANGUAGE, new Date(), null));

    DocumentMaster documentMaster = new DocumentMaster(workspace, DocumentUtil.DOCUMENT_ID, user);
    documentRevision = new DocumentRevision(documentMaster, "A", user);
    documentIteration = new DocumentIteration(documentRevision, user);
    documentRevision.setCheckOutUser(user);
    documentRevision.setCheckOutDate(new Date());
    acl = new ACL();
    acl.addEntry(user, ACLPermission.READ_ONLY);
    documentRevision.setACL(acl);

    DocumentRevisionKey documentRevisionKey = new DocumentRevisionKey(workspace.getId(), documentMaster.getId(), documentRevision.getVersion());

    Mockito.when(userManager.checkWorkspaceReadAccess(workspace.getId())).thenReturn(user);
    Mockito.when(aclTypedQuery.setParameter(Matchers.anyString(), Matchers.any())).thenReturn(aclTypedQuery);
    Mockito.when(documentRevisionDAO.getDocRRef(documentRevisionKey)).thenReturn(documentRevision);

    documentManagerBean.removeACLFromDocumentRevision(documentRevision.getKey());
    Assert.assertNull(documentRevision.getACL());
}
 
Example #10
Source File: AuroraCLIControllerTest.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
@Test
public void testRestartJob() throws Exception {
  int containerId = 1;
  List<String> expectedCommand = asList("aurora job restart %s/%s %s %s %d",
      JOB_SPEC, containerId, VERBOSE_CONFIG, BATCH_CONFIG, Integer.MAX_VALUE);

  // Failed
  Mockito.doReturn(false).when(controller).runProcess(Matchers.anyListOf(String.class));
  Assert.assertFalse(controller.restart(containerId));
  Mockito.verify(controller).runProcess(Mockito.eq(expectedCommand));

  // Happy path
  Mockito.doReturn(true).when(controller).runProcess(Matchers.anyListOf(String.class));
  Assert.assertTrue(controller.restart(containerId));
  Mockito.verify(controller, Mockito.times(2)).runProcess(expectedCommand);
}
 
Example #11
Source File: TargetTypesServiceImplTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void getAttributeValuesTest() throws IOException {
	AttributeValuesRequest attributeValuesRequest = getAttributeValuesRequest();
	when(config.getElasticSearch()).thenReturn(getElasticSearchProperty());
	HttpEntity jsonEntity = new StringEntity("{}", ContentType.APPLICATION_JSON);
       when(response.getEntity()).thenReturn(jsonEntity);
       when(restClient.performRequest(anyString(), anyString(), any(Map.class), any(HttpEntity.class),
       Matchers.<Header>anyVararg())).thenReturn(response);
       ReflectionTestUtils.setField(targetTypesServiceImpl, "restClient", restClient);
       when(sl.getStatusCode()).thenReturn(200);
	    when(response.getStatusLine()).thenReturn(sl);
	    Map<String, Object> ruleParamDetails = Maps.newHashMap();
       when(mapper.readValue(anyString(), any(TypeReference.class))).thenReturn(ruleParamDetails);
	assertThat(targetTypesService.getAttributeValues(attributeValuesRequest), is(notNullValue()));
}
 
Example #12
Source File: ManagedChannelImplTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void loadBalancerThrowsInHandleResolvedAddresses() {
  RuntimeException ex = new RuntimeException("simulated");
  // Delay the success of name resolution until allResolved() is called
  FakeNameResolverFactory nameResolverFactory =
      new FakeNameResolverFactory.Builder(expectedUri)
          .setResolvedAtStart(false)
          .setServers(Collections.singletonList(new EquivalentAddressGroup(socketAddress)))
          .build();
  channelBuilder.nameResolverFactory(nameResolverFactory);
  createChannel();

  verify(mockLoadBalancerFactory).newLoadBalancer(any(Helper.class));
  doThrow(ex).when(mockLoadBalancer).handleResolvedAddressGroups(
      Matchers.<List<EquivalentAddressGroup>>anyObject(), any(Attributes.class));

  // NameResolver returns addresses.
  nameResolverFactory.allResolved();

  // Exception thrown from balancer is caught by ChannelExecutor, making channel enter panic mode.
  verifyPanicMode(ex);
}
 
Example #13
Source File: ClientCallImplTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void statusPropagatedFromStreamToCallListener() {
  DelayedExecutor executor = new DelayedExecutor();
  ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
      method,
      executor,
      baseCallOptions,
      provider,
      deadlineCancellationExecutor,
      channelCallTracer,
      false /* retryEnabled */);
  call.start(callListener, new Metadata());
  verify(stream).start(listenerArgumentCaptor.capture());
  final ClientStreamListener streamListener = listenerArgumentCaptor.getValue();
  streamListener.headersRead(new Metadata());
  Status status = Status.RESOURCE_EXHAUSTED.withDescription("simulated");
  streamListener.closed(status , new Metadata());
  executor.release();

  verify(callListener).onClose(same(status), Matchers.isA(Metadata.class));
}
 
Example #14
Source File: ZipFileProcessorTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoControlFileZipFileProcessor() throws Exception {

    Exchange preObject = new DefaultExchange(new DefaultCamelContext());

    String batchJobId = NewBatchJob.createId("NoControlFile.zip");
    Mockito.when(workNote.getBatchJobId()).thenReturn(batchJobId);
    preObject.getIn().setBody(workNote);
    Mockito.when(mockedBatchJobDAO.findBatchJobById(Matchers.eq(batchJobId))).thenReturn(mockedJob);

    File zipFile = IngestionTest.getFile("zip/NoControlFile.zip");
    ResourceEntry entry = new ResourceEntry();
    entry.setResourceName(zipFile.getAbsolutePath());
    Mockito.when(mockedJob.getZipResourceEntry()).thenReturn(entry);

    createResourceEntryAndAddToJob(zipFile, mockedJob);
    mockedJob.setSourceId("zip");
    Mockito.when(mockedBatchJobDAO.findBatchJobById(Matchers.eq(batchJobId))).thenReturn(mockedJob);
    preObject.getIn().setHeader("BatchJobId", batchJobId);

    zipProc.process(preObject);

    Assert.assertNotNull(preObject.getIn().getBody());
    Assert.assertTrue(preObject.getIn().getBody(WorkNote.class).hasErrors());
    Assert.assertEquals(preObject.getIn().getHeader("IngestionMessageType") , MessageType.BATCH_REQUEST.name());
}
 
Example #15
Source File: TenantLogControllerTest.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@Test
@WithMockUser(authorities = { "ROLE_SUPER_USER", "ROLE_IOT_USER", "ROLE_ANALYTICS_USER" })
public void shouldDescendingTenantLogs() throws Exception {

	ServiceResponse<List<TenantLog>> responseTenantOk = ServiceResponseBuilder.<List<TenantLog>>ok().build();

	List<TenantLog> logs = new ArrayList<TenantLog>();
	logs.add(TenantLog.builder().time(new Date()).build());
	logs.add(TenantLog.builder().time(new Date()).build());
	responseTenantOk.setResult(logs);

	when(tenantLogService.findByTenant(Matchers.anyObject(), Matchers.eq(false))).thenReturn(responseTenantOk);
	when(dateToStringConverter.convert(Matchers.anyObject())).thenReturn("00/00/0000");

	ResultActions result = getMockMvc().perform(get("/tenants/log").param("asc", "false"));

	result.andExpect(model().attribute("logs", org.hamcrest.Matchers.iterableWithSize(2)));
	result.andExpect(model().attribute("asc", org.hamcrest.Matchers.equalTo(false)));

}
 
Example #16
Source File: ESManagerTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "static-access" })
@Test 
public void configureIndexAndTypesTest() throws Exception{
    
    PowerMockito.mockStatic(ConfigManager.class);
    List<String> types = new ArrayList<>();
    types.add("ds");
    when(ConfigManager.getTypes(anyString())).thenReturn(new HashSet<>(types));
    
    HttpEntity jsonEntity = new StringEntity("{}", ContentType.APPLICATION_JSON);
    when(response.getEntity()).thenReturn(jsonEntity);
    when(restClient.performRequest(anyString(), anyString(), anyMap(), any(HttpEntity.class),
    Matchers.<Header>anyVararg())).thenReturn(response);
    ReflectionTestUtils.setField(esManager, "restClient", restClient);
    when(sl.getStatusCode()).thenReturn(100);
    when(response.getStatusLine()).thenReturn(sl);
    
    esManager.configureIndexAndTypes("index",new ArrayList<>());
}
 
Example #17
Source File: LocatorFetchRunnableTest.java    From blueflood with Apache License 2.0 6 votes vote down vote up
@Test
public void finishExecutionWhenSuccessful() {

    // given
    when(executionContext.wasSuccessful()).thenReturn(true);

    // when
    lfr.finishExecution(0, executionContext);

    // then
    verify(executionContext, times(1)).wasSuccessful();
    verifyNoMoreInteractions(executionContext);
    verify(scheduleCtx, times(1)).clearFromRunning(Matchers.<SlotKey>any());
    verify(scheduleCtx).getCurrentTimeMillis();
    verifyNoMoreInteractions(scheduleCtx);
}
 
Example #18
Source File: AbstractReaderTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testTaskEvent() throws Exception {
	final AbstractReader reader = new MockReader(createInputGate(1));

	final EventListener<TaskEvent> listener1 = mock(EventListener.class);
	final EventListener<TaskEvent> listener2 = mock(EventListener.class);
	final EventListener<TaskEvent> listener3 = mock(EventListener.class);

	reader.registerTaskEventListener(listener1, TestTaskEvent1.class);
	reader.registerTaskEventListener(listener2, TestTaskEvent2.class);
	reader.registerTaskEventListener(listener3, TaskEvent.class);

	reader.handleEvent(new TestTaskEvent1()); // for listener1 only
	reader.handleEvent(new TestTaskEvent2()); // for listener2 only

	verify(listener1, times(1)).onEvent(Matchers.any(TaskEvent.class));
	verify(listener2, times(1)).onEvent(Matchers.any(TaskEvent.class));
	verify(listener3, times(0)).onEvent(Matchers.any(TaskEvent.class));
}
 
Example #19
Source File: SchedulerRestWorkflowFromCatalogExecutionTest.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testWhenSubmittingAValidTemplateWithoutVariablesThenTheDefaultJobVariableIsUsed() throws Exception {
    when(scheduler.submit(Matchers.<Job> any())).thenReturn(new JobIdImpl(88L, "job"));
    ArgumentCaptor<Job> argumentCaptor = ArgumentCaptor.forClass(Job.class);

    String workflowUrl = getBaseUriTestWorkflowsServer() + "/workflow";

    JobIdData response = schedulerRest.submitFromUrl(sessionId, workflowUrl, getEmptyPathSegment(), null);

    verify(scheduler).submit(argumentCaptor.capture());
    Job interceptedJob = argumentCaptor.getValue();
    Assert.assertEquals(1, interceptedJob.getVariables().size());
    Assert.assertEquals("defaultvalue", interceptedJob.getVariables().get("var1").getValue());

    Assert.assertEquals(88L, response.getId());
    Assert.assertEquals("job", response.getReadableName());
}
 
Example #20
Source File: KubernetesSchedulerTest.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
@Test
public void testOnRestart() throws Exception {
  KubernetesController controller = Mockito.mock(KubernetesController.class);
  Mockito.doReturn(controller).when(scheduler).getController();
  scheduler.initialize(config, mockRuntime);

  // Construct RestartTopologyRequest
  Scheduler.RestartTopologyRequest restartTopologyRequest =
      Scheduler.RestartTopologyRequest.newBuilder()
          .setTopologyName(TOPOLOGY_NAME)
          .setContainerIndex(CONTAINER_INDEX)
          .build();

  // Fail to restart
  Mockito.doReturn(false).when(controller).restart(Mockito.anyInt());
  Assert.assertFalse(scheduler.onRestart(restartTopologyRequest));
  Mockito.verify(controller).restart(Matchers.anyInt());

  // Succeed to restart
  Mockito.doReturn(true).when(controller).restart(Mockito.anyInt());
  Assert.assertTrue(scheduler.onRestart(restartTopologyRequest));
  Mockito.verify(controller, Mockito.times(2)).restart(Matchers.anyInt());
}
 
Example #21
Source File: DedupQueueTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Test
public void testPollSkipsEmptyChannels() {
    EventReaderDAO readerDao = mock(EventReaderDAO.class);
    EventStore eventStore = new DefaultEventStore(readerDao, mock(EventWriterDAO.class), new AstyanaxEventIdSerializer(), new MockClaimStore());

    DedupQueue q = new DedupQueue("test-queue", "read", "write",
            mock(QueueDAO.class), eventStore, Suppliers.ofInstance(true), mock(ScheduledExecutorService.class), getPersistentSortedQueueFactory(),
            mock(MetricRegistry.class));
    q.startAndWait();

    // The first poll checks the read channel, find it empty, checks the write channel.
    q.poll(Duration.ofSeconds(30), new SimpleEventSink(10));
    verify(readerDao).readNewer(eq("read"), Matchers.<EventSink>any());
    verify(readerDao).readNewer(eq("write"), Matchers.<EventSink>any());
    verifyNoMoreInteractions(readerDao);

    reset(readerDao);

    // Subsequent polls w/in a short window skips the poll operations.
    q.poll(Duration.ofSeconds(30), new SimpleEventSink(10));
    verifyNoMoreInteractions(readerDao);
}
 
Example #22
Source File: AddIpToVmNicTest.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateFailure() throws ResourceAllocationException, ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException {

    NetworkService networkService = Mockito.mock(NetworkService.class);
    AddIpToVmNicCmd ipTonicCmd = Mockito.mock(AddIpToVmNicCmd.class);

    Mockito.when(
        networkService.allocateSecondaryGuestIP(Matchers.anyLong(), Matchers.any()))
        .thenReturn(null);

    ipTonicCmd._networkService = networkService;

    try {
        ipTonicCmd.execute();
    } catch (InsufficientAddressCapacityException e) {
        throw new InvalidParameterValueException("Allocating guest ip for nic failed");
    }
}
 
Example #23
Source File: LookupHelperTests.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
@Test
public void testAuthenticateAndLoadVsoContexts_specifiedAccountUrl() {
    final ServerContextLookupOperation.ContextScope scope = ServerContextLookupOperation.ContextScope.REPOSITORY;
    final String serverUrl = "http://test.visualstudio.com";
    final AuthenticationInfo authInfo = new AuthenticationInfo("user1", "pass1", serverUrl, "userOne");
    final LoginPageModel loginPageModel = Mockito.mock(LoginPageModel.class);
    when(loginPageModel.getServerName()).thenReturn(serverUrl);
    final ServerContextLookupPageModel lookupPageModel = Mockito.mock(ServerContextLookupPageModel.class);
    final AuthenticationProvider authenticationProvider = Mockito.mock(AuthenticationProvider.class);
    when(authenticationProvider.isAuthenticated(serverUrl)).thenReturn(true);
    when(authenticationProvider.getAuthenticationInfo(serverUrl)).thenReturn(authInfo);
    final ServerContextLookupListener lookupListener = Mockito.mock(ServerContextLookupListener.class);

    LookupHelper.authenticateAndLoadVsoContexts(loginPageModel, lookupPageModel,
            authenticationProvider, lookupListener, scope);

    verify(loginPageModel).setConnected(true);
    verify(lookupPageModel).setLoading(true);
    verify(lookupListener).loadContexts(anyList(), Matchers.eq(scope));
}
 
Example #24
Source File: AlertTriggerRestControllerTest.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateAlertTrigger() throws Exception {

    when(alertTriggerService.save(Matchers.any(Tenant.class), Matchers.any(Application.class), Matchers.any(AlertTrigger.class)))
        .thenReturn(ServiceResponseBuilder.<AlertTrigger> ok()
                .withResult(silenceAlertTrigger).build());

    getMockMvc()
            .perform(MockMvcRequestBuilders
                    .post(MessageFormat.format("/{0}/{1}", application.getName(), BASEPATH))
                    .contentType("application/json")
                    .content(getJson(new AlertTriggerInputVO().apply(silenceAlertTrigger)))
                    .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().is2xxSuccessful())
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(jsonPath("$.code", is(HttpStatus.CREATED.value())))
            .andExpect(jsonPath("$.status", is("success")))
            .andExpect(jsonPath("$.timestamp",greaterThan(1400000000)))
            .andExpect(jsonPath("$.result.name", is(silenceAlertTrigger.getName())))
            .andExpect(jsonPath("$.result.description", is(silenceAlertTrigger.getDescription())))
            .andExpect(jsonPath("$.result.deviceModelName", is(deviceModel.getName())))
            .andExpect(jsonPath("$.result.locationName", is(location.getName())))
            .andExpect(jsonPath("$.result.type", is("SILENCE")))
            .andExpect(jsonPath("$.result.minutes", is(200)))
    ;
}
 
Example #25
Source File: NativeFolderWatchServiceTest.java    From PeerWasp with MIT License 6 votes vote down vote up
@Test
public void testCreateManyFiles() throws Exception{
	watchService.start(basePath);
	File file = null;
	int fileNumbers = 1000;

	for (int i = 1; i <= fileNumbers; i++){

		String randomFileName = WatchServiceTestHelpers.getRandomString(9, "abcdefg123456789");

		file = Paths.get(basePath.toString(), randomFileName + ".txt").toFile();
		FileWriter out = new FileWriter(file);
		WatchServiceTestHelpers.writeRandomData(out, NUM_CHARS_SMALL_FILE);
		out.close();
		// System.out.println("File added: Itemnr.: " + i);
	}
	sleep();

	Mockito.verify(fileManager, Mockito.times(fileNumbers)).add(Matchers.anyObject());
}
 
Example #26
Source File: WebServerServiceRestImplTest.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateWebServerPopulatesTemplatesFromGroup() throws IOException {
    final JsonCreateWebServer jsonCreateWebServer = mock(JsonCreateWebServer.class);
    when(Config.mockWebServerService.createWebServer(any(CreateWebServerRequest.class), any(User.class))).thenReturn(webServer);

    List<String> templateNames = new ArrayList<>();
    templateNames.add("httpd.conf");

    when(Config.mockGroupService.getGroupWebServersResourceTemplateNames(anyString())).thenReturn(templateNames);
    when(Config.mockGroupService.getGroupWebServerResourceTemplate(anyString(), anyString(), eq(false), any(ResourceGroup.class))).thenReturn("httpd.conf template");
    when(Config.mockGroupService.getGroupWebServerResourceTemplateMetaData(anyString(), anyString())).thenReturn("{}");
    ResourceTemplateMetaData mockMetaData = mock(ResourceTemplateMetaData.class);
    when(mockMetaData.getDeployFileName()).thenReturn("httpd.conf");
    when(Config.mockResourceService.getTokenizedMetaData(anyString(), Matchers.anyObject(), anyString())).thenReturn(mockMetaData);
    final Response response = webServerServiceRest.createWebServer(jsonCreateWebServer, Config.mockAuthenticatedUser);
    assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());
}
 
Example #27
Source File: APPAuthenticationServiceBeanIT.java    From development with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testAuthenticateAdministrator_SSO() throws Throwable {
    // given
    Map<String, String> settings = getProxySettingsForMode("SAML_SP");
    VOUserDetails admin = createVOUserDetails(1000, "admin", "org");
    admin.setUserRoles(
            Collections.singleton(UserRoleType.ORGANIZATION_ADMIN));

    Mockito.doReturn(admin).when(besDAO).getUserDetails(
            Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class),
            Matchers.anyString());
    Mockito.doReturn(new PasswordAuthentication("nobody", ""))
            .when(configService).getWebServiceAuthentication(
                    Matchers.any(ServiceInstance.class), Matchers.anyMap());
    Mockito.doReturn(settings).when(configService)
            .getAllProxyConfigurationSettings();

    // when
    authService.authenticateAdministrator(
            new PasswordAuthentication(admin.getUserId(), "admin123"));

    // then
    Mockito.verify(besDAO, Mockito.times(0)).getUser(
            Matchers.any(ServiceInstance.class),
            Matchers.any(VOUser.class));
}
 
Example #28
Source File: ByteCodeTest.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * For test coverage mostly .. not that useful.
 */
@Test
public void probeByteCodeDebug() {
    PrintStream sysOut = mock(PrintStream.class);

    System.out.println("Sysout hijack!");
    PrintStream oldPrintStream = System.out;

    try {
        System.setOut(sysOut);

        InvokeInstruction ins = mock(InvokeInstruction.class);
        ConstantPoolGen cpg = mock(ConstantPoolGen.class);

        when(ins.getClassName(Matchers.<ConstantPoolGen>any())).thenReturn("ClassTest");
        when(ins.getMethodName(Matchers.<ConstantPoolGen>any())).thenReturn("method");
        when(ins.getSignature(Matchers.<ConstantPoolGen>any())).thenReturn("(Lsignature)Lblah");

        //Print invocation
        ByteCode.printOpCode(ins, cpg);

        verify(sysOut, atLeastOnce()).println(contains("ClassTest.method"));
    } finally {
        System.setOut(oldPrintStream);
        System.out.println("Sysout is back!");
    }

}
 
Example #29
Source File: ExternalMeasureOperatorImplTest.java    From griffin with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateForSuccess() {
    ExternalMeasure measure = createExternalMeasure("view_item_hourly");
    measure.setId(1L);
    given(measureRepo.findOne(1L)).willReturn(measure);
    given(measureRepo.save(Matchers.any(ExternalMeasure.class)))
            .willReturn(measure);

    operator.create(measure);
    verify(measureRepo, times(1)).save(
            Matchers.any(ExternalMeasure.class));
}
 
Example #30
Source File: SendMailInputTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
/**
 * Test extractHeaderNamesAndValues method for invalid inputs.
 *
 * @throws Exception
 */
@Test
public void testExtractHeaderNamesAndValueForInvalidValues() throws Exception {
    exception.expect(Exception.class);
    inputBuilder.extractHeaderNamesAndValues(HEADERS_WITH_MISSING_COLUMNDELIMITER,
            DEFAULT_ROW_DELIMITER, DEFAULT_COLUMN_DELIMITER);
    verify(inputBuilderSpy).validateRow(Matchers.<String>any(), Matchers.<String>any(), Matchers.anyInt());
}