@Test
  public void testNoneExtensionMatchingSuccess() {
    // initialize
    expect(mainHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("unknown")))
        .andReturn(null)
        .anyTimes();
    expect(mainHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("unknown2")))
        .andReturn(null)
        .anyTimes();
    replay(mainHandshakerMock);

    expect(fallbackHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("unknown")))
        .andReturn(null)
        .anyTimes();
    expect(fallbackHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("unknown2")))
        .andReturn(null)
        .anyTimes();
    replay(fallbackHandshakerMock);

    // execute
    EmbeddedChannel ch =
        new EmbeddedChannel(
            new WebSocketServerExtensionHandler(mainHandshakerMock, fallbackHandshakerMock));

    HttpRequest req = newUpgradeRequest("unknown, unknown2");
    ch.writeInbound(req);

    HttpResponse res = newUpgradeResponse(null);
    ch.writeOutbound(res);

    HttpResponse res2 = ch.readOutbound();

    // test
    assertFalse(res2.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));
  }
  @Test
  public void testCompatibleExtensionTogetherSuccess() {
    // initialize
    expect(mainHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("main")))
        .andReturn(mainExtensionMock)
        .anyTimes();
    expect(mainHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("fallback")))
        .andReturn(null)
        .anyTimes();
    replay(mainHandshakerMock);

    expect(fallbackHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("fallback")))
        .andReturn(fallbackExtensionMock)
        .anyTimes();
    expect(fallbackHandshakerMock.handshakeExtension(webSocketExtensionDataEqual("main")))
        .andReturn(null)
        .anyTimes();
    replay(fallbackHandshakerMock);

    expect(mainExtensionMock.rsv()).andReturn(WebSocketExtension.RSV1).anyTimes();
    expect(mainExtensionMock.newReponseData())
        .andReturn(new WebSocketExtensionData("main", Collections.<String, String>emptyMap()))
        .once();
    expect(mainExtensionMock.newExtensionEncoder()).andReturn(new DummyEncoder()).once();
    expect(mainExtensionMock.newExtensionDecoder()).andReturn(new DummyDecoder()).once();
    replay(mainExtensionMock);

    expect(fallbackExtensionMock.rsv()).andReturn(WebSocketExtension.RSV2).anyTimes();
    expect(fallbackExtensionMock.newReponseData())
        .andReturn(new WebSocketExtensionData("fallback", Collections.<String, String>emptyMap()))
        .once();
    expect(fallbackExtensionMock.newExtensionEncoder()).andReturn(new Dummy2Encoder()).once();
    expect(fallbackExtensionMock.newExtensionDecoder()).andReturn(new Dummy2Decoder()).once();
    replay(fallbackExtensionMock);

    // execute
    EmbeddedChannel ch =
        new EmbeddedChannel(
            new WebSocketServerExtensionHandler(mainHandshakerMock, fallbackHandshakerMock));

    HttpRequest req = newUpgradeRequest("main, fallback");
    ch.writeInbound(req);

    HttpResponse res = newUpgradeResponse(null);
    ch.writeOutbound(res);

    HttpResponse res2 = ch.readOutbound();
    List<WebSocketExtensionData> resExts =
        WebSocketExtensionUtil.extractExtensions(
            res2.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS));

    // test
    assertEquals(2, resExts.size());
    assertEquals("main", resExts.get(0).name());
    assertEquals("fallback", resExts.get(1).name());
    assertNotNull(ch.pipeline().get(DummyDecoder.class));
    assertNotNull(ch.pipeline().get(DummyEncoder.class));
    assertNotNull(ch.pipeline().get(Dummy2Decoder.class));
    assertNotNull(ch.pipeline().get(Dummy2Encoder.class));
  }
  @Test
  public void accepts() throws DatabaseException {
    ArrayList<RanChangeSet> ranChanges = new ArrayList<RanChangeSet>();
    ranChanges.add(
        new RanChangeSet(
            "path/changelog", "1", "testAuthor", CheckSum.parse("12345"), new Date(), null, null));
    ranChanges.add(
        new RanChangeSet(
            "path/changelog", "2", "testAuthor", CheckSum.parse("12345"), new Date(), null, null));

    Database database = createMock(Database.class);
    expect(database.getRanChangeSetList()).andReturn(ranChanges);
    expect(database.getDatabaseChangeLogTableName()).andReturn("DATABASECHANGELOG").anyTimes();
    expect(database.getDefaultSchemaName()).andReturn(null).anyTimes();

    Executor template = createMock(Executor.class);
    expect(template.update(isA(UpdateStatement.class))).andReturn(1).anyTimes();
    //        template.comment("Lock Database");
    //        expectLastCall();

    replay(database);
    replay(template);
    ExecutorService.getInstance().setExecutor(database, template);

    ShouldRunChangeSetFilter filter = new ShouldRunChangeSetFilter(database);

    // everything same
    assertFalse(
        filter.accepts(
            new ChangeSet("1", "testAuthor", false, false, "path/changelog", null, null)));

    // alwaysRun
    assertTrue(
        filter.accepts(
            new ChangeSet("1", "testAuthor", true, false, "path/changelog", null, null)));

    // run on change
    assertTrue(
        filter.accepts(
            new ChangeSet("1", "testAuthor", false, true, "path/changelog", null, null)));

    // different id
    assertTrue(
        filter.accepts(
            new ChangeSet("3", "testAuthor", false, false, "path/changelog", null, null)));

    // different author
    assertTrue(
        filter.accepts(
            new ChangeSet("1", "otherAuthor", false, false, "path/changelog", null, null)));

    // different path
    assertTrue(
        filter.accepts(
            new ChangeSet("1", "testAuthor", false, false, "other/changelog", null, null)));
  }
  @Test
  public void testGetQueryNoCache() throws Exception {
    final PermissionsFilterCache cache = mockController.getMock(PermissionsFilterCache.class);
    final BooleanQuery generatedQuery = new BooleanQuery();

    org.easymock.EasyMock.expect(cache.getQuery(theUser)).andReturn(null);

    cache.storeQuery(generatedQuery, theUser);
    org.easymock.EasyMock.expectLastCall();

    replay();
    final PermissionQueryFactory permissionQueryFactory =
        new PermissionQueryFactory() {
          public Query getQuery(com.atlassian.crowd.embedded.api.User searcher, int permissionId) {
            assertSame(theUser, searcher);
            assertEquals(Permissions.BROWSE, permissionId);
            return generatedQuery;
          }
        };

    final PermissionsFilterGeneratorImpl generator =
        new PermissionsFilterGeneratorImpl(permissionQueryFactory) {
          @Override
          PermissionsFilterCache getCache() {
            return cache;
          }
        };

    final Query result = generator.getQuery(theUser);

    assertSame(generatedQuery, result);
  }
  @Before
  public void setUp() throws Exception {
    clusterCommunicator = createNiceMock(ClusterCommunicationService.class);
    clusterCommunicator.addSubscriber(
        anyObject(MessageSubject.class),
        anyObject(ClusterMessageHandler.class),
        anyObject(ExecutorService.class));
    expectLastCall().anyTimes();
    replay(clusterCommunicator);
    ClusterService clusterService = new TestClusterService();

    testGossipDeviceStore =
        new TestGossipDeviceStore(deviceClockService, clusterService, clusterCommunicator);
    testGossipDeviceStore.mastershipService = new TestMastershipService();

    TestDatabaseManager testDatabaseManager = new TestDatabaseManager();
    testDatabaseManager.init(clusterService, clusterCommunicator);
    testGossipDeviceStore.storageService = testDatabaseManager;
    testGossipDeviceStore.deviceClockService = deviceClockService;

    gossipDeviceStore = testGossipDeviceStore;
    gossipDeviceStore.activate();
    deviceStore = gossipDeviceStore;
    verify(clusterCommunicator);
    reset(clusterCommunicator);
  }
  @Test
  public void testGetSearchClauseOneProjectIsFlag() throws Exception {
    final CustomFieldParamsImpl customFieldParams = new CustomFieldParamsImpl();
    customFieldParams.addValue(Collections.singleton("123"));
    final Map<String, Object> map =
        MapBuilder.<String, Object>newBuilder()
            .add(urlParameterName, customFieldParams)
            .add(
                SystemSearchConstants.forProject().getUrlParameter(),
                Collections.singletonList("-1"))
            .toMap();
    FieldValuesHolder values = new FieldValuesHolderImpl(map);
    final AtomicBoolean specialCalled = new AtomicBoolean(false);

    final IndexedInputHelper helper =
        new DefaultIndexedInputHelper<Version>(
            indexInfoResolver,
            operandResolver,
            fieldFlagOperandRegistry,
            searchContextVisibilityChecker) {
          @Override
          public Clause getClauseForNavigatorValues(final String clauseName, final Set values) {
            return null;
          }
        };

    transformer =
        new VersionCustomFieldSearchInputTransformer(
            urlParameterName,
            clauseNames,
            customField,
            indexInfoResolver,
            operandResolver,
            fieldFlagOperandRegistry,
            searchContextVisibilityChecker,
            versionResolver,
            customFieldInputHelper,
            versionManager) {
          @Override
          protected DefaultIndexedInputHelper getDefaultIndexedInputHelper() {
            throw new UnsupportedOperationException(
                "Should not have called through to the special indexed input helper");
          }

          @Override
          protected IndexedInputHelper getIndexedInputHelper() {
            specialCalled.set(true);
            return helper;
          }

          @Override
          protected String getClauseName(final User searcher, final ClauseNames clauseNames) {
            return primaryClauseName;
          }
        };
    replay();

    transformer.getSearchClause(theUser, values);
    assertTrue(specialCalled.get());
  }
  @Test
  public void testGetQueryCached() throws Exception {
    final PermissionsFilterCache cache = mockController.getMock(PermissionsFilterCache.class);
    final BooleanQuery cachedQuery = new BooleanQuery();

    org.easymock.EasyMock.expect(cache.getQuery(theUser)).andReturn(cachedQuery);

    replay();

    final PermissionQueryFactory permissionQueryFactory =
        new PermissionQueryFactory() {
          public Query getQuery(com.atlassian.crowd.embedded.api.User searcher, int permissionId) {
            fail("Should not be called as query was cached");
            return null;
          }
        };

    final PermissionsFilterGeneratorImpl generator =
        new PermissionsFilterGeneratorImpl(permissionQueryFactory) {
          @Override
          PermissionsFilterCache getCache() {
            return cache;
          }
        };

    final Query result = generator.getQuery(theUser);

    assertSame(cachedQuery, result);
  }
  @Test
  public void testaaKäsittelijäWithEasyMockHinnoittelijaOver100() {
    float alkuSaldo = 100.0f;
    float listaHinta = 300.0f;
    float alennus = 20.0f;
    float loppuSaldo = alkuSaldo - (listaHinta * (1 - alennus / 100));

    Asiakas asiakas = new Asiakas(alkuSaldo);
    Tuote tuote = new Tuote("TDD in Action", listaHinta);
    Hinnoittelija hinnoittelija = createMock(Hinnoittelija.class);

    hinnoittelija.aloita();
    expect(hinnoittelija.getAlennusProsentti(asiakas, tuote)).andReturn(alennus);
    expectLastCall().times(2);
    hinnoittelija.setAlennusProsentti(asiakas, alennus + 5);
    hinnoittelija.lopeta();
    replay(hinnoittelija);

    TilaustenKäsittely kasittelija = new TilaustenKäsittely();
    kasittelija.setHinnoittelija(hinnoittelija);
    kasittelija.käsittele(new Tilaus(asiakas, tuote));

    assertEquals("Price over 100", loppuSaldo, asiakas.getSaldo(), 0.001);
    verify(hinnoittelija);
  }
  @Test
  public void resolveArgumentOrdering() throws Exception {
    String name = "testBean";
    Object testBean = new TestBean(name);
    mavContainer.addAttribute(name, testBean);
    mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, testBean);

    Object anotherTestBean = new TestBean();
    mavContainer.addAttribute("anotherTestBean", anotherTestBean);

    StubRequestDataBinder dataBinder = new StubRequestDataBinder(testBean, name);
    WebDataBinderFactory binderFactory = createMock(WebDataBinderFactory.class);
    expect(binderFactory.createBinder(webRequest, testBean, name)).andReturn(dataBinder);
    replay(binderFactory);

    processor.resolveArgument(paramModelAttr, mavContainer, webRequest, binderFactory);

    assertSame(
        "Resolved attribute should be updated to be last in the order",
        testBean,
        mavContainer.getModel().values().toArray()[1]);
    assertSame(
        "BindingResult of resolved attribute should be last in the order",
        dataBinder.getBindingResult(),
        mavContainer.getModel().values().toArray()[2]);
  }
 @Test
 public void testGetUser() {
   expect(dao.load(1)).andReturn(fred);
   replay(dao);
   assertSame(fred, manager.getUser(1));
   verify(dao);
 }
  @Test
  public void testRunnableWrappsRunnable() throws Exception {
    final Object mockChannel = createMock("mockChannel", AbstractAioChannel.class);
    replay(mockChannel);

    final Runnable r =
        new Runnable() {

          @SuppressWarnings("unused")
          @Override
          public void run() {
            Object channel = mockChannel;
            // Noop
          }
        };
    Runnable r2 =
        new Runnable() {

          @SuppressWarnings("unused")
          @Override
          public void run() {
            Runnable runnable = r;
            // Noop
          }
        };
    AioChannelFinder finder = create();
    AbstractAioChannel channel = finder.findChannel(r2);
    assertNotNull(channel);

    AbstractAioChannel channel2 = finder.findChannel(r2);
    assertNotNull(channel2);
    assertSame(channel2, channel);
    verify(mockChannel);
    reset(mockChannel);
  }
  private void invoke(boolean extendToInterfaces) throws NoSuchMethodException, Throwable {
    FilterService fs = createMock(FilterService.class);
    IService service = createMock(IService.class);

    // expect
    int paramValue = 10;
    Object retValue = new Object();
    Method method = IService.class.getDeclaredMethod("test0", int.class);
    expect(fs.invoke(service, extendToInterfaces, method, paramValue)).andReturn(retValue);

    // replay
    replay(service, fs);

    // test
    FilterInterceptor fi = new FilterInterceptor();
    fi.setFilterService(fs);
    fi.setExtendToInterfaces(extendToInterfaces);
    MethodInvocation mi = new TestMethodInvocation(service, method, new Object[] {paramValue});
    Object ret = fi.invoke(mi);

    // check
    verify(service, fs);
    assertNotNull("Result must not be null", ret);
    assertEquals("FilterService must be called", retValue, ret);
  }
Example #13
0
 @Test
 public void testHandleMessagesNoListeners() throws Exception {
   IOFSwitch sw = createMock(IOFSwitch.class);
   expect(sw.getId()).andReturn(DatapathId.NONE).anyTimes();
   replay(sw);
   controller.handleMessage(sw, pi, null);
   verify(sw);
 }
Example #14
0
 @Test
 public void testSaveState() {
   FacesContext context = EasyMock.createMock(FacesContext.class);
   UIInput input = new UIInput();
   replay(context);
   assertNotNull(input.saveState(context));
   verify(context);
 }
Example #15
0
 @Test
 public void testRestoreState() {
   FacesContext context = EasyMock.createMock(FacesContext.class);
   UIInput input = new UIInput();
   replay(context);
   input.restoreState(context, null);
   verify(context);
 }
Example #16
0
  /** Test interaction with OFChannelHandler when the current role is master. */
  @Test
  public void testChannelHandlerMaster() {
    OFSwitchHandshakeHandler h = createMock(OFSwitchHandshakeHandler.class);

    // Reassert the role.
    reset(h);
    h.sendRoleRequestIfNotPending(OFControllerRole.ROLE_MASTER);
    replay(h);
    controller.reassertRole(h, HARole.ACTIVE);
    verify(h);

    // reassert a different role: no-op
    reset(h);
    replay(h);
    controller.reassertRole(h, HARole.STANDBY);
    verify(h);
  }
 @Test
 public void testFindById() {
   Categorie categorie = new Categorie();
   categorieRepository.save(categorie);
   expect(categorieRepository.findById(1l)).andReturn(categorie);
   replay(categorieRepository);
   assertEquals(categorie, categorieRepository.findById(1l));
 }
Example #18
0
 private <T> void resetCommunicatorExpectingNoBroadcast(
     Capture<T> message, Capture<MessageSubject> subject, Capture<Function<T, byte[]>> encoder) {
   message.reset();
   subject.reset();
   encoder.reset();
   reset(clusterCommunicator);
   replay(clusterCommunicator);
 }
Example #19
0
 @Test(expected = NullPointerException.class)
 public void testRestoreState2() {
   FacesContext context = EasyMock.createMock(FacesContext.class);
   UIInput input = new UIInput();
   replay(context);
   input.restoreState(null, null);
   verify(context);
 }
  @Test
  public void shouldLookInClasspathForFiles() {
    ClasspathProvider mockClasspath = createMock(ClasspathProvider.class);
    expect(mockClasspath.classDirectoriesInClasspath()).andReturn(Collections.<File>emptyList());
    replay(mockClasspath);

    new FileChangeDetector().setClasspathProvider(mockClasspath);
    verify(mockClasspath);
  }
Example #21
0
  @Test
  public void testIsErrorEnabled() {
    org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class);
    replay(mock);

    InternalLogger logger = new Log4JLogger(mock);
    assertTrue(logger.isErrorEnabled());
    verify(mock);
  }
Example #22
0
  @Test
  public void testHandleMessagesSlave() throws Exception {
    doSetUp(HARole.STANDBY);
    IOFSwitch sw = createMock(IOFSwitch.class);
    expect(sw.getId()).andReturn(DatapathId.NONE).anyTimes();

    IOFMessageListener test1 = createMock(IOFMessageListener.class);
    expect(test1.getName()).andReturn("test1").atLeastOnce();
    expect(test1.isCallbackOrderingPrereq((OFType) anyObject(), (String) anyObject()))
        .andReturn(false)
        .atLeastOnce();
    expect(test1.isCallbackOrderingPostreq((OFType) anyObject(), (String) anyObject()))
        .andReturn(false)
        .atLeastOnce();

    replay(test1, sw);
    controller.addOFMessageListener(OFType.PACKET_IN, test1);
    // message should not be dispatched
    controller.handleMessage(sw, pi, null);
    verify(test1);

    // ---------------------------------
    // transition to Master
    // --------------------------------
    controller.setRole(HARole.ACTIVE, "FooBar");

    // transitioned but HA listeneres not yet notified.
    // message should not be dispatched
    reset(test1);
    replay(test1);
    controller.handleMessage(sw, pi, null);
    verify(test1);

    // notify HA listeners
    controller.processUpdateQueueForTesting();
    // no message should be dispatched
    reset(test1);
    expect(test1.receive(eq(sw), eq(pi), isA(FloodlightContext.class))).andReturn(Command.STOP);
    replay(test1);
    controller.handleMessage(sw, pi, null);
    verify(test1);

    verify(sw);
  }
Example #23
0
 @Test
 public void testRestoreState3() {
   FacesContext context = EasyMock.createMock(FacesContext.class);
   UIInput input = new UIInput();
   replay(context);
   Object state = input.saveState(context);
   assertNotNull(state);
   input.restoreState(context, state);
   verify(context);
 }
Example #24
0
  @Test
  public void testInfo() {
    org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class);

    mock.info("a");
    replay(mock);

    InternalLogger logger = new Log4JLogger(mock);
    logger.info("a");
    verify(mock);
  }
Example #25
0
  @Test
  public void testDebugWithException() {
    org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class);

    mock.debug("a", e);
    replay(mock);

    InternalLogger logger = new Log4JLogger(mock);
    logger.debug("a", e);
    verify(mock);
  }
Example #26
0
  @Test
  public void testIsInfoEnabled() {
    org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class);

    expect(mock.isInfoEnabled()).andReturn(true);
    replay(mock);

    InternalLogger logger = new Log4JLogger(mock);
    assertTrue(logger.isInfoEnabled());
    verify(mock);
  }
Example #27
0
  private <T> void resetCommunicatorExpectingSingleBroadcast(
      Capture<T> message, Capture<MessageSubject> subject, Capture<Function<T, byte[]>> encoder) {

    message.reset();
    subject.reset();
    encoder.reset();
    reset(clusterCommunicator);
    clusterCommunicator.broadcast(capture(message), capture(subject), capture(encoder));
    expectLastCall().once();
    replay(clusterCommunicator);
  }
  @Test
  public void shouldForwardReadCallsBlindly() throws Exception {
    ChannelBuffer buf = createStrictMock(ChannelBuffer.class);
    expect(buf.readerIndex()).andReturn(0).anyTimes();
    expect(buf.writerIndex()).andReturn(0).anyTimes();
    expect(buf.capacity()).andReturn(0).anyTimes();

    expect(buf.getBytes(1, (GatheringByteChannel) null, 2)).andReturn(3);
    buf.getBytes(4, (OutputStream) null, 5);
    buf.getBytes(6, (byte[]) null, 7, 8);
    buf.getBytes(9, (ChannelBuffer) null, 10, 11);
    buf.getBytes(12, (ByteBuffer) null);
    expect(buf.getByte(13)).andReturn(Byte.valueOf((byte) 14));
    expect(buf.getShort(15)).andReturn(Short.valueOf((short) 16));
    expect(buf.getUnsignedMedium(17)).andReturn(18);
    expect(buf.getInt(19)).andReturn(20);
    expect(buf.getLong(21)).andReturn(22L);

    ByteBuffer bb = ByteBuffer.allocate(100);
    ByteBuffer[] bbs = {ByteBuffer.allocate(101), ByteBuffer.allocate(102)};

    expect(buf.toByteBuffer(23, 24)).andReturn(bb);
    expect(buf.toByteBuffers(25, 26)).andReturn(bbs);
    expect(buf.capacity()).andReturn(27);

    replay(buf);

    ChannelBuffer roBuf = unmodifiableBuffer(buf);
    assertEquals(3, roBuf.getBytes(1, (GatheringByteChannel) null, 2));
    roBuf.getBytes(4, (OutputStream) null, 5);
    roBuf.getBytes(6, (byte[]) null, 7, 8);
    roBuf.getBytes(9, (ChannelBuffer) null, 10, 11);
    roBuf.getBytes(12, (ByteBuffer) null);
    assertEquals((byte) 14, roBuf.getByte(13));
    assertEquals((short) 16, roBuf.getShort(15));
    assertEquals(18, roBuf.getUnsignedMedium(17));
    assertEquals(20, roBuf.getInt(19));
    assertEquals(22L, roBuf.getLong(21));

    ByteBuffer roBB = roBuf.toByteBuffer(23, 24);
    assertEquals(100, roBB.capacity());
    assertTrue(roBB.isReadOnly());

    ByteBuffer[] roBBs = roBuf.toByteBuffers(25, 26);
    assertEquals(2, roBBs.length);
    assertEquals(101, roBBs[0].capacity());
    assertTrue(roBBs[0].isReadOnly());
    assertEquals(102, roBBs[1].capacity());
    assertTrue(roBBs[1].isReadOnly());
    assertEquals(27, roBuf.capacity());

    verify(buf);
  }
 private Dictionary createDictionary(String... valid) {
   Dictionary dictionary = createMock(Dictionary.class);
   for (String word : valid) {
     if (word != null) {
       expect(dictionary.contains(word)).andReturn(true);
     } else {
       expect(dictionary.contains(isA(String.class))).andReturn(false);
     }
   }
   replay(dictionary);
   return dictionary;
 }
  @Test
  public void accepts_noneRun() throws DatabaseException {
    Database database = createMock(Database.class);
    expect(database.getRanChangeSetList()).andReturn(new ArrayList<RanChangeSet>());
    replay(database);

    ShouldRunChangeSetFilter filter = new ShouldRunChangeSetFilter(database);

    assertTrue(
        filter.accepts(
            new ChangeSet("1", "testAuthor", false, false, "path/changelog", null, null)));
  }