예제 #1
0
  /** ディレクトリ内にファイルのみがある場合。 */
  @Test
  public void testSimple() throws Exception {
    long cur = System.currentTimeMillis();

    // a/1
    // a/2
    File frd = tempdir.newFolder("a");
    File fr1 = tempdir.newFile("a/1");
    touch(fr1, "1", cur);
    File fr2 = tempdir.newFile("a/2");
    touch(fr2, "22", cur);

    // b/2
    // b/3
    File tod = tempdir.newFolder("b");
    File to2 = tempdir.newFile("b/2");
    touch(to2, "22", cur);
    File to3 = tempdir.newFile("b/3");
    touch(to3, "333", cur);

    BackuperEx target = new BackuperEx(frd, tod);

    target.doCompare(System.out);

    assertEquals(Arrays.asList(new File[] {fr1}), target.fromOnlyList);
    assertEquals(makeFilePairList(new File[] {fr2, to2}), target.sameList);
    assertEquals(Arrays.asList(new File[] {to3}), target.toOnlyList);
  }
  /**
   * This tests whether the RocksDB backends uses the temp directories that are provided from the
   * {@link Environment} when no db storage path is set.
   *
   * @throws Exception
   */
  @Test
  public void testUseTempDirectories() throws Exception {
    String checkpointPath = tempFolder.newFolder().toURI().toString();
    RocksDBStateBackend rocksDbBackend = new RocksDBStateBackend(checkpointPath);

    File dir1 = tempFolder.newFolder();
    File dir2 = tempFolder.newFolder();

    File[] tempDirs = new File[] {dir1, dir2};

    assertNull(rocksDbBackend.getDbStoragePaths());

    Environment env = getMockEnvironment(tempDirs);
    RocksDBKeyedStateBackend<Integer> keyedBackend =
        (RocksDBKeyedStateBackend<Integer>)
            rocksDbBackend.createKeyedStateBackend(
                env,
                env.getJobID(),
                "test_op",
                IntSerializer.INSTANCE,
                1,
                new KeyGroupRange(0, 0),
                env.getTaskKvStateRegistry());

    File instanceBasePath = keyedBackend.getInstanceBasePath();
    assertThat(
        instanceBasePath.getAbsolutePath(),
        anyOf(startsWith(dir1.getAbsolutePath()), startsWith(dir2.getAbsolutePath())));
  }
예제 #3
0
  @Before
  public void setUp() throws Exception {
    server = mock(Server.class);
    container = mock(Container.class);
    when(server.getContainer()).thenReturn(container);
    systemEnvironment = mock(SystemEnvironment.class);
    when(systemEnvironment.getServerPort()).thenReturn(1234);
    when(systemEnvironment.getSslServerPort()).thenReturn(4567);
    when(systemEnvironment.keystore()).thenReturn(temporaryFolder.newFolder());
    when(systemEnvironment.truststore()).thenReturn(temporaryFolder.newFolder());
    when(systemEnvironment.getWebappContextPath()).thenReturn("context");
    when(systemEnvironment.getCruiseWar()).thenReturn("cruise.war");
    when(systemEnvironment.getParentLoaderPriority()).thenReturn(true);
    when(systemEnvironment.useCompressedJs()).thenReturn(true);
    when(systemEnvironment.useNioSslSocket()).thenReturn(true);
    when(systemEnvironment.getListenHost()).thenReturn("localhost");
    when(systemEnvironment.getParentLoaderPriority()).thenReturn(false);
    when(systemEnvironment.get(SystemEnvironment.RESPONSE_BUFFER_SIZE)).thenReturn(1000);
    when(systemEnvironment.get(SystemEnvironment.IDLE_TIMEOUT)).thenReturn(2000);
    when(systemEnvironment.getJettyConfigFile()).thenReturn(new File("foo"));

    sslSocketFactory = mock(SSLSocketFactory.class);
    when(sslSocketFactory.getSupportedCipherSuites()).thenReturn(new String[] {});
    goJetty6CipherSuite = mock(GoJetty6CipherSuite.class);
    when(goJetty6CipherSuite.getExcludedCipherSuites()).thenReturn(new String[] {"CS1", "CS2"});
    configuration = mock(Jetty6GoWebXmlConfiguration.class);
    jetty6Server =
        new Jetty6Server(
            systemEnvironment, "pwd", sslSocketFactory, server, goJetty6CipherSuite, configuration);
  }
예제 #4
0
 @Before
 public void setUpRepos() throws Exception {
   buckRepoRoot = temp.newFolder().toPath();
   thirdPartyRelative = Paths.get("third-party").resolve("java");
   thirdParty = buckRepoRoot.resolve(thirdPartyRelative);
   localRepo = temp.newFolder().toPath();
   resolver =
       new Resolver(buckRepoRoot, thirdPartyRelative, localRepo, httpd.getUri("/").toString());
 }
예제 #5
0
파일: Tools.java 프로젝트: jaanek/jrds
  public static final PropertiesManager makePm(TemporaryFolder testFolder, String... props)
      throws IOException {
    PropertiesManager pm = new PropertiesManager();
    pm.setProperty("tmpdir", testFolder.newFolder("tmp").getCanonicalPath());
    pm.setProperty("configdir", testFolder.newFolder("config").getCanonicalPath());
    pm.setProperty("rrddir", testFolder.newFolder("rrddir").getCanonicalPath());
    pm.setProperty("autocreate", "true");

    return finishPm(pm, props);
  }
예제 #6
0
  private void setUpGeogig(GeogigCLI cli) throws Exception {
    final File userhome = tempFolder.newFolder("mockUserHomeDir");
    final File workingDir = tempFolder.newFolder("mockWorkingDir");
    tempFolder.newFolder("mockWorkingDir", ".geogig");

    final Platform platform = mock(Platform.class);
    when(platform.pwd()).thenReturn(workingDir);
    when(platform.getUserHome()).thenReturn(userhome);

    cli.setPlatform(platform);
  }
예제 #7
0
  @Before
  public final void setUp() {
    final File userhome = tempFolder.newFolder("mockUserHomeDir");

    final File workingDir = tempFolder.newFolder("mockWorkingDir");
    tempFolder.newFolder("mockWorkingDir", ".geogig");

    final Platform platform = mock(Platform.class);
    when(platform.getUserHome()).thenReturn(userhome);
    when(platform.pwd()).thenReturn(workingDir);

    config = createDatabase(platform);
  }
예제 #8
0
 private SonarRunner configureRunner(String projectDir, String... props) throws IOException {
   SonarRunner runner =
       SonarRunner.create(
           ItUtils.projectDir(projectDir),
           "sonar.working.directory",
           temp.newFolder().getAbsolutePath(),
           "sonar.report.export.path",
           "sonar-report.json",
           "sonar.userHome",
           temp.newFolder().getAbsolutePath());
   runner.setProperties(props);
   return runner;
 }
예제 #9
0
 @Before
 public void setUp() {
   folder.newFolder("scaffolder");
   folder.newFolder("scaffolder-existing");
   folder.newFolder("scaffolder-existing-custom-lc");
   folder.newFolder("scaffolder-existing-old");
   folder.newFolder("scaffolder-existing-old-address");
   folder.newFolder("scaffolder-existing-custom-and-normal-lc");
   folder.newFolder("custom-domain");
   folder.newFolder("empty-domain");
   folder.newFolder("custom-domain-multiple-lc");
 }
예제 #10
0
  /** 同一ファイル名、同一時刻でも、完全に比較する場合のテスト。 */
  @Test
  public void testSame() throws Exception {
    long current = System.currentTimeMillis() - 10000L;
    File a = tempdir.newFolder("a");
    File a1 = tempdir.newFile("a/1");
    touch(a1, "data 11", current);
    File a2 = tempdir.newFile("a/2");
    touch(a2, "data 2222", current);
    File a3 = tempdir.newFile("a/3");
    touch(a3, "data 333333", current);

    current += 10000L;
    File b = tempdir.newFolder("b");
    File b1 = tempdir.newFile("b/1");
    touch(b1, "data 11", a1.lastModified());
    File b2 = tempdir.newFile("b/2");
    touch(b2, "data 1212", a2.lastModified());
    File b3 = tempdir.newFile("b/3");
    touch(b3, "data 131313", a3.lastModified());

    BackuperEx target = new BackuperEx(a, b);

    target.doCompare(System.out);

    assertEquals(new ArrayList<File>(), target.fromOnlyList);
    assertEquals(makeFilePairList(new File[] {a1, b1, a2, b2, a3, b3}), target.sameList);
    assertEquals(new ArrayList<File>(), target.toOnlyList);
    assertEquals(new ArrayList<FilePair>(), target.touchList);
    assertEquals(new ArrayList<File>(), target.moveList);

    target.compareSameList(System.out);

    assertEquals(Arrays.asList(new File[] {a2, a3}), target.fromOnlyList);
    assertEquals(makeFilePairList(new File[] {a1, b1}), target.sameList);
    assertEquals(Arrays.asList(new File[] {b2, b3}), target.toOnlyList);
    assertEquals(new ArrayList<FilePair>(), target.touchList);
    assertEquals(new ArrayList<File>(), target.moveList);

    target.doExecute(System.out);

    assertDirectory(
        b,
        new String[][] {
          {"1", "data 11"},
          {"2", "data 2222"},
          {"3", "data 333333"},
        });
  }
  @Test
  public void pullFileProjectUsingFileMapping() throws Exception {
    PullOptionsImpl opts = mockServerRule.getPullOpts();
    opts.setPullType("trans");
    File pullBaseDir = tempFolder.newFolder("file-pull-test");
    opts.setSrcDir(pullBaseDir);
    opts.setTransDir(pullBaseDir);
    log.debug("pull base dir is: {}", pullBaseDir);
    // we define our own rule
    opts.setFileMappingRules(
        Lists.newArrayList(
            new FileMappingRule("**/*.odt", "{extension}/{path}/{locale}/{filename}.{extension}"),
            new FileMappingRule(
                "**/*.ods", "{extension}/{locale_with_underscore}/{filename}.{extension}")));

    InputStream sourceFileStream = IOUtils.toInputStream("source content", Charsets.UTF_8);
    InputStream transFileStream = IOUtils.toInputStream("translation content", Charsets.UTF_8);
    ArrayList<ResourceMeta> remoteDocList =
        Lists.newArrayList(new ResourceMeta("test-ods.ods"), new ResourceMeta("test-odt.odt"));

    RawPullCommand pullCommand =
        mockServerRule.createRawPullCommand(remoteDocList, sourceFileStream, transFileStream);

    pullCommand.run();

    assertThat(new File(pullBaseDir, "odt/zh-CN/test-odt.odt").exists(), is(true));
    assertThat(new File(pullBaseDir, "ods/zh_CN/test-ods.ods").exists(), is(true));
  }
  @Test
  public void test_add_different() {
    MonitoringDataStorage monitoringDataStorage;
    try {
      monitoringDataStorage =
          new MonitoringDataStorage(testFolder.newFolder("test"), "copperMonitorLog");
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    final MonitoringDataAccessor monitoringDataAccesor =
        new MonitoringDataAccessor(monitoringDataStorage);
    final MonitoringDataAdder monitoringDataAdder = new MonitoringDataAdder(monitoringDataStorage);
    final AdapterWfLaunchInfo adapterWfLaunch = new AdapterWfLaunchInfo();
    adapterWfLaunch.setTimestamp(new Date());
    monitoringDataAdder.addMonitoringData(adapterWfLaunch);
    final LogEvent logEvent = new LogEvent();
    logEvent.setTime(new Date());
    monitoringDataAdder.addMonitoringData(logEvent);

    assertEquals(
        1,
        monitoringDataAccesor
            .getList(
                new TypeFilter<AdapterWfLaunchInfo>(AdapterWfLaunchInfo.class), null, null, 1000)
            .size());
    assertEquals(
        1,
        monitoringDataAccesor
            .getList(new TypeFilter<LogEvent>(LogEvent.class), null, null, 1000)
            .size());
  }
예제 #13
0
  @Before
  public void setUp() throws Exception {
    mojo = new CreateMojo();

    project = folder.newFolder("my-project");
    src = new File(project, "src");
    main = new File(src, "main");
    app = new File(main, "app");
    api = new File(main, "api");
    lala = new File(api, "lala");

    api.mkdirs();
    app.mkdirs();
    lala.mkdirs();

    // Do
    apiFile = new File(api, "hello.yaml");
    apiFile.createNewFile();
    new File(api, "bye.yml").createNewFile();
    new File(lala, "wow.yaml").createNewFile();

    // Don't
    new File(main, "dont-read.yaml").createNewFile();

    // TODO mock properties like this:
    setVariableValueToObject(mojo, "buildContext", new DefaultBuildContext());
    setVariableValueToObject(mojo, "log", mock(Log.class));
  }
예제 #14
0
 @Before
 public void prepare() throws IOException {
   baseDir = temp.newFolder();
   fs = new DefaultFileSystem(baseDir.toPath());
   input = mock(BlameInput.class);
   when(input.fileSystem()).thenReturn(fs);
 }
 @Before
 public void before() throws IOException {
   baseDir = temp.newFolder();
   fs.setBaseDir(baseDir);
   scmActivitySensor =
       new ScmActivitySensor(conf, blameVersionSelector, urlChecker, timeMachine, fs);
 }
  /**
   * Set up an embedded ZooKeeper instance backed by a temporary directory. The setup procedure also
   * allocates a port that is free for the ZooKeeper server so that you should be able to run
   * multiple instances of this test.
   */
  @Before
  public void setup() throws Exception {
    File rootDir = temp.newFolder("zk-test");
    zkport = Net.getFreePort();

    log.info("EmbeddedZooKeeper rootDir=" + rootDir.getCanonicalPath() + ", port=" + zkport);

    // Set up and initialize the embedded ZooKeeper
    ezk = new EmbeddedZooKeeper(rootDir, zkport);
    ezk.init();

    // Set up a zookeeper client that we can use for inspection
    final CountDownLatch connectedLatch = new CountDownLatch(1);

    zk =
        new ZooKeeper(
            "localhost:" + zkport,
            1000,
            new Watcher() {
              public void process(WatchedEvent event) {
                if (event.getState() == Event.KeeperState.SyncConnected) {
                  connectedLatch.countDown();
                }
              }
            });
    connectedLatch.await();

    System.out.println("ZooKeeper port is " + zkport);
  }
예제 #17
0
  @Test
  public void testDynamicProperties() throws IOException {

    Map<String, String> map = new HashMap<String, String>(System.getenv());
    File tmpFolder = tmp.newFolder();
    File fakeConf = new File(tmpFolder, "flink-conf.yaml");
    fakeConf.createNewFile();
    map.put(ConfigConstants.ENV_FLINK_CONF_DIR, tmpFolder.getAbsolutePath());
    TestBaseUtils.setEnv(map);
    FlinkYarnSessionCli cli = new FlinkYarnSessionCli("", "", false);
    Options options = new Options();
    cli.addGeneralOptions(options);
    cli.addRunOptions(options);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
      cmd =
          parser.parse(
              options,
              new String[] {"run", "-j", "fake.jar", "-n", "15", "-D", "akka.ask.timeout=5 min"});
    } catch (Exception e) {
      e.printStackTrace();
      Assert.fail("Parsing failed with " + e.getMessage());
    }

    AbstractYarnClusterDescriptor flinkYarnDescriptor = cli.createDescriptor(null, cmd);

    Assert.assertNotNull(flinkYarnDescriptor);

    Map<String, String> dynProperties =
        FlinkYarnSessionCli.getDynamicProperties(flinkYarnDescriptor.getDynamicPropertiesEncoded());
    Assert.assertEquals(1, dynProperties.size());
    Assert.assertEquals("5 min", dynProperties.get("akka.ask.timeout"));
  }
  @Test
  public void testClasspathSetupNone() throws Exception {
    System.clearProperty(HiveConf.ConfVars.HADOOPBIN.toString());
    String originalHadoopBin = new HiveConf().get(HiveConf.ConfVars.HADOOPBIN.toString());

    List<String> inputURLs = Lists.newArrayList();
    inputURLs.add("/usr/lib/hbase/lib/hbase-hadoop2-compat-0.96.1.2.0.11.0-1-hadoop2.jar");
    inputURLs.add("/usr/lib/hbase/lib/hbase-thrift-0.96.1.2.0.11.0-1-hadoop2.jar");
    inputURLs.add("/usr/lib/hadoop/hadoop-common-2.2.0.2.0.11.0-1-tests.jar");

    HiveConf hiveConf = new HiveConf();
    LocalMapreduceClasspathSetter classpathSetter =
        new LocalMapreduceClasspathSetter(
            hiveConf, TEMP_FOLDER.newFolder().getAbsolutePath(), ImmutableList.<String>of());

    for (String url : inputURLs) {
      classpathSetter.accept(url);
    }

    Assert.assertTrue(classpathSetter.getHbaseProtocolJarPaths().isEmpty());

    classpathSetter.setupClasspathScript();

    String newHadoopBin = new HiveConf().get(HiveConf.ConfVars.HADOOPBIN.toString());
    Assert.assertEquals(originalHadoopBin, newHadoopBin);
    System.clearProperty(HiveConf.ConfVars.HADOOPBIN.toString());
  }
  @Test
  public void testCorrectStatusUpdatesAreSent()
      throws FileNotFoundException, NDPReadException, ImageTilingException {
    ImageInformation info = createImageInformation();

    // setup mocks so we get 3x4 tiles
    when(tilePositions.getTileXPositions()).thenReturn(Arrays.asList(new Long[] {1L, 2L, 3L}));
    when(tilePositions.getTileYPositions()).thenReturn(Arrays.asList(new Long[] {5L, 7L, 9L, 11L}));
    when(tilePositions.getTileWidthInPixels()).thenReturn(20);
    when(tilePositions.getTileHeightInPixels()).thenReturn(10);
    when(tilePositions.getTotalNumberOfTiles()).thenReturn(12);

    File outputDirectory = temporaryFolder.newFolder("output");

    splitter.tileImage("testfile", tilePositions, info, 30, outputDirectory, statusUpdater);

    // check that we got updates for tiles 1-12 being completed
    verify(statusUpdater).setNumberOfTiles(12);
    verify(statusUpdater).setNumberOfTilesCompleted(0);
    verify(statusUpdater).setNumberOfTilesCompleted(1);
    verify(statusUpdater).setNumberOfTilesCompleted(2);
    verify(statusUpdater).setNumberOfTilesCompleted(3);
    verify(statusUpdater).setNumberOfTilesCompleted(4);
    verify(statusUpdater).setNumberOfTilesCompleted(5);
    verify(statusUpdater).setNumberOfTilesCompleted(6);
    verify(statusUpdater).setNumberOfTilesCompleted(7);
    verify(statusUpdater).setNumberOfTilesCompleted(8);
    verify(statusUpdater).setNumberOfTilesCompleted(9);
    verify(statusUpdater).setNumberOfTilesCompleted(10);
    verify(statusUpdater).setNumberOfTilesCompleted(11);
    verify(statusUpdater).setNumberOfTilesCompleted(12);
    verifyNoMoreInteractions(statusUpdater);
  }
  @Test
  public void nothing_to_do_when_no_events_in_report() throws Exception {
    dbTester.prepareDbUnit(getClass(), "nothing_to_do_when_no_events_in_report.xml");

    File reportDir = temp.newFolder();
    BatchReportWriter writer = new BatchReportWriter(reportDir);
    writer.writeMetadata(
        BatchReport.Metadata.newBuilder()
            .setRootComponentRef(1)
            .setProjectKey("PROJECT_KEY")
            .setAnalysisDate(150000000L)
            .build());

    writer.writeComponent(
        BatchReport.Component.newBuilder()
            .setRef(1)
            .setType(Constants.ComponentType.PROJECT)
            .setUuid("ABCD")
            .build());

    step.execute(
        new ComputationContext(new BatchReportReader(reportDir), mock(ComponentDto.class)));

    dbTester.assertDbUnit(getClass(), "nothing_to_do_when_no_events_in_report.xml", "events");
  }
  @Test
  public void emptyDocumentTest() throws Exception {
    File tmpDir = folder.newFolder();

    CollectionReaderDescription reader =
        CollectionReaderFactory.createReaderDescription(
            TextReader.class,
            TextReader.PARAM_SOURCE_LOCATION,
            "src/test/resources/empty/",
            TextReader.PARAM_LANGUAGE,
            "en",
            TextReader.PARAM_PATTERNS,
            "empty*.txt");

    AnalysisEngineDescription segmenter =
        AnalysisEngineFactory.createEngineDescription(BreakIteratorSegmenter.class);

    AnalysisEngineDescription metaCollector =
        AnalysisEngineFactory.createEngineDescription(
            LuceneNGramMetaCollector.class, LuceneNGramDFE.PARAM_LUCENE_DIR, tmpDir);

    for (JCas jcas : new JCasIterable(reader, segmenter, metaCollector)) {
      //            System.out.println(jcas.getDocumentText().length());
    }
  }
예제 #22
0
 @Before
 public void prepare() throws IOException {
   baseDir = temp.newFolder();
   metricFinder = mock(MetricFinder.class);
   sensor = new MeasureSensor(metricFinder);
   context = SensorContextTester.create(baseDir);
 }
예제 #23
0
  @Test
  @Category(UnitTest.class)
  public void readSplitsPath() throws IOException {
    File splitFolder = folder.newFolder(testName.getMethodName());
    File splitfile = new File(splitFolder, "partitions");

    FileOutputStream stream = new FileOutputStream(splitfile);
    PrintWriter writer = new PrintWriter(stream);

    writer.println(generated.length);
    for (int i = 0; i < generated.length; i++) {
      writer.print(generated[i]);
      writer.print(" ");
      writer.println(i);
    }

    writer.close();
    stream.close();

    Splits splits = new PartitionerSplit();
    splits.readSplits(new Path(splitFolder.toURI()));

    PartitionerSplit.PartitionerSplitInfo[] si =
        (PartitionerSplit.PartitionerSplitInfo[]) splits.getSplits();

    Assert.assertEquals("Splits length not correct", generated.length, si.length);
    for (int i = 0; i < generated.length; i++) {
      Assert.assertEquals("Splits entry not correct", generated[i].longValue(), si[i].getTileId());
    }
  }
예제 #24
0
  @Test
  @Category(UnitTest.class)
  public void writeSplitsPath() throws IOException {
    Splits splits = new PartitionerSplit();
    splits.generateSplits(new TestGenerator());

    File splitfile = folder.newFolder(testName.getMethodName());

    splits.writeSplits(new Path(splitfile.toURI()));

    FileInputStream in = new FileInputStream(new File(splitfile, "partitions"));
    Scanner reader = new Scanner(in);

    Assert.assertEquals("Wrong number written", generated.length, reader.nextInt());

    PartitionerSplit.PartitionerSplitInfo[] si =
        (PartitionerSplit.PartitionerSplitInfo[]) splits.getSplits();

    for (int i = 0; i < generated.length; i++) {
      Assert.assertEquals("Splits entry not correct", generated[i].longValue(), reader.nextLong());
      Assert.assertEquals("Partition entry not correct", i, reader.nextLong());
    }

    reader.close();
  }
 @Before
 public void prepare() throws IOException {
   tester =
       BatchMediumTester.builder()
           .bootstrapProperties(
               ImmutableMap.of(
                   CoreProperties.ANALYSIS_MODE,
                   CoreProperties.ANALYSIS_MODE_ISSUES,
                   CoreProperties.GLOBAL_WORKING_DIRECTORY,
                   temp.newFolder().getAbsolutePath()))
           .registerPlugin("xoo", new XooPlugin())
           .addQProfile("xoo", "Sonar Way")
           .addRules(new XooRulesDefinition())
           .addRule("manual:MyManualIssue", "manual", "MyManualIssue", "My manual issue")
           .addRule("manual:MyManualIssueDup", "manual", "MyManualIssue", "My manual issue")
           .addActiveRule(
               "xoo", "OneIssuePerLine", null, "One issue per line", "MAJOR", null, "xoo")
           .addActiveRule(
               "xoo", "OneIssueOnDirPerFile", null, "OneIssueOnDirPerFile", "MAJOR", null, "xoo")
           .addActiveRule(
               "xoo", "OneIssuePerModule", null, "OneIssuePerModule", "MAJOR", null, "xoo")
           .addActiveRule("manual", "MyManualIssue", null, "My manual issue", "MAJOR", null, null)
           .setAssociated(false)
           .build();
   tester.start();
 }
  @Test
  public void keep_one_event_by_version() throws Exception {
    dbTester.prepareDbUnit(getClass(), "keep_one_event_by_version.xml");

    File reportDir = temp.newFolder();
    BatchReportWriter writer = new BatchReportWriter(reportDir);
    writer.writeMetadata(
        BatchReport.Metadata.newBuilder()
            .setRootComponentRef(1)
            .setProjectKey("PROJECT_KEY")
            .setAnalysisDate(150000000L)
            .build());

    writer.writeComponent(
        BatchReport.Component.newBuilder()
            .setRef(1)
            .setType(Constants.ComponentType.PROJECT)
            .setUuid("ABCD")
            .setSnapshotId(1001L)
            .setVersion("1.5-SNAPSHOT")
            .build());

    step.execute(
        new ComputationContext(new BatchReportReader(reportDir), mock(ComponentDto.class)));

    dbTester.assertDbUnit(getClass(), "keep_one_event_by_version-result.xml", "events");
  }
  @Test
  public void shouldPopulatePropertiesContentWithCustomWorkspace() throws Exception {
    final String customWorkspaceValue = tmp.newFolder().getAbsolutePath();
    String customEnvVarName = "materialize_workspace_path";
    String customEnvVarValue = "${WORKSPACE}/materialize_workspace";

    FreeStyleProject project = j.createFreeStyleProject();
    project.setCustomWorkspace(customWorkspaceValue);

    EnvVars.masterEnvVars.remove("WORKSPACE"); // ensure build node don't have such var already

    EnvInjectBuildWrapper envInjectBuildWrapper = new EnvInjectBuildWrapper();
    envInjectBuildWrapper.setInfo(withPropContent(customEnvVarName + "=" + customEnvVarValue));
    project.getBuildWrappersList().add(envInjectBuildWrapper);

    FreeStyleBuild build = j.buildAndAssertSuccess(project);

    // Retrieve build workspace
    String buildWorkspaceValue = build.getWorkspace().getRemote();
    assertThat(
        "1. Should see actual ws equal to custom",
        buildWorkspaceValue,
        equalTo(customWorkspaceValue));

    // Compute value with workspace
    String expectedCustomEnvVarValue =
        replaceMacro(customEnvVarValue, of("WORKSPACE", buildWorkspaceValue));

    assertThat(
        "2. Property should be resolved with custom ws in build",
        build,
        withEnvInjectAction(map(hasEntry(customEnvVarName, expectedCustomEnvVarValue))));
  }
예제 #28
0
  @Test
  public void testConsumer() throws Exception {
    EventloopStub eventloop = new EventloopStub();
    eventloop.setTimestamp(
        new LocalDateTime("1970-01-01T00:00:00").toDateTime(DateTimeZone.UTC).getMillis());
    ExecutorService executor = Executors.newCachedThreadPool();
    Path dir = temporaryFolder.newFolder().toPath();
    LogFileSystemImpl fileSystem = new LogFileSystemImpl(eventloop, executor, dir);
    LogManager<String> logManager =
        new LogManagerImpl<>(eventloop, fileSystem, BufferSerializers.stringSerializer());
    new StreamProducers.OfIterator<>(eventloop, Arrays.asList("1", "2", "3").iterator())
        .streamTo(logManager.consumer("p1"));
    eventloop.run();
    eventloop.setTimestamp(
        new LocalDateTime("1970-01-01T00:50:00").toDateTime(DateTimeZone.UTC).getMillis());
    new StreamProducers.OfIterator<>(eventloop, Arrays.asList("4", "5", "6").iterator())
        .streamTo(logManager.consumer("p1"));
    eventloop.run();
    eventloop.setTimestamp(
        new LocalDateTime("1970-01-01T01:50:00").toDateTime(DateTimeZone.UTC).getMillis());
    new StreamProducers.OfIterator<>(eventloop, Arrays.asList("7", "8", "9").iterator())
        .streamTo(logManager.consumer("p1"));
    eventloop.run();
    StreamProducer<String> p1 =
        logManager.producer("p1", new LogFile("1970-01-01_00", 1), 0L, null);

    StreamConsumers.ToList<String> consumerToList = new StreamConsumers.ToList<>(eventloop);
    p1.streamTo(consumerToList);
    eventloop.run();
    System.out.println(consumerToList.getList());
    //		System.out.println(p1.getLogPosition());
  }
  /**
   * Test method for {@link SubtitleProvider#loadSubtitles(Path)}. Check that multiple subtitles are
   * loaded.
   *
   * @throws IOException if there was an I/O error.
   */
  @Test
  public void testLoadSubtitles() throws IOException {
    final SubtitleFormat subtitleFormat = mock(SubtitleFormat.class);
    final SubtitleReader subtitleReader = mock(SubtitleReader.class);
    final SubtitleFile subtitleFile = mock(SubtitleFile.class);
    final SubtitleFile secondSubtitle = mock(SubtitleFile.class);
    final Path folder = subtitleFolder.newFolder().toPath();
    final Path file = folder.resolve("single.srt");
    final Path second = folder.resolve("other.srt");
    Files.createFile(file);
    Files.createFile(second);
    Files.createFile(folder.resolve("test.sub"));

    when(subtitleFormatManager.getFormatByPath(file))
        .thenReturn(new HashSet<>(Arrays.asList(subtitleFormat)));
    when(subtitleFormatManager.getFormatByPath(second))
        .thenReturn(new HashSet<>(Arrays.asList(subtitleFormat)));
    when(subtitleFormat.getReader()).thenReturn(subtitleReader);
    when(subtitleReader.readFile(file)).thenReturn(subtitleFile);
    when(subtitleReader.readFile(second)).thenReturn(secondSubtitle);
    final Map<SubtitleFile, SubtitleFormat> subtitles = subtitleProvider.loadSubtitles(folder);
    assertEquals(2, subtitles.size());
    //		final Entry<SubtitleFile, SubtitleFormat> loaded = subtitles.entrySet().iterator().next();
    //		assertEquals(subtitleFile, loaded.getKey());
    //		assertEquals(subtitleFormat, loaded.getValue());
  }
  @Test
  public void testPredefinedAndOptionsFactory() throws Exception {
    String checkpointPath = tempFolder.newFolder().toURI().toString();
    RocksDBStateBackend rocksDbBackend = new RocksDBStateBackend(checkpointPath);

    assertEquals(PredefinedOptions.DEFAULT, rocksDbBackend.getPredefinedOptions());

    rocksDbBackend.setPredefinedOptions(PredefinedOptions.SPINNING_DISK_OPTIMIZED);
    rocksDbBackend.setOptions(
        new OptionsFactory() {
          @Override
          public DBOptions createDBOptions(DBOptions currentOptions) {
            return currentOptions;
          }

          @Override
          public ColumnFamilyOptions createColumnOptions(ColumnFamilyOptions currentOptions) {
            return currentOptions.setCompactionStyle(CompactionStyle.UNIVERSAL);
          }
        });

    assertEquals(PredefinedOptions.SPINNING_DISK_OPTIMIZED, rocksDbBackend.getPredefinedOptions());
    assertNotNull(rocksDbBackend.getOptions());
    assertEquals(CompactionStyle.UNIVERSAL, rocksDbBackend.getColumnOptions().compactionStyle());
  }