Exemplo n.º 1
1
  /**
   * Tests all options, checks if their default values are correct.
   *
   * @throws Exception
   */
  public void testDefaultConfig() throws Exception {
    ZipalignMojo mojo = createMojo("zipalign-config-project0");
    final ConfigHandler cfh = new ConfigHandler(mojo);
    cfh.parseConfiguration();

    Boolean skip = Whitebox.getInternalState(mojo, "parsedSkip");
    assertTrue("zipalign 'skip' parameter should be true", skip);

    Boolean verbose = Whitebox.getInternalState(mojo, "parsedVerbose");
    assertFalse("zipalign 'verbose' parameter should be false", verbose);

    MavenProject project = Whitebox.getInternalState(mojo, "project");

    String inputApk = Whitebox.getInternalState(mojo, "parsedInputApk");
    File inputApkFile =
        new File(project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".apk");
    assertEquals(
        "zipalign 'inputApk' parameter should be equal", inputApkFile.getAbsolutePath(), inputApk);

    String outputApk = Whitebox.getInternalState(mojo, "parsedOutputApk");
    File outputApkFile =
        new File(
            project.getBuild().getDirectory(), project.getBuild().getFinalName() + "-aligned.apk");
    assertEquals(
        "zipalign 'outputApk' parameter should be equal",
        outputApkFile.getAbsolutePath(),
        outputApk);
  }
Exemplo n.º 2
1
  @Test
  public void should_create_entity_dao() throws Exception {
    PropertyMeta idMeta =
        PropertyMetaTestBuilder //
            .completeBean(Void.class, Long.class)
            .field("id")
            .build();

    EntityMeta entityMeta = new EntityMeta();
    entityMeta.setClusteredEntity(false);
    entityMeta.setTableName("cf");
    entityMeta.setIdMeta(idMeta);
    entityMeta.setIdClass(Long.class);
    entityMeta.setPropertyMetas(new HashMap<String, PropertyMeta>());

    factory.createDaosForEntity(
        cluster, keyspace, configContext, entityMeta, entityDaosMap, wideRowDaosMap);

    ThriftGenericEntityDao entityDao = entityDaosMap.get("cf");

    assertThat(entityDao).isNotNull();
    assertThat(entityDao.getColumnFamily()).isEqualTo("cf");
    assertThat(Whitebox.getInternalState(entityDao, "policy")).isSameAs(consistencyPolicy);
    assertThat(Whitebox.getInternalState(entityDao, "cluster")).isSameAs(cluster);
    assertThat(Whitebox.getInternalState(entityDao, "keyspace")).isSameAs(keyspace);
    assertThat(Whitebox.getInternalState(entityDao, "columnNameSerializer"))
        .isSameAs(COMPOSITE_SRZ);

    Pair<Class<Long>, Class<String>> rowAndValueClases =
        Whitebox.getInternalState(entityDao, "rowkeyAndValueClasses");
    assertThat(rowAndValueClases.left).isSameAs(Long.class);
    assertThat(rowAndValueClases.right).isSameAs(String.class);
  }
  /*
   * Test that if enabled, but not configured, that the code creates the 2nd level classloader
   */
  @Test
  public void testDefaultConfig() throws Exception {

    Whitebox.setInternalState(
        AccumuloVFSClassLoader.class, "loader", (AccumuloReloadingVFSClassLoader) null);

    File conf = folder1.newFile("accumulo-site.xml");
    FileWriter out = new FileWriter(conf);
    out.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    out.append("<configuration>\n");
    out.append("<property>\n");
    out.append("<name>general.classpaths</name>\n");
    out.append("<value></value>\n");
    out.append("</property>\n");
    out.append("<property>\n");
    out.append("<name>general.vfs.classpaths</name>\n");
    out.append("<value></value>\n");
    out.append("</property>\n");
    out.append("</configuration>\n");
    out.close();

    Whitebox.setInternalState(
        AccumuloClassLoader.class, "SITE_CONF", conf.toURI().toURL().toString());
    Whitebox.setInternalState(AccumuloVFSClassLoader.class, "lock", new Object());
    ClassLoader acl = AccumuloVFSClassLoader.getClassLoader();
    Assert.assertTrue((acl instanceof VFSClassLoader));
    Assert.assertTrue((acl.getParent() instanceof URLClassLoader));
  }
  /**
   * Tests if a {@link MatrixBuild} gets loaded and converted correctly from a version 1.2.0 save.
   *
   * @throws InterruptedException if it is not allowed to sleep in the beginning.
   */
  @LocalData
  public void testMatrix120() throws InterruptedException {
    MatrixProject project = (MatrixProject) jenkins.getItem("mymatrix");
    MatrixBuild build = project.getBuildByNumber(1);
    OldDataConverter.getInstance().waitForInitialCompletion();
    FailureCauseMatrixBuildAction matrixBuildAction =
        build.getAction(FailureCauseMatrixBuildAction.class);
    assertNotNull(matrixBuildAction);
    List<MatrixRun> runs = Whitebox.getInternalState(matrixBuildAction, "runs");
    assertNotNull(runs);
    List<String> runIds = null;

    runIds = Whitebox.getInternalState(matrixBuildAction, "runIds");

    assertEquals(runs.size(), runIds.size());
    assertNotNull(runs.get(3).getProject());
    assertEquals(runs.get(3).getProject().getCombination().toString(), runIds.get(3));
    assertNotNull(Whitebox.getInternalState(matrixBuildAction, "build"));

    MatrixBuild build2 = project.getBuildByNumber(2);
    List<MatrixRun> aggregatedRuns2 = FailureCauseMatrixAggregator.getRuns(build2);
    FailureCauseMatrixBuildAction matrixBuildAction2 =
        build2.getAction(FailureCauseMatrixBuildAction.class);
    assertNotNull(matrixBuildAction2);
    List<MatrixRun> runs2 = Whitebox.getInternalState(matrixBuildAction2, "runs");
    assertSame(aggregatedRuns2.get(5), runs2.get(5));
  }
 /**
  * Checks the list of event listeners for a single {@link
  * com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.EventListener} that points to a
  * {@link GerritTrigger} and checks if that is configured for the project pattern.
  *
  * @param gerritProjectPattern the pattern to check
  * @throws Exception if so
  */
 private void assertEventListenerWithSomeOtherProjectSet(String gerritProjectPattern)
     throws Exception {
   Collection<GerritEventListener> eventListeners = getGerritEventListeners();
   boolean found = false;
   for (GerritEventListener listener : eventListeners) {
     if (listener
         .getClass()
         .getName()
         .equals("com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.EventListener")) {
       found = true;
       GerritTrigger trigger = Whitebox.invokeMethod(listener, "getTrigger");
       assertNotNull("No Trigger for EventListener", trigger);
       assertSame(Whitebox.getInternalState(trigger, "job"), j.jenkins.getItem("testProj"));
       List<GerritProject> projectList = trigger.getGerritProjects();
       assertEquals(2, projectList.size());
       boolean foundSomeOtherProject = false;
       for (GerritProject project : projectList) {
         if (gerritProjectPattern.equals(project.getPattern())) {
           foundSomeOtherProject = true;
         }
       }
       assertTrue("Could not find " + gerritProjectPattern, foundSomeOtherProject);
     }
   }
   assertTrue("No EventListener", found);
 }
Exemplo n.º 6
0
  @Test
  public void should_create_value_less_clustered_entity_dao() throws Exception {

    PropertyMeta idMeta =
        PropertyMetaTestBuilder.valueClass(CompoundKey.class)
            .compClasses(Integer.class, String.class, UUID.class)
            .field("id")
            .type(PropertyType.EMBEDDED_ID)
            .build();

    EntityMeta entityMeta = new EntityMeta();
    entityMeta.setClusteredEntity(true);
    entityMeta.setIdMeta(idMeta);
    entityMeta.setTableName("cf");
    entityMeta.setPropertyMetas(ImmutableMap.of("id", idMeta));

    factory.createClusteredEntityDao(cluster, keyspace, configContext, entityMeta, wideRowDaosMap);

    ThriftGenericWideRowDao clusteredEntityDao = wideRowDaosMap.get("cf");

    assertThat(clusteredEntityDao).isNotNull();
    assertThat(clusteredEntityDao.getColumnFamily()).isEqualTo("cf");
    assertThat(Whitebox.getInternalState(clusteredEntityDao, "policy")).isSameAs(consistencyPolicy);
    assertThat(Whitebox.getInternalState(clusteredEntityDao, "cluster")).isSameAs(cluster);
    assertThat(Whitebox.getInternalState(clusteredEntityDao, "keyspace")).isSameAs(keyspace);
    assertThat(Whitebox.getInternalState(clusteredEntityDao, "columnNameSerializer"))
        .isSameAs(COMPOSITE_SRZ);

    Pair<Class<Integer>, Class<String>> rowAndValueClasses =
        Whitebox.getInternalState(clusteredEntityDao, "rowkeyAndValueClasses");
    assertThat(rowAndValueClasses.left).isSameAs(Integer.class);
    assertThat(rowAndValueClasses.right).isSameAs(String.class);
  }
 /**
  * Gets the internal list of listeners from {@link
  * com.sonymobile.tools.gerrit.gerritevents.GerritHandler#gerritEventListeners}.
  *
  * @return the list.
  */
 private Collection<GerritEventListener> getGerritEventListeners() {
   GerritHandler handler =
       Whitebox.getInternalState(
           PluginImpl.getInstance().getServer(PluginImpl.DEFAULT_SERVER_NAME),
           GerritHandler.class);
   return Whitebox.getInternalState(handler, "gerritEventListeners");
 }
 /**
  * Tests that the trigger is added as a listener during startup of the server.
  *
  * @throws Exception if so.
  */
 @LocalData
 public void testProject() throws Exception {
   GerritHandler handler =
       Whitebox.getInternalState(PluginImpl.getInstance(), GerritHandler.class);
   Map<Integer, GerritEventListener> gerritEventListeners =
       Whitebox.getInternalState(handler, "gerritEventListeners");
   assertEquals(1, gerritEventListeners.size());
 }
Exemplo n.º 9
0
  /**
   * Tests run of zipalign with correct parameters as well adding aligned file to artifacts
   *
   * @throws Exception
   */
  public void testDefaultRun() throws Exception {
    ZipalignMojo mojo = createMojo("zipalign-config-project3");

    MavenProject project = Whitebox.getInternalState(mojo, "project");
    project.setPackaging(AndroidExtension.APK);

    MavenProjectHelper projectHelper = EasyMock.createNiceMock(MavenProjectHelper.class);
    Capture<File> capturedParameter = new Capture<File>();
    projectHelper.attachArtifact(
        EasyMock.eq(project),
        EasyMock.eq(AndroidExtension.APK),
        EasyMock.eq("aligned"),
        EasyMock.capture(capturedParameter));
    Whitebox.setInternalState(mojo, "projectHelper", projectHelper);

    final CommandExecutor mockExecutor = PowerMock.createMock(CommandExecutor.class);
    PowerMock.replace(
            CommandExecutor.Factory.class.getDeclaredMethod("createDefaultCommmandExecutor"))
        .with(
            new InvocationHandler() {
              @Override
              public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return mockExecutor;
              }
            });

    Capture<List<String>> capturedFile = new Capture<List<String>>();
    mockExecutor.setLogger(EasyMock.anyObject(Log.class));
    mockExecutor.executeCommand(EasyMock.anyObject(String.class), EasyMock.capture(capturedFile));

    PowerMock.mockStatic(FileUtils.class);
    EasyMock.expect(FileUtils.fileExists("app-updated.apk")).andReturn(true);

    EasyMock.replay(projectHelper);
    PowerMock.replay(mockExecutor);
    PowerMock.replay(FileUtils.class);

    mojo.execute();

    PowerMock.verify(mockExecutor);
    List<String> parameters = capturedFile.getValue();
    List<String> parametersExpected = new ArrayList<String>();
    parametersExpected.add("-v");
    parametersExpected.add("-f");
    parametersExpected.add("4");
    parametersExpected.add("app.apk");
    parametersExpected.add("app-updated.apk");
    assertEquals("Zipalign arguments aren't as expected", parametersExpected, parameters);

    PowerMock.verify(projectHelper);
    assertEquals(
        "File should be same as expected",
        new File("app-updated.apk"),
        capturedParameter.getValue());

    // verify that all method were invoked
    PowerMock.verify(FileUtils.class);
  }
 @Test
 public void testSupressStaticInitializerAndSetFinalField() throws Exception {
   assertNull(
       "Should be null because the static initializer should be suppressed",
       StaticInitializerExample.getMySet());
   final HashSet<String> hashSet = new HashSet<String>();
   Whitebox.setInternalState(StaticInitializerExample.class, "mySet", hashSet);
   assertSame(hashSet, Whitebox.getInternalState(StaticInitializerExample.class, "mySet"));
 }
 /**
  * Tests that the re-loaded trigger is still there when a new triggered project is added.
  *
  * @throws Exception if so.
  */
 @LocalData
 public void testCreateNewProject() throws Exception {
   FreeStyleProject p = createGerritTriggeredJob(this, "testing1");
   GerritHandler handler =
       Whitebox.getInternalState(PluginImpl.getInstance(), GerritHandler.class);
   Map<Integer, GerritEventListener> gerritEventListeners =
       Whitebox.getInternalState(handler, "gerritEventListeners");
   assertEquals(2, gerritEventListeners.size());
 }
 @Before
 public void before() throws Exception {
   AlluxioWorker alluxioWorker = mResource.get().getWorker();
   mBlockWorker = PowerMockito.mock(BlockWorker.class);
   // Replace the block worker created by LocalAlluxioClusterResource with a mock.
   BlockWorker blockWorker = Whitebox.getInternalState(alluxioWorker, "mBlockWorker");
   blockWorker.stop();
   Whitebox.setInternalState(alluxioWorker, "mBlockWorker", mBlockWorker);
 }
 @Before
 public void setUp() {
   pmf =
       new PersistenceManagerFactory(
           cluster, ImmutableMap.<ConfigurationParameters, Object>of(FORCE_TABLE_CREATION, true));
   pmf.configurationMap = configMap;
   Whitebox.setInternalState(pmf, ArgumentExtractor.class, argumentExtractor);
   Whitebox.setInternalState(pmf, AchillesBootstrapper.class, boostrapper);
   Whitebox.setInternalState(pmf, ProxyClassFactory.class, proxyClassFactory);
 }
  @Before
  public void init() {
    controller = new FlexOfferController();
    Whitebox.setInternalState(controller, messageService);
    Whitebox.setInternalState(controller, jmsService);
    Whitebox.setInternalState(controller, corePlanboardBusinessService);
    Whitebox.setInternalState(controller, corePlanboardValidatorService);
    Whitebox.setInternalState(controller, config);

    PowerMockito.when(config.getProperty(Matchers.eq(ConfigParam.HOST_DOMAIN)))
        .thenReturn("usef-example.com");
  }
Exemplo n.º 15
0
  @Test
  public void testGetInstance_whenDefaultInstanceIsNull() {
    // given
    ExceptionMapper exceptionMapper = null;
    Whitebox.setInternalState(ExceptionMapper.class, "defaultInstance", exceptionMapper);

    // then
    exceptionMapper = ExceptionMapper.getInstance();
    assertEquals(
        "Should be equals because ExceptionMapper is a singleton",
        Whitebox.getInternalState(ExceptionMapper.class, "defaultInstance"),
        exceptionMapper);
  }
Exemplo n.º 16
0
  @Before
  public void setUp() {
    File dataDir = tempDir.getRoot();

    when(settings.getDocumentrDataDir()).thenReturn(dataDir);

    globalRepoManager = new GlobalRepositoryManager();
    Whitebox.setInternalState(globalRepoManager, settings, repoManagerFactory, eventBus);
    globalRepoManager.init();

    pageStore = new PageStore();
    Whitebox.setInternalState(pageStore, globalRepoManager, eventBus);
  }
Exemplo n.º 17
0
 /** Sets up all dependencies before running a test. */
 @Before
 public void before() {
   mLineageMasterClient = PowerMockito.mock(LineageMasterClient.class);
   mLineageContext = PowerMockito.mock(LineageContext.class);
   Mockito.when(mLineageContext.acquireMasterClient()).thenReturn(mLineageMasterClient);
   Whitebox.setInternalState(LineageContext.class, "INSTANCE", mLineageContext);
   mAlluxioLineageFileSystem = LineageFileSystem.get();
   Whitebox.setInternalState(mAlluxioLineageFileSystem, "mLineageContext", mLineageContext);
   FileSystemContext fileSystemContext = PowerMockito.mock(FileSystemContext.class);
   FileSystemMasterClient fileSystemMasterClient = PowerMockito.mock(FileSystemMasterClient.class);
   Mockito.when(fileSystemContext.acquireMasterClient()).thenReturn(fileSystemMasterClient);
   Whitebox.setInternalState(FileSystemContext.class, "INSTANCE", fileSystemContext);
   Whitebox.setInternalState(mAlluxioLineageFileSystem, "mContext", fileSystemContext);
 }
Exemplo n.º 18
0
  private void assertThatBatchContextHasBeenReset(CQLBatchingEntityManager batchEm) {
    CQLBatchingFlushContext flushContext =
        Whitebox.getInternalState(batchEm, CQLBatchingFlushContext.class);
    Optional<ConsistencyLevel> readLevelO = Whitebox.getInternalState(flushContext, "readLevelO");
    Optional<ConsistencyLevel> writeLevelO = Whitebox.getInternalState(flushContext, "writeLevelO");
    Optional<Integer> ttlO = Whitebox.getInternalState(flushContext, "ttlO");
    List<BoundStatement> boundStatements =
        Whitebox.getInternalState(flushContext, "boundStatements");

    assertThat(readLevelO.isPresent()).isFalse();
    assertThat(writeLevelO.isPresent()).isFalse();
    assertThat(ttlO.isPresent()).isFalse();
    assertThat(boundStatements).isEmpty();
  }
  @Test
  public void should_bootstrap_persistence_manager_factory() throws Exception {
    // Given
    List<Class<?>> candidateClasses = Arrays.asList();
    List<Interceptor<?>> interceptors = Arrays.asList();
    Map<Class<?>, EntityMeta> entityMetaMap =
        ImmutableMap.<Class<?>, EntityMeta>of(CompleteBean.class, new EntityMeta());
    ParsingResult parsingResult = new ParsingResult(entityMetaMap, true);

    // When
    when(argumentExtractor.initConfigContext(configMap)).thenReturn(configContext);
    when(argumentExtractor.initSession(cluster, configMap)).thenReturn(session);
    when(argumentExtractor.initInterceptors(configMap)).thenReturn(interceptors);
    when(argumentExtractor.initProxyWarmUp(configMap)).thenReturn(true);
    when(argumentExtractor.initEntities(configMap)).thenReturn(candidateClasses);

    when(configMap.getTyped(ENTITY_PACKAGES)).thenReturn("packages");
    when(configMap.getTyped(KEYSPACE_NAME)).thenReturn("keyspace");
    when(boostrapper.buildMetaDatas(configContext, candidateClasses)).thenReturn(parsingResult);
    when(configContext.isForceColumnFamilyCreation()).thenReturn(true);
    when(boostrapper.buildDaoContext(session, parsingResult, configContext)).thenReturn(daoContext);

    pmf.bootstrap();

    // Then
    assertThat(pmf.entityMetaMap).isSameAs(entityMetaMap);
    assertThat(pmf.configContext).isSameAs(configContext);
    assertThat(pmf.daoContext).isSameAs(daoContext);
    PersistenceContextFactory contextFactory =
        Whitebox.getInternalState(pmf, PersistenceContextFactory.class);
    assertThat(Whitebox.getInternalState(contextFactory, DaoContext.class)).isSameAs(daoContext);
    assertThat(Whitebox.getInternalState(contextFactory, ConfigurationContext.class))
        .isSameAs(configContext);
    assertThat(Whitebox.getInternalState(contextFactory, "entityMetaMap")).isSameAs(entityMetaMap);

    verify(boostrapper).buildMetaDatas(configContext, candidateClasses);
    verify(boostrapper).validateOrCreateTables(contextCaptor.capture());
    verify(boostrapper).addInterceptorsToEntityMetas(interceptors, entityMetaMap);
    verify(proxyClassFactory).createProxyClass(CompleteBean.class);

    SchemaContext schemaContext = contextCaptor.getValue();

    assertThat(Whitebox.getInternalState(schemaContext, Cluster.class)).isSameAs(cluster);
    assertThat(Whitebox.getInternalState(schemaContext, Session.class)).isSameAs(session);
    assertThat(Whitebox.getInternalState(schemaContext, "entityMetaMap")).isSameAs(entityMetaMap);
    assertThat(Whitebox.getInternalState(schemaContext, "keyspaceName")).isEqualTo("keyspace");
    assertThat((Boolean) Whitebox.getInternalState(schemaContext, "forceColumnFamilyCreation"))
        .isTrue();
    assertThat((Boolean) Whitebox.getInternalState(schemaContext, "hasCounter")).isTrue();
  }
Exemplo n.º 20
0
  @Test
  public void should_create_counter_dao() throws Exception {
    ThriftCounterDao thriftCounterDao = factory.createCounterDao(cluster, keyspace, configContext);

    assertThat(thriftCounterDao).isNotNull();
    assertThat(Whitebox.getInternalState(thriftCounterDao, "policy")).isSameAs(consistencyPolicy);
    assertThat(Whitebox.getInternalState(thriftCounterDao, "cluster")).isSameAs(cluster);
    assertThat(Whitebox.getInternalState(thriftCounterDao, "keyspace")).isSameAs(keyspace);
    assertThat(Whitebox.getInternalState(thriftCounterDao, "columnNameSerializer"))
        .isSameAs(COMPOSITE_SRZ);
    Pair<Class<Composite>, Class<Long>> rowAndValueClases =
        Whitebox.getInternalState(thriftCounterDao, "rowkeyAndValueClasses");
    assertThat(rowAndValueClases.left).isSameAs(Composite.class);
    assertThat(rowAndValueClases.right).isSameAs(Long.class);
  }
 @BeforeClass
 public void setUpClass() {
   mockControl = EasyMock.createStrictControl();
   logger = mockControl.createMock(Logger.class);
   generator = mockControl.createMock(RandomNumberGenerator.class);
   setUpEnemy();
   setUpResolvationData();
   underTest = new SingleFightRoundResolver();
   Whitebox.setInternalState(underTest, "logger", logger);
   Whitebox.setInternalState(underTest, "generator", generator);
   init(mockControl, underTest);
   beforeRoundResult = new FightBeforeRoundResult();
   diceResultRenderer = mockControl.createMock(DiceResultRenderer.class);
   Whitebox.setInternalState(underTest, "diceResultRenderer", diceResultRenderer);
 }
Exemplo n.º 22
0
  @Test
  public void shouldCancelOrder() throws IOException {
    // given
    BitMarketCancelResponse response =
        new BitMarketCancelResponse(
            true,
            new BitMarketBalance(createAvailable(), createBlocked()),
            new BitMarketAPILimit(3, 100, 12345000L),
            0,
            null);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(
            bitMarketAuthenticated.cancel(
                Mockito.eq(SPECIFICATION_API_KEY),
                Mockito.any(ParamsDigest.class),
                Mockito.any(SynchronizedValueFactory.class),
                Mockito.eq(12345L)))
        .thenReturn(response);
    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    boolean cancelled = tradeService.cancelOrder("12345");

    // then
    assertThat(cancelled).isTrue();
  }
Exemplo n.º 23
0
  /**
   * Tests the {@link SwiftUnderFileSystem#stripFolderSuffixIfPresent(String)} method.
   *
   * @throws Exception when the Whitebox fails
   */
  @Test
  public void stripFolderSuffixIfPresentTest() throws Exception {
    String input1 = mMockContainerPrefix;
    String input2 = mMockContainerPrefix + "dir/file";
    String input3 = mMockContainerPrefix + "dir_$folder$";
    String result1 =
        Whitebox.invokeMethod(mMockSwiftUnderFileSystem, "stripFolderSuffixIfPresent", input1);
    String result2 =
        Whitebox.invokeMethod(mMockSwiftUnderFileSystem, "stripFolderSuffixIfPresent", input2);
    String result3 =
        Whitebox.invokeMethod(mMockSwiftUnderFileSystem, "stripFolderSuffixIfPresent", input3);

    Assert.assertEquals(mMockContainerPrefix, result1);
    Assert.assertEquals(mMockContainerPrefix + "dir/file", result2);
    Assert.assertEquals(mMockContainerPrefix + "dir", result3);
  }
Exemplo n.º 24
0
  /**
   * If a close request to an unknown session is received it should be replied with an
   * &lt;item-not-found/&gt; error.
   *
   * @throws Exception should not happen
   */
  @Test
  public void shouldReplyErrorIfSessionIsUnknown() throws Exception {

    // mock connection
    XMPPConnection connection = mock(XMPPConnection.class);

    // initialize InBandBytestreamManager to get the CloseListener
    InBandBytestreamManager byteStreamManager =
        InBandBytestreamManager.getByteStreamManager(connection);

    // get the CloseListener from InBandByteStreamManager
    CloseListener closeListener = Whitebox.getInternalState(byteStreamManager, CloseListener.class);

    Close close = new Close("unknownSessionId");
    close.setFrom(initiatorJID);
    close.setTo(targetJID);

    closeListener.handleIQRequest(close);

    // wait because packet is processed in an extra thread
    Thread.sleep(200);

    // capture reply to the In-Band Bytestream close request
    ArgumentCaptor<IQ> argument = ArgumentCaptor.forClass(IQ.class);
    verify(connection).sendStanza(argument.capture());

    // assert that reply is the correct error packet
    assertEquals(initiatorJID, argument.getValue().getTo());
    assertEquals(IQ.Type.error, argument.getValue().getType());
    assertEquals(XMPPError.Condition.item_not_found, argument.getValue().getError().getCondition());
  }
  /**
   * Tests {@link
   * TriggerContextConverter#unmarshal(com.thoughtworks.xstream.io.HierarchicalStreamReader,
   * com.thoughtworks.xstream.converters.UnmarshallingContext)}. With "retriggerAction_oldData2.xml"
   * as input.
   *
   * @throws Exception if so.
   */
  @Test
  public void testUnmarshalOldData2() throws Exception {
    XStream xStream = new XStream2();
    xStream.registerConverter(new TriggerContextConverter());
    Object obj = xStream.fromXML(getClass().getResourceAsStream("retriggerAction_oldData2.xml"));
    assertTrue(obj instanceof RetriggerAction);
    RetriggerAction action = (RetriggerAction) obj;
    TriggerContext context = Whitebox.getInternalState(action, "context");
    assertNotNull(context.getEvent());
    assertEquals(
        "semctools/hudson/plugins/gerrit-trigger-plugin",
        context.getEvent().getChange().getProject());
    assertEquals("1", context.getEvent().getPatchSet().getNumber());

    assertNotNull(context.getThisBuild());
    assertEquals(6, context.getThisBuild().getBuildNumber().intValue());
    assertEquals("EXPERIMENTAL_Gerrit_Trigger_1", context.getThisBuild().getProjectId());

    assertNotNull(context.getOthers());
    assertEquals(2, context.getOthers().size());
    TriggeredItemEntity entity = context.getOthers().get(0);
    assertEquals(16, entity.getBuildNumber().intValue());
    assertEquals("EXPERIMENTAL_Gerrit_Trigger_2", entity.getProjectId());
    entity = context.getOthers().get(1);
    assertEquals(15, entity.getBuildNumber().intValue());
    assertEquals("EXPERIMENTAL_Gerrit_Trigger_3", entity.getProjectId());
  }
Exemplo n.º 26
0
 /**
  * Tests the {@link SwiftUnderFileSystem#stripPrefixIfPresent(String)} method.
  *
  * @throws Exception when the Whitebox fails
  */
 @Test
 public void stripPrefixIfPresentTest() throws Exception {
   String[] inputs =
       new String[] {
         "swift://" + mMockContainerName,
         mMockContainerPrefix,
         mMockContainerPrefix + "file",
         mMockContainerPrefix + "dir/file",
         "swift://test-container-wrong/dir/file",
         "dir/file",
         "/dir/file",
       };
   String[] results =
       new String[] {
         "swift://" + mMockContainerName,
         "",
         "file",
         "dir/file",
         "swift://test-container-wrong/dir/file",
         "dir/file",
         "/dir/file",
       };
   for (int i = 0; i < inputs.length; i++) {
     Assert.assertEquals(
         results[i],
         Whitebox.invokeMethod(mMockSwiftUnderFileSystem, "stripPrefixIfPresent", inputs[i]));
   }
 }
  /**
   * Tests {@link
   * TriggerContextConverter#unmarshal(com.thoughtworks.xstream.io.HierarchicalStreamReader,
   * com.thoughtworks.xstream.converters.UnmarshallingContext)}. With "matrix_build.xml" as input.
   *
   * @throws Exception if so.
   */
  @Test
  public void testUnmarshalOldMatrixBuild() throws Exception {
    XStream xStream = new XStream2();
    xStream.registerConverter(new TriggerContextConverter());
    xStream.alias("matrix-run", MatrixRun.class);
    Object obj = xStream.fromXML(getClass().getResourceAsStream("matrix_build.xml"));
    assertTrue(obj instanceof MatrixRun);
    MatrixRun run = (MatrixRun) obj;

    Cause.UpstreamCause upCause = run.getCause(Cause.UpstreamCause.class);
    List upstreamCauses = Whitebox.getInternalState(upCause, "upstreamCauses");
    GerritCause cause = (GerritCause) upstreamCauses.get(0);
    assertNotNull(cause.getEvent());
    assertEquals("platform/project", cause.getEvent().getChange().getProject());
    assertNotNull(cause.getContext());
    assertNotNull(cause.getContext().getThisBuild());

    assertEquals("Gerrit_master-theme_matrix", cause.getContext().getThisBuild().getProjectId());
    assertEquals(102, cause.getContext().getThisBuild().getBuildNumber().intValue());

    assertNotNull(cause.getContext().getOthers());
    assertEquals(1, cause.getContext().getOthers().size());

    TriggeredItemEntity entity = cause.getContext().getOthers().get(0);
    assertEquals("master-theme", entity.getProjectId());
    assertNull(entity.getBuildNumber());
  }
Exemplo n.º 28
0
  @Test(expected = ExchangeException.class)
  public void shouldFailOnUnsuccessfulLimitOrder() throws IOException {
    // given
    BitMarketTradeResponse response =
        new BitMarketTradeResponse(
            false, null, new BitMarketAPILimit(3, 100, 12345000L), 502, "Invalid message hash");

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(
            bitMarketAuthenticated.trade(
                Mockito.eq(SPECIFICATION_API_KEY),
                Mockito.any(ParamsDigest.class),
                Mockito.any(SynchronizedValueFactory.class),
                Mockito.eq("BTCAUD"),
                Mockito.eq("sell"),
                Mockito.eq(BigDecimal.ONE),
                Mockito.eq(BigDecimal.TEN)))
        .thenReturn(response);
    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    tradeService.placeLimitOrder(
        new LimitOrder(
            Order.OrderType.ASK,
            BigDecimal.ONE,
            CurrencyPair.BTC_AUD,
            "12345",
            null,
            BigDecimal.TEN));

    // then
    fail(
        "BitMarketTradeService should throw ExchangeException when place limit order request was unsuccessful");
  }
Exemplo n.º 29
0
  @Test
  public void shouldGetOpenOrders() throws IOException {
    // given
    final LimitOrder[] expectedOrders = expectedOrders();

    BitMarketOrdersResponse response =
        new BitMarketOrdersResponse(
            true, createOpenOrdersData(), new BitMarketAPILimit(3, 100, 12345000L), 0, null);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(
            bitMarketAuthenticated.orders(
                Mockito.eq(SPECIFICATION_API_KEY),
                Mockito.any(ParamsDigest.class),
                Mockito.any(SynchronizedValueFactory.class)))
        .thenReturn(response);
    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    OpenOrders orders = tradeService.getOpenOrders();
    List<LimitOrder> openOrders = orders.getOpenOrders();

    // then
    assertThat(openOrders).hasSize(2);
    for (int i = 0; i < openOrders.size(); i++) {
      BitMarketAssert.assertEquals(openOrders.get(i), expectedOrders[i]);
      assertThat(orders.toString()).contains(expectedOrders[i].toString());
    }
  }
Exemplo n.º 30
0
  @Test
  public void should_create_object_type_clustered_entity_dao() throws Exception {

    PropertyMeta idMeta =
        PropertyMetaTestBuilder.valueClass(CompoundKey.class)
            .compClasses(Integer.class, String.class, UUID.class)
            .field("id")
            .type(PropertyType.EMBEDDED_ID)
            .build();

    PropertyMeta pm =
        PropertyMetaTestBuilder.valueClass(UserBean.class).type(PropertyType.SIMPLE).build();

    EntityMeta entityMeta = new EntityMeta();
    entityMeta.setClusteredEntity(true);
    entityMeta.setIdMeta(idMeta);
    entityMeta.setTableName("cf");
    entityMeta.setPropertyMetas(ImmutableMap.of("id", idMeta, "pm", pm));
    entityMeta.setAllMetasExceptIdMeta(Arrays.asList(pm));
    entityMeta.setFirstMeta(pm);

    factory.createClusteredEntityDao(cluster, keyspace, configContext, entityMeta, wideRowDaosMap);

    ThriftGenericWideRowDao clusteredEntityDao = wideRowDaosMap.get("cf");

    Pair<Class<Integer>, Class<String>> rowAndValueClases =
        Whitebox.getInternalState(clusteredEntityDao, "rowkeyAndValueClasses");
    assertThat(rowAndValueClases.left).isSameAs(Integer.class);
    assertThat(rowAndValueClases.right).isSameAs(String.class);
  }