@Test
  public void testAddStatefulEventGenerator() {
    @Stateful
    final class Generator implements StatefulEventGenerator {
      @Override
      public Event poll() {
        return null;
      }
    }

    Generator generator = new Generator();
    builder.add(generator);

    ArgumentCaptor<EventSource> argument = ArgumentCaptor.forClass(EventSource.class);
    verify(process).addEventSource(argument.capture());

    EventSource addedSource = argument.getValue();
    assertNotNull(addedSource);
    assertTrue(addedSource instanceof TimewarpEventSourceAdapter);

    verifyNoMoreInteractions(process);

    // We know the generator and the source but don't have the adapter.
    // So we simply check that the generator and the source got registered
    // and require 3 calls overall.
    verify(service).register(generator);
    verify(service).register(addedSource);
    verify(service, times(3)).register(any());
    verifyNoMoreInteractions(service);
  }
Exemplo n.º 2
0
  @Test
  public void shouldCantUnbombOnBoard() {
    shouldBoardWith(new Sapper(1, 1));

    assertBoard("☼☼☼☼☼\n" + "☼   ☼\n" + "☼   ☼\n" + "☼☺  ☼\n" + "☼☼☼☼☼\n");

    unbombLeft();
    verifyNoMoreInteractions(listener);

    assertBoard("☼☼☼☼☼\n" + "☼   ☼\n" + "☼   ☼\n" + "☼☺  ☼\n" + "☼☼☼☼☼\n");

    unbombDown();
    verifyNoMoreInteractions(listener);

    assertBoard("☼☼☼☼☼\n" + "☼   ☼\n" + "☼   ☼\n" + "☼☺  ☼\n" + "☼☼☼☼☼\n");

    moveRight();
    moveRight();
    reset(listener);

    unbombRight();
    verifyNoMoreInteractions(listener);

    assertBoard("☼☼☼☼☼\n" + "☼   ☼\n" + "☼   ☼\n" + "☼  ☺☼\n" + "☼☼☼☼☼\n");

    moveUp();
    moveUp();
    reset(listener);

    unbombUp();
    verifyNoMoreInteractions(listener);

    assertBoard("☼☼☼☼☼\n" + "☼  ☺☼\n" + "☼   ☼\n" + "☼   ☼\n" + "☼☼☼☼☼\n");
  }
  @Test
  public void testAddProcess() {
    final class Process implements DiscreteEventProcess {
      @Override
      public void dispatchEvent(Event e) {}

      @Override
      public void offer(Event event) {}

      @Override
      public Event peek(long currentSimtime) {
        return null;
      }

      @Override
      public void remove(Event event) {}
    }

    Process dummy = new Process();
    builder.add(dummy);

    verify(process).addEventSource(dummy);
    verify(process).addEventSink(dummy);
    verify(process).addEventDispatcher(dummy);
    verifyNoMoreInteractions(process);

    verify(service).register(dummy);
    verifyNoMoreInteractions(service);
  }
  /**
   * Verify that a stateful but not state aware source is wrapped into a TimewarpEventSourceAdapter
   * before it is added to the process.
   */
  @Test
  public void testAddStatefulSource() {
    // We cannot mock here because we'd loose annotations
    @Stateful
    final class Source implements EventSource {
      @Override
      public Event peek(long currentSimtime) {
        return null;
      }

      @Override
      public void remove(Event event) {}
    }

    Source source = new Source();
    builder.add(source);

    ArgumentCaptor<EventSource> argument = ArgumentCaptor.forClass(EventSource.class);
    verify(process).addEventSource(argument.capture());

    EventSource addedSource = argument.getValue();
    assertNotNull(addedSource);
    assertTrue(addedSource instanceof TimewarpEventSourceAdapter);

    verifyNoMoreInteractions(process);

    verify(service).register(source);
    verify(service).register(addedSource);
    verifyNoMoreInteractions(service);
  }
  @Test
  public void testAddEventSinkWithFilter() {
    final class Sink implements EventSink {
      @Override
      public void offer(Event event) {}
    }

    final class Condition implements EventCondition {
      @Override
      public boolean match(Event e) {
        return false;
      }
    }

    Sink sink = new Sink();
    Condition condition = new Condition();
    builder.add(sink, condition);

    ArgumentCaptor<EventSink> argument = ArgumentCaptor.forClass(EventSink.class);
    verify(process).addEventSink(argument.capture());

    EventSink addedSink = argument.getValue();
    assertNotNull(addedSink);
    assertTrue(addedSink instanceof FilteredEventSink);

    verifyNoMoreInteractions(process);

    verify(service).register(sink);
    verify(service).register(addedSink);
    verifyNoMoreInteractions(service);
  }
  @Test
  public void testGroupCollapseFilterFieldAllFiltered() throws IOException {
    mockResponse(true);
    when(rb.grouping()).thenReturn(true);
    when(params.getBool(GroupCollapseParams.GROUP_COLLAPSE, false)).thenReturn(true);
    when(params.get(GroupCollapseParams.GROUP_COLLAPSE_FL))
        .thenReturn("price,discount,isCloseout,color,colorFamily");
    when(params.get(GroupCollapseParams.GROUP_COLLAPSE_FF)).thenReturn(FIELD_CLOSEOUT);
    component.process(rb);
    verify(rb).grouping();
    verify(rb).getGroupingSpec();
    verify(params).getBool(GroupCollapseParams.GROUP_COLLAPSE, false);
    verify(params).get(GroupCollapseParams.GROUP_COLLAPSE_FL);
    verify(params).get(GroupCollapseParams.GROUP_COLLAPSE_FF);
    verify(params).getParams(GroupCollapseParams.GROUP_COLLAPSE_FQ);
    verifyNoMoreInteractions(rb);
    verifyNoMoreInteractions(params);

    ArgumentCaptor<NamedList> namedListArgument = ArgumentCaptor.forClass(NamedList.class);
    verify(rsp).add(eq("groups_summary"), namedListArgument.capture());

    NamedList groupsSummary = namedListArgument.getValue();
    NamedList productId = (NamedList) groupsSummary.get("productId");
    assertNotNull(productId);
    Set<String> colorFamilies = new HashSet<String>();
    colorFamilies.add("RedColorFamily");
    colorFamilies.add("BlackColorFamily");
    verifyProductSummary(
        (NamedList) productId.get("product1"), 80.0f, 100.0f, 0.0f, 20.0f, 2, colorFamilies);
    colorFamilies = new HashSet<String>();
    colorFamilies.add("OrangeColorFamily");
    colorFamilies.add("BrownColorFamily");
    verifyProductSummary(
        (NamedList) productId.get("product2"), 60.0f, 80.0f, 20.0f, 40.0f, 2, colorFamilies);
  }
  @Test
  public void testAddStatelessEventGenerator() {
    final class Generator implements StatelessEventGenerator {
      @Override
      public Event peek(long simtime) {
        return null;
      }
    }

    Generator generator = new Generator();
    builder.add(generator);

    ArgumentCaptor<EventSource> argument = ArgumentCaptor.forClass(EventSource.class);
    verify(process).addEventSource(argument.capture());

    EventSource addedSource = argument.getValue();
    assertNotNull(addedSource);
    assertTrue(addedSource instanceof EventSourceStatelessGeneratorAdapter);

    verifyNoMoreInteractions(process);

    verify(service).register(generator);
    verify(service).register(addedSource);
    verifyNoMoreInteractions(service);
  }
 @Test
 public void testNoGroupCollapse() throws IOException {
   when(rb.grouping()).thenReturn(true);
   when(params.getBool(GroupCollapseParams.GROUP_COLLAPSE, false)).thenReturn(false);
   component.process(rb);
   verify(rb).grouping();
   verify(params).getBool(GroupCollapseParams.GROUP_COLLAPSE, false);
   verifyNoMoreInteractions(rb);
   verifyNoMoreInteractions(params);
 }
  @Test
  public void testAddDispatcher() {
    final class Dispatcher implements EventDispatcher {
      @Override
      public void dispatchEvent(Event e) {}
    }

    Dispatcher dispatcher = new Dispatcher();
    builder.add(dispatcher);
    verify(process).addEventDispatcher(dispatcher);
    verifyNoMoreInteractions(process);

    verify(service).register(dispatcher);
    verifyNoMoreInteractions(service);
  }
  @Test
  public void testAddStatefulProcess() {
    @Stateful
    final class Process implements DiscreteEventProcess {
      @Override
      public void dispatchEvent(Event e) {}

      @Override
      public void offer(Event event) {}

      @Override
      public Event peek(long currentSimtime) {
        return null;
      }

      @Override
      public void remove(Event event) {}
    }

    Process dummy = new Process();
    builder.add(dummy);

    verify(service).register(dummy);

    // source
    ArgumentCaptor<EventSource> sourceArgument = ArgumentCaptor.forClass(EventSource.class);
    verify(process).addEventSource(sourceArgument.capture());

    EventSource addedSource = sourceArgument.getValue();
    assertNotNull(addedSource);
    assertTrue(addedSource instanceof TimewarpEventSourceAdapter);
    verify(service).register(addedSource);

    // sink
    ArgumentCaptor<EventSink> sinkArgument = ArgumentCaptor.forClass(EventSink.class);
    verify(process).addEventSink(sinkArgument.capture());

    EventSink addedSink = sinkArgument.getValue();
    assertNotNull(addedSink);
    assertTrue(addedSink instanceof TimewarpEventSinkAdapter);
    verify(service).register(addedSink);

    // dispatcher
    verify(process).addEventDispatcher(dummy);

    verifyNoMoreInteractions(process);
    verifyNoMoreInteractions(service);
  }
  @Test
  public void testAddEventSink() {
    final class Sink implements EventSink {
      @Override
      public void offer(Event event) {}
    }

    Sink sink = new Sink();
    builder.add(sink);

    verify(process).addEventSink(sink);
    verifyNoMoreInteractions(process);

    verify(service).register(sink);
    verifyNoMoreInteractions(service);
  }
Exemplo n.º 12
0
    @Test
    public void testUnsubscribeAfterTake() {
      Subscription s = mock(Subscription.class);
      TestObservable w = new TestObservable(s, "one", "two", "three");

      @SuppressWarnings("unchecked")
      Observer<String> aObserver = mock(Observer.class);
      Observable<String> take = Observable.create(take(w, 1));
      take.subscribe(aObserver);

      // wait for the Observable to complete
      try {
        w.t.join();
      } catch (Throwable e) {
        e.printStackTrace();
        fail(e.getMessage());
      }

      System.out.println("TestObservable thread finished");
      verify(aObserver, times(1)).onNext("one");
      verify(aObserver, never()).onNext("two");
      verify(aObserver, never()).onNext("three");
      verify(aObserver, times(1)).onCompleted();
      verify(s, times(1)).unsubscribe();
      verifyNoMoreInteractions(aObserver);
    }
Exemplo n.º 13
0
    @Test
    public void testTakeZeroDoesntLeakError() {
      final AtomicBoolean subscribed = new AtomicBoolean(false);
      final AtomicBoolean unSubscribed = new AtomicBoolean(false);
      Observable<String> source =
          Observable.create(
              new Func1<Observer<String>, Subscription>() {
                @Override
                public Subscription call(Observer<String> observer) {
                  subscribed.set(true);
                  observer.onError(new Throwable("test failed"));
                  return new Subscription() {
                    @Override
                    public void unsubscribe() {
                      unSubscribed.set(true);
                    }
                  };
                }
              });

      @SuppressWarnings("unchecked")
      Observer<String> aObserver = mock(Observer.class);

      Observable.create(take(source, 0)).subscribe(aObserver);
      assertTrue("source subscribed", subscribed.get());
      assertTrue("source unsubscribed", unSubscribed.get());

      verify(aObserver, never()).onNext(anyString());
      // even though onError is called we take(0) so shouldn't see it
      verify(aObserver, never()).onError(any(Throwable.class));
      verify(aObserver, times(1)).onCompleted();
      verifyNoMoreInteractions(aObserver);
    }
Exemplo n.º 14
0
  @Test
  public void testGetAll() {

    when(genreDAO.getAll()).thenReturn(new ArrayList<Genre>());
    ArrayList<GenreDTO> list = new ArrayList<>();
    assertEquals(list, genreService.getAll());

    GenreDTO expResult1 = new GenreDTO("Heavy metal");
    GenreDTO expResult2 = new GenreDTO("Doom metal");
    GenreDTO expResult3 = new GenreDTO("Death metal");

    expResult1.setId(1l);
    expResult2.setId(2l);
    expResult3.setId(3l);

    list.add(expResult1);
    list.add(expResult2);
    list.add(expResult3);

    ArrayList<Genre> daoList = new ArrayList<>();
    daoList.add(DTOMapper.toEntity(expResult1));
    daoList.add(DTOMapper.toEntity(expResult2));
    daoList.add(DTOMapper.toEntity(expResult3));
    when(genreDAO.getAll()).thenReturn(daoList);

    assertEquals(
        DTOMapper.genresListToEntity(list), DTOMapper.genresListToEntity(genreService.getAll()));
    verify(genreDAO, times(2)).getAll();

    verifyNoMoreInteractions(genreDAO);
  }
  @Test
  public void handleMessageToClientConnectAck() {

    StompHeaderAccessor connectHeaders = StompHeaderAccessor.create(StompCommand.CONNECT);
    connectHeaders.setHeartbeat(10000, 10000);
    connectHeaders.setNativeHeader(StompHeaderAccessor.STOMP_ACCEPT_VERSION_HEADER, "1.0,1.1");
    Message<?> connectMessage =
        MessageBuilder.withPayload(new byte[0]).setHeaders(connectHeaders).build();

    SimpMessageHeaderAccessor connectAckHeaders =
        SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
    connectAckHeaders.setHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER, connectMessage);
    Message<byte[]> connectAckMessage =
        MessageBuilder.withPayload(new byte[0]).setHeaders(connectAckHeaders).build();

    this.protocolHandler.handleMessageToClient(this.session, connectAckMessage);

    verifyNoMoreInteractions(this.channel);

    // Check CONNECTED reply

    assertEquals(1, this.session.getSentMessages().size());
    TextMessage textMessage = (TextMessage) this.session.getSentMessages().get(0);
    Message<?> message =
        new StompDecoder().decode(ByteBuffer.wrap(textMessage.getPayload().getBytes()));
    StompHeaderAccessor replyHeaders = StompHeaderAccessor.wrap(message);

    assertEquals(StompCommand.CONNECTED, replyHeaders.getCommand());
    assertEquals("1.1", replyHeaders.getVersion());
    assertArrayEquals(new long[] {0, 0}, replyHeaders.getHeartbeat());
    assertEquals("joe", replyHeaders.getNativeHeader("user-name").get(0));
  }
Exemplo n.º 16
0
  @Test
  public void processPathWithQuotasByQTVH() throws Exception {
    Path path = new Path("mockfs:/test");

    when(mockFs.getFileStatus(eq(path))).thenReturn(fileStat);

    PrintStream out = mock(PrintStream.class);

    Count count = new Count();
    count.out = out;

    LinkedList<String> options = new LinkedList<String>();
    options.add("-q");
    options.add("-t");
    options.add("-v");
    options.add("-h");
    options.add("dummy");
    count.processOptions(options);
    String withStorageTypeHeader =
        // <----13---> <-------17------>
        "    SSD_QUOTA     REM_SSD_QUOTA "
            + "   DISK_QUOTA    REM_DISK_QUOTA "
            + "ARCHIVE_QUOTA REM_ARCHIVE_QUOTA "
            + "PATHNAME";
    verify(out).println(withStorageTypeHeader);
    verifyNoMoreInteractions(out);
  }
  @Test
  public void compareAndUpdateSportteryAllBeans_UpdateOneBean_HistoryRepositoryShouldBeCalled() {

    List<SportteryAllEntity> list = new ArrayList<>();
    SportteryAllEntity sportteryAllEntity = new SportteryAllEntity();
    sportteryAllEntity.setMatchCode("1001");
    list.add(sportteryAllEntity);
    when(sportteryAllRepository.findByMatchCode(isA(String.class)))
        .thenReturn(new SportteryAllEntity());
    sportteryDao.compareAndUpdateSportteryAllBeans(list);
    verify(sportteryAllRepository).findByMatchCode(isA(String.class));
    verify(sportteryAllRepository).save(isA(SportteryAllEntity.class));
    verify(sportteryAllHistoryRepository).save(isA(SportteryAllHistoryEntity.class));
    verifyNoMoreInteractions(sportteryAllRepository);
    verifyNoMoreInteractions(sportteryAllHistoryRepository);
  }
Exemplo n.º 18
0
  @Test
  public void processPathWithQuotasByMultipleStorageTypesContent() throws Exception {
    Path path = new Path("mockfs:/test");

    when(mockFs.getFileStatus(eq(path))).thenReturn(fileStat);
    PathData pathData = new PathData(path.toString(), conf);

    PrintStream out = mock(PrintStream.class);

    Count count = new Count();
    count.out = out;

    LinkedList<String> options = new LinkedList<String>();
    options.add("-q");
    options.add("-t");
    options.add("SSD,DISK");
    options.add("dummy");
    count.processOptions(options);
    count.processPath(pathData);
    String withStorageType =
        BYTES
            + StorageType.SSD.toString()
            + " "
            + StorageType.DISK.toString()
            + " "
            + pathData.toString();
    verify(out).println(withStorageType);
    verifyNoMoreInteractions(out);
  }
Exemplo n.º 19
0
 @Test
 public void testFlush() {
   TamedEnderman e = factory.getNewOne("main()");
   factory.flush();
   verify(database).save(e.getDatabaseEntity());
   verifyNoMoreInteractions(database);
 }
  @Test
  public void testValidProduct() {
    boolean result = _productValidator.isValid(M_product);

    assertEquals(true, result);
    verifyNoMoreInteractions(S_logger);
  }
Exemplo n.º 21
0
  /** When BACKUP_PACKET is received, updates are written to store */
  @Test
  public void whenBACKUP_PACKETThenWriteUpdates() throws Exception {
    final ByteBuffer buffer1 = randomBuffer(50);
    final ByteBuffer buffer2 = randomBuffer(50);
    final ByteBuffer buffer3 = randomBuffer(50);

    final BACKUP_PACKET bp =
        Message.BACKUP_PACKET(
            7,
            Arrays.asList(
                Message.BACKUP(id(1), 4, buffer1),
                Message.BACKUP(id(2), 5, buffer2),
                Message.BACKUP(id(3), 6, buffer3)));
    bp.setNode(sh(10));
    mm.receive(bp);

    InOrder inOrder = inOrder(store, comm);
    inOrder.verify(store).beginTransaction();
    inOrder
        .verify(store)
        .write(eq(id(1)), eq(sh(10)), eq(4L), eq(Persistables.toByteArray(buffer1)), anyObject());
    inOrder
        .verify(store)
        .write(eq(id(2)), eq(sh(10)), eq(5L), eq(Persistables.toByteArray(buffer2)), anyObject());
    inOrder
        .verify(store)
        .write(eq(id(3)), eq(sh(10)), eq(6L), eq(Persistables.toByteArray(buffer3)), anyObject());
    inOrder.verify(store).commit(anyObject());
    inOrder.verify(comm).send(argThat(equalTo(Message.BACKUP_PACKETACK(bp))));
    verify(monitor).addTransaction(3);
    verifyNoMoreInteractions(monitor);
  }
 @Test
 public void testNoGrouping() throws IOException {
   when(rb.grouping()).thenReturn(false);
   component.process(rb);
   verify(rb).grouping();
   verifyNoMoreInteractions(rb);
 }
Exemplo n.º 23
0
  @Test
  public void rejectsABadTriple() throws IOException, InterruptedException {
    Context mockContext = mock(Context.class);
    pse3mapper.map(
        new LongWritable(24562L),
        new Text("<http://example.com/A>\t<http://example.com/B>\t\"2001-06\"^^xsd:datetime."),
        mockContext);

    verify(pse3mapper.rejected)
        .write(
            new Text("<http://example.com/A>"),
            new Text("<http://example.com/B>\t\"2001-06\"^^xsd:datetime\t."),
            mockContext);

    verifyNoMoreInteractions(pse3mapper.accepted);
    verifyNoMoreInteractions(pse3mapper.rejected);
  }
  @Test
  public void shouldNotLogVoidReturnValue() {
    returnVoidClass.foo();

    verify(log, atLeast(0)).isDebugEnabled();
    verify(log).debug("foo", NO_ARGS);
    verifyNoMoreInteractions(log);
  }
Exemplo n.º 25
0
  @Test
  public void shouldDeliverUpdatesThatOccurDuringPopulationToPopulator() throws Exception {
    // given
    when(populator.newPopulatingUpdater()).thenReturn(updater);

    CountDownLatch latch = new CountDownLatch(1);
    doAnswer(afterAwaiting(latch)).when(populator).add(anyLong(), any());

    IndexingService indexingService =
        newIndexingServiceWithMockedDependencies(populator, accessor, withData(add(1, "value1")));

    life.start();

    // when
    indexingService.createIndex(indexRule(0, labelId, propertyKeyId, PROVIDER_DESCRIPTOR));
    IndexProxy proxy = indexingService.getProxyForRule(0);
    assertEquals(InternalIndexState.POPULATING, proxy.getState());

    try (IndexUpdater updater = proxy.newUpdater(IndexUpdateMode.ONLINE)) {
      updater.process(add(2, "value2"));
    }

    latch.countDown();

    verify(populator, timeout(1000)).close(true);

    // then
    assertEquals(InternalIndexState.ONLINE, proxy.getState());
    InOrder order = inOrder(populator, accessor, updater);
    order.verify(populator).create();
    order.verify(populator).add(1, "value1");

    // this is invoked from indexAllNodes(),
    // empty because the id we added (2) is bigger than the one we indexed (1)
    order.verify(populator).newPopulatingUpdater();
    order.verify(updater).close();

    order.verify(populator).newPopulatingUpdater();
    order.verify(updater).process(add(2, "value2"));
    order.verify(updater).close();

    order.verify(populator).close(true);
    verifyNoMoreInteractions(updater);
    verifyNoMoreInteractions(populator);
    verifyZeroInteractions(accessor);
  }
  @Test
  public void whenWithAspectMultipleTimesThenShouldNotResetAndShouldRegisterEveryAspect() {
    context.withAspect(AnAspect.class);
    context.withAspect(OtherAspect.class);

    verify(weaverMock, times(2)).registerAspect((Class<?>) anyObject());
    verifyNoMoreInteractions(weaverMock);
  }
  @Test
  public void testSubscribe() {
    testSubject.subscribe();

    verify(mockBus).subscribe(Long.class, testSubject);
    verify(mockBus).subscribe(String.class, testSubject);
    verify(mockBus).subscribe(HashSet.class, testSubject);
    verify(mockBus).subscribe(ArrayList.class, testSubject);
    verifyNoMoreInteractions(mockBus);
  }
Exemplo n.º 28
0
  /** Test of doFinalize method, of class ObjectFinalizer. */
  @Test
  public void testDoFinalize() {
    Runnable task = mock(Runnable.class);

    ObjectFinalizer finalizer = new ObjectFinalizer(task, "DESCRIPTION");
    assertTrue(finalizer.doFinalize());

    verify(task).run();
    verifyNoMoreInteractions(task);
  }
Exemplo n.º 29
0
  @Test
  public void acceptsAGoodTriple() throws IOException, InterruptedException {
    Context mockContext = mock(Context.class);
    pse3mapper.map(
        new LongWritable(944L),
        new Text("<http://example.com/A>\t<http://example.com/B>\t<http://example.com/C>."),
        mockContext);

    verify(pse3mapper.accepted)
        .write(
            new WritableTriple(
                Node_URI.createURI("http://example.com/A"),
                Node_URI.createURI("http://example.com/B"),
                Node_URI.createURI("http://example.com/C")),
            new LongWritable(1),
            mockContext);
    verifyNoMoreInteractions(pse3mapper.accepted);
    verifyNoMoreInteractions(pse3mapper.rejected);
  }
 @Test
 public void removeGroupHandlesNoResultOnRead()
     throws MalformedURLException, InstantiationException, IllegalAccessException, SQLException {
   String query = getRemoveGroupReadQuery();
   when(sql.sqlQuery(query)).thenReturn(result);
   when(result.next()).thenReturn(false);
   webGroupDao.removeUserFromGroup(USER_ID, GROUP_ID);
   verify(sql).sqlQuery(query);
   verifyNoMoreInteractions(sql);
 }