@Before
 public void setup() throws IOException {
   file = folder.newFile("log.txt");
   pathToEmptyFile = file.getAbsolutePath();
   File file2 = folder.newFile("content.txt");
   writeContentTo(file2, "Some content");
 }
Ejemplo n.º 2
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);
  }
Ejemplo n.º 3
0
  /**
   * Setup input data
   *
   * @throws IOException
   */
  @Before
  public void setup() throws IOException {
    String exampleList =
        "n00007846_41	http://static.flickr.com/3423/3788747850_c9653099c2.jpg" + "\n"
        //		+
        //		"t3st	http://farm5.staticflickr.com/4013/4214727934_0ff14790f8.jpg" + "\n" +
        //		"test	http://farm3.static.flickr.com/2412/2364526179_6d19772ac4_b.jpg" + "\n" +
        //		"n00007846_383	http://secrets-of-flirting.com/girlfriend.jpg" + "\n" +
        //		"n00007846_499	http://z.about.com/d/kidstvmovies/1/0/a/8/sm3005.jpg" + "\n" +
        //		"n00007846_543	http://static.flickr.com/3455/3372482944_244c25c45f.jpg" + "\n" +
        //		"n00007846_612	http://static.flickr.com/3592/3376795744_e89f42f5c5.jpg" + "\n" +
        //		"n00007846_658	http://static.flickr.com/122/286394792_9232f00db3.jpg" + "\n" +
        //		"n00007846_709	http://static.flickr.com/3299/3621111660_bcb5907cb0.jpg" + "\n" +
        //		"n00007846_839	http://static.flickr.com/3628/3376796820_a1dd3e2ed7.jpg" + "\n" +
        //		"n00007846_846	http://static.flickr.com/3383/3653165852_8f8a06eaa6.jpg" + "\n" +
        //		"Special	designedToFail.com/image.wang" + "\n" +
        //		"Failcakes
        //	http://www.wave.co.nz/~bodyline/pages/catalogue/wetsuits/mens_summer/images/long-sleeve-inferno-L.jpg" + "\n" +
        //		"n00007846_991	http://www.cinema.bg/sff/images-person/David-Lanzmann.gif"
        ;

    exampleFile = folder.newFile("images.txt");

    PrintWriter pw = new PrintWriter(new FileWriter(exampleFile));
    pw.println(exampleList);
    pw.flush();
    pw.close();

    exampleOut = folder.newFile("example.images");
    exampleOut.delete();
  }
  @Test
  public void should_include_the_name_of_any_screenshots_where_present() throws Exception {
    TestOutcome testOutcome = TestOutcome.forTest("a_simple_test_case", SomeTestScenario.class);
    String expectedReport =
        "<acceptance-test-run title='A simple test case' name='a_simple_test_case' steps='2' successful='1' failures='1' skipped='0' ignored='0' pending='0' result='FAILURE'>\n"
            + "  <user-story id='net.thucydides.core.reports.integration.WhenGeneratingAnXMLReport.AUserStory' name='A user story' />\n"
            + "  <test-step result='SUCCESS'>\n"
            + "    <screenshots>\n"
            + "      <screenshot image='step_1.png' source='step_1.html'/>\n"
            + "    </screenshots>\n"
            + "    <description>step 1</description>\n"
            + "  </test-step>\n"
            + "  <test-step result='FAILURE'>\n"
            + "    <description>step 2</description>\n"
            + "  </test-step>\n"
            + "</acceptance-test-run>";

    File screenshot = temporaryDirectory.newFile("step_1.png");
    File source = temporaryDirectory.newFile("step_1.html");

    TestStep step1 = TestStepFactory.successfulTestStepCalled("step 1");
    step1.addScreenshot(new ScreenshotAndHtmlSource(screenshot, source));
    testOutcome.recordStep(step1);
    testOutcome.recordStep(TestStepFactory.failingTestStepCalled("step 2"));

    File xmlReport = reporter.generateReportFor(testOutcome);
    String generatedReportText = getStringFrom(xmlReport);

    assertThat(generatedReportText, isSimilarTo(expectedReport));
  }
Ejemplo n.º 5
0
  @Test
  public void testCacheFile() throws Exception {
    final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class);

    final DefaultConfiguration treeWalkerConfig = createCheckConfig(TreeWalker.class);
    treeWalkerConfig.addAttribute("cacheFile", temporaryFolder.newFile().getPath());
    treeWalkerConfig.addChild(checkConfig);

    final DefaultConfiguration checkerConfig = new DefaultConfiguration("configuration");
    checkerConfig.addAttribute("charset", "UTF-8");
    checkerConfig.addChild(treeWalkerConfig);

    final Checker checker = new Checker();
    final Locale locale = Locale.ROOT;
    checker.setLocaleCountry(locale.getCountry());
    checker.setLocaleLanguage(locale.getLanguage());
    checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
    checker.configure(checkerConfig);
    checker.addListener(new BriefLogger(stream));

    final String pathToEmptyFile = temporaryFolder.newFile("file.java").getPath();
    final String[] expected = {};

    verify(checker, pathToEmptyFile, pathToEmptyFile, expected);
    // one more time to reuse cache
    verify(checker, pathToEmptyFile, pathToEmptyFile, expected);
  }
  @Test
  public void findsCorrectFile() throws Exception {
    final File directory = testFolder.getRoot();

    final String fileNames[] = new String[] {"other.txt", "my.txt", "a.log", "b.log"};
    for (String fileName : fileNames) {
      testFolder.newFile(fileName);
    }

    final int pidValue = 42;
    final File file = testFolder.newFile("my.pid");
    writeToFile(file, String.valueOf(pidValue));

    final File other = testFolder.newFile("other.pid");
    writeToFile(other, "43");

    final File[] files = directory.listFiles();
    assertEquals(fileNames.length + 2, files.length);

    PidFile pidFile = new PidFile(directory, file.getName());
    assertEquals(file, pidFile.getFile());

    int value = pidFile.readPid();
    assertEquals(pidValue, value);
  }
Ejemplo n.º 7
0
  @Test
  public void testCorrectSettingOfMaxSlots() throws Exception {

    File confFile = tmp.newFile("flink-conf.yaml");
    File jarFile = tmp.newFile("test.jar");
    new CliFrontend(tmp.getRoot().getAbsolutePath());

    String[] params = new String[] {"-yn", "2", "-ys", "3", jarFile.getAbsolutePath()};

    RunOptions runOptions = CliFrontendParser.parseRunCommand(params);

    FlinkYarnSessionCli yarnCLI = new TestCLI("y", "yarn");

    AbstractYarnClusterDescriptor descriptor =
        yarnCLI.createDescriptor("", runOptions.getCommandLine());

    // each task manager has 3 slots but the parallelism is 7. Thus the slots should be increased.
    Assert.assertEquals(3, descriptor.getTaskManagerSlots());
    Assert.assertEquals(2, descriptor.getTaskManagerCount());

    Configuration config = new Configuration();
    CliFrontend.setJobManagerAddressInConfig(config, new InetSocketAddress("test", 9000));
    ClusterClient client = new TestingYarnClusterClient(descriptor, config);
    Assert.assertEquals(6, client.getMaxSlots());
  }
Ejemplo n.º 8
0
 private void createTempFiles() throws IOException {
   for (int i = 0; i < MUSIC_FILE_NUMBER; i++) {
     File file = tempSourceFolder.newFile("test_music_file_" + i + ".mp3");
     file.createNewFile();
     File imageFile = tempSourceFolder.newFile("test_image_file_" + i + ".jpeg");
     imageFile.createNewFile();
   }
 }
  @Before
  public void setUp() throws IOException {
    temporaryFolder.newFile("context1.context");
    temporaryFolder.newFile("context2.context");
    temporaryFolder.newFile("context3.context");
    temporaryFolder.newFile("unknown.file");

    persistenceService = new ContextFilePersistenceService();
    persistenceService.setStorageFolderPath(temporaryFolder.getRoot().getAbsolutePath());
  }
Ejemplo n.º 10
0
  @Before
  public void before() throws Exception {
    topSongsResultPath = tempFolder.newFile().toURI().toString();
    communitiesResultPath = tempFolder.newFile().toURI().toString();

    File tripletsFile = tempFolder.newFile();
    Files.write(MusicProfilesData.USER_SONG_TRIPLETS, tripletsFile, Charsets.UTF_8);
    tripletsPath = tripletsFile.toURI().toString();

    File mismatchesFile = tempFolder.newFile();
    Files.write(MusicProfilesData.MISMATCHES, mismatchesFile, Charsets.UTF_8);
    mismatchesPath = mismatchesFile.toURI().toString();
  }
  @Test
  public void should_have_a_meaningful_filename() throws Exception {
    TestOutcome testOutcome = TestOutcome.forTest("a_simple_test_case", SomeTestScenario.class);

    TestStep step1 = TestStepFactory.successfulTestStepCalled("step 1");
    File screenshot = temporaryDirectory.newFile("step_1.png");
    File source = temporaryDirectory.newFile("step_1.html");
    step1.addScreenshot(new ScreenshotAndHtmlSource(screenshot, source));
    testOutcome.recordStep(step1);

    File xmlReport = reporter.generateReportFor(testOutcome);
    assertThat(xmlReport.getName(), is("a_user_story_a_simple_test_case.xml"));
  }
Ejemplo n.º 12
0
  @Test
  /**
   * Reads from TRIG with Jena API into Dataset 1, transforms one named graph from that Dataset into
   * Signingframework's API GraphCollection and writes it with Signingframework's API, reads the
   * result with Jena API into Dataset 2, and checks if the specified named graph model from Dataset
   * 1 is isomorphic with the same named graph model from Dataset 2.
   */
  public void modelToGraphCollectionTest() throws Exception {

    for (String resourceFile : RESOURCE_FILES) {

      // prepare the input Dataset containg the Model to be converted
      InputStream is = this.getClass().getResourceAsStream(resourceFile);
      File outFile = testFolder.newFile();
      // use this when debugging:
      // File outFile = File.createTempFile("won", ".trig");
      // System.out.println(outFile);
      Dataset dataset = DatasetFactory.createMem();
      RDFDataMgr.read(dataset, is, RDFFormat.TRIG.getLang());
      is.close();

      // test the convertion from the Model to the NamedGraph
      String modelName = dataset.listNames().next();
      Model model = dataset.getNamedModel(modelName);
      // the method to be tested
      GraphCollection gc = ModelConverter.modelToGraphCollection(modelName, dataset);
      TriGPlusWriter.writeFile(gc, outFile.getAbsolutePath(), false);

      // check that the resulting graph collection is a representation
      // of the converted model. For this, read the resulting graph collection
      // as a Model with Jena API
      InputStream is2 = new FileInputStream(outFile);
      Dataset dataset2 = DatasetFactory.createMem();
      RDFDataMgr.read(dataset2, is2, RDFFormat.TRIG.getLang());
      is2.close();
      Model model2 = dataset2.getNamedModel(modelName);
      File outFile2 = testFolder.newFile();
      // use this when debugging:
      // File outFile2 = File.createTempFile("won", ".trig");
      // System.out.println(outFile2);
      OutputStream os = new FileOutputStream(outFile2);
      RDFDataMgr.write(os, dataset2, RDFFormat.TRIG.getLang());
      os.close();

      // check that the model obtained from resulting graph collection is
      // a representation of the original converted model.
      Assert.assertTrue(model.listStatements().hasNext() && model2.listStatements().hasNext());
      Assert.assertTrue(model.isIsomorphicWith(model2));
    }
  }
Ejemplo n.º 13
0
  @Before
  public void createTestFiles() throws IOException {
    SOME_FILE = test_folder.newFile();
    FileUtils.writeLines(SOME_FILE, Arrays.asList(SOME_FILE_LINE1, SOME_FILE_LINE2));

    OTHER_FILE = test_folder.newFile();
    FileUtils.writeLines(
        OTHER_FILE, Arrays.asList(OTHER_FILE_LINE1, OTHER_FILE_LINE2, OTHER_FILE_LINE3));

    DIRECTORY_DOES_NOT_EXIST = new File("");
    VALID_DIRECTORY_INPUT = new DirectoryInput(test_folder.getRoot());

    NON_READABLE_DIRECTORY = test_folder.newFolder();
    NON_READABLE_DIRECTORY.setReadable(false);
  }
Ejemplo n.º 14
0
  <T> void runTestRead(T[] expected, Coder<T> coder) throws Exception {
    File tmpFile = tmpFolder.newFile("file.txt");
    String filename = tmpFile.getPath();

    try (PrintStream writer = new PrintStream(new FileOutputStream(tmpFile))) {
      for (T elem : expected) {
        byte[] encodedElem = CoderUtils.encodeToByteArray(coder, elem);
        String line = new String(encodedElem);
        writer.println(line);
      }
    }

    Pipeline p = TestPipeline.create();

    TextIO.Read.Bound<T> read;
    if (coder.equals(StringUtf8Coder.of())) {
      TextIO.Read.Bound<String> readStrings = TextIO.Read.from(filename);
      // T==String
      read = (TextIO.Read.Bound<T>) readStrings;
    } else {
      read = TextIO.Read.from(filename).withCoder(coder);
    }

    PCollection<T> output = p.apply(read);

    DataflowAssert.that(output).containsInAnyOrder(expected);
    p.run();
  }
Ejemplo n.º 15
0
  @Before
  public void setup() throws Exception {

    vfs = getVFS();

    folder1.create();
    folder2.create();

    FileUtils.copyURLToFile(
        this.getClass().getResource("/HelloWorld.jar"), folder1.newFile("HelloWorld.jar"));
    FileUtils.copyURLToFile(
        this.getClass().getResource("/HelloWorld.jar"), folder2.newFile("HelloWorld.jar"));

    uri1 = new File(folder1.getRoot(), "HelloWorld.jar").toURI();
    uri2 = folder2.getRoot().toURI();
  }
Ejemplo n.º 16
0
 @Test
 public void testExistingFilePlainOutputToFileWithoutReadAndRwPermissions() throws Exception {
   final File file = temporaryFolder.newFile("file.output");
   // That works fine on Linux/Unix, but ....
   // It's not possible to make a file unreadable in Windows NTFS for owner.
   // http://stackoverflow.com/a/4354686
   // https://github.com/google/google-oauth-java-client/issues/55#issuecomment-69403681
   // assertTrue(file.setReadable(false, false));
   assertTrue(file.setWritable(false, false));
   exit.expectSystemExitWithStatus(-1);
   exit.checkAssertionAfterwards(
       new Assertion() {
         @Override
         public void checkAssertion() throws IOException {
           assertEquals(
               "Permission denied : '" + file.getCanonicalPath() + "'." + System.lineSeparator(),
               systemOut.getLog());
           assertEquals("", systemErr.getLog());
         }
       });
   Main.main(
       "-c",
       getPath("config-classname.xml"),
       "-f",
       "plain",
       "-o",
       file.getCanonicalPath(),
       getPath("InputMain.java"));
 }
  @Test
  public void createCachingXmlDataStore_successful() throws IOException, InterruptedException {
    // create temp file
    final File cache = folder.newFile("uas_temp.xml");
    assertThat(readFile(cache)).isEqualTo("");

    // create caching data store
    final CachingXmlDataStore store =
        CachingXmlDataStore.createCachingXmlDataStore(
            cache, DATA_URL, VERSION_URL, CHARSET, fallback);
    final UpdatingUserAgentStringParserImpl parser = new UpdatingUserAgentStringParserImpl(store);

    Thread.sleep(1000l);
    assertThat(readFile(cache).length() >= 721915).isTrue();

    final long firstLastUpdateCheck = store.getUpdateOperation().getLastUpdateCheck();
    LOG.debug("LastUpdateCheck at: " + firstLastUpdateCheck);
    final long originalInterval = parser.getUpdateInterval();

    // reduce the interval since testing
    LOG.debug("Reducing the update interval during the test.");
    parser.setUpdateInterval(1000l);
    // we have to read to activate the update mechanism
    parser.parse("check for updates");

    Thread.sleep(3000l);
    final long currentLastUpdateCheck = store.getUpdateOperation().getLastUpdateCheck();
    LOG.debug("LastUpdateCheck at: " + currentLastUpdateCheck);
    assertThat(firstLastUpdateCheck < currentLastUpdateCheck).isTrue();

    parser.setUpdateInterval(originalInterval);
  }
Ejemplo n.º 18
0
  @Test
  public void testLimitedView() throws IOException {
    File file = folder.newFile();
    FileChannel chan = new RandomAccessFile(file, "rw").getChannel();
    BinaryIndexTableWriter writer = BinaryIndexTableWriter.create(BinaryFormat.create(), chan, 3);
    writer.writeEntry(12, new int[] {0});
    writer.writeEntry(17, new int[] {1, 3});
    writer.writeEntry(19, new int[] {4, 5});

    MappedByteBuffer buffer = chan.map(FileChannel.MapMode.READ_ONLY, 0, chan.size());
    BinaryIndexTable tbl = BinaryIndexTable.fromBuffer(3, buffer);
    tbl = tbl.createLimitedView(2);
    assertThat(tbl.getKeys(), hasSize(2));
    assertThat(tbl.getKeys(), contains(12L, 17L));
    assertThat(tbl.getEntry(12), contains(0));
    assertThat(tbl.getEntry(17), contains(1));
    assertThat(tbl.getEntry(19), nullValue());
    assertThat(tbl.getEntry(-1), nullValue());

    BinaryIndexTable serializedTbl = SerializationUtils.clone(tbl);
    assertThat(serializedTbl.getKeys(), hasSize(2));
    assertThat(serializedTbl.getKeys(), contains(12L, 17L));
    assertThat(serializedTbl.getEntry(12), contains(0));
    assertThat(serializedTbl.getEntry(17), contains(1));
    assertThat(serializedTbl.getEntry(19), nullValue());
    assertThat(serializedTbl.getEntry(-1), nullValue());
  }
  @Test
  public void test() throws Exception {
    int KEY_COUNT = 1000;
    TemporaryFolder tempFolder = new TemporaryFolder();

    File keyPath = tempFolder.newFile();

    String[] buckets = {"A", "B", "C", "D", "E", "F"};
    String[] keys = new String[KEY_COUNT];
    for (Integer i = 0; i < keys.length; ++i) {
      keys[i] = i.toString();
    }

    KeyJournal journal = new KeyJournal(keyPath, KeyJournal.Mode.WRITE);

    for (String bucket : buckets) {
      for (String key : keys) {
        journal.write(bucket, key);
      }
    }
    journal.close();

    KeyJournal readJournal = new KeyJournal(keyPath, KeyJournal.Mode.READ);

    int readCount = 0;
    for (Key key : readJournal) {
      if (!key.errorKey()) ++readCount;
    }

    assertTrue(readCount == buckets.length * keys.length);
  }
Ejemplo n.º 20
0
 private File getFile(String s) throws Exception {
   File file = folder.newFile(s);
   file.createNewFile();
   InputStream resourceAsStream = ScaffolderTest.class.getClassLoader().getResourceAsStream(s);
   IOUtils.copy(resourceAsStream, new FileOutputStream(file));
   return file;
 }
Ejemplo n.º 21
0
  @Test
  public void testCompressedRead() throws Exception {
    String[] lines = {"Irritable eagle", "Optimistic jay", "Fanciful hawk"};
    File tmpFile = tmpFolder.newFile("test");
    String filename = tmpFile.getPath();

    List<String> expected = new ArrayList<>();
    try (PrintStream writer =
        new PrintStream(new GZIPOutputStream(new FileOutputStream(tmpFile)))) {
      for (String line : lines) {
        writer.println(line);
        expected.add(line);
      }
    }

    Pipeline p = TestPipeline.create();

    TextIO.Read.Bound<String> read =
        TextIO.Read.from(filename).withCompressionType(CompressionType.GZIP);
    PCollection<String> output = p.apply(read);

    DataflowAssert.that(output).containsInAnyOrder(expected);
    p.run();

    tmpFile.delete();
  }
Ejemplo n.º 22
0
 @Test
 public void returnedUrlFormatForTemporaryFileIsCorrect() throws Exception {
   final File file = temporaryFolder.newFile();
   final DownloadedReport downloadedReport = new DownloadedReport(file);
   final String urlString = downloadedReport.getUrl();
   assertThat(urlString, equalTo(expectedUrlFor(file)));
 }
Ejemplo n.º 23
0
  @Before
  public void buildModel() throws Exception {
    model = folder.newFile();

    // write the model
    CollectionReaderDescription reader =
        createReaderDescription(
            TextReader.class,
            TextReader.PARAM_SOURCE_LOCATION,
            CONSUMER_TEST_DATA_PATH,
            TextReader.PARAM_PATTERNS,
            INCLUDE_PREFIX + "*.txt");

    AnalysisEngineDescription aggregate =
        createEngineDescription(
            createEngineDescription(BreakIteratorSegmenter.class),
            createEngineDescription(
                TfidfConsumer.class,
                TfidfConsumer.PARAM_FEATURE_PATH,
                Token.class,
                TfidfConsumer.PARAM_TARGET_LOCATION,
                model));

    SimplePipeline.runPipeline(reader, aggregate);
  }
Ejemplo n.º 24
0
  @Before
  public void setUp() throws Exception {
    assumeThat(TD_API_KEY, not(isEmptyOrNullString()));
    projectDir = folder.getRoot().toPath().toAbsolutePath().normalize();
    config = folder.newFile().toPath();
    Files.write(config, asList("secrets.td.apikey = " + TD_API_KEY));
    outfile = projectDir.resolve("outfile");

    client = TDClient.newBuilder(false).setApiKey(TD_API_KEY).build();
    database = "tmp_" + UUID.randomUUID().toString().replace('-', '_');
    client.createDatabase(database);

    table = "test";
    String insertJobId =
        client.submit(
            TDJobRequest.newPrestoQuery(database, "create table " + table + " as select 1"));

    TestUtils.expect(Duration.ofMinutes(5), jobSuccess(client, insertJobId));

    String selectCountJobId =
        client.submit(TDJobRequest.newPrestoQuery(database, "select count(*) from " + table));
    TestUtils.expect(Duration.ofMinutes(5), jobSuccess(client, selectCountJobId));

    List<ArrayNode> result = downloadResult(selectCountJobId);
    assertThat(result.get(0).get(0).asInt(), is(1));
  }
Ejemplo n.º 25
0
  @Test
  @Category(UnitTest.class)
  public void writeSplits() throws IOException {
    Splits splits = new PartitionerSplit();
    splits.generateSplits(new TestGenerator());

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

    FileOutputStream stream = new FileOutputStream(splitfile);
    splits.writeSplits(stream);

    stream.close();

    FileInputStream in = new FileInputStream(splitfile);
    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();
  }
Ejemplo n.º 26
0
  @Test
  public void testException_NoSuchAlgorithmException() throws Exception {

    Configuration config = new DefaultConfiguration("myname");
    final String filePath = temporaryFolder.newFile().getPath();
    PropertyCacheFile cache = new PropertyCacheFile(config, filePath);
    cache.put("myFile", 1);
    mockStatic(MessageDigest.class);

    when(MessageDigest.getInstance("SHA-1")).thenThrow(NoSuchAlgorithmException.class);

    Class<?>[] param = new Class<?>[1];
    param[0] = Serializable.class;
    Method method = PropertyCacheFile.class.getDeclaredMethod("getConfigHashCode", param);
    method.setAccessible(true);
    try {
      method.invoke(cache, config);
      fail();
    } catch (InvocationTargetException e) {
      assertTrue(e.getCause().getCause() instanceof NoSuchAlgorithmException);
      assertEquals("Unable to calculate hashcode.", e.getCause().getMessage());
    } catch (Exception e) {
      fail();
    }
  }
Ejemplo n.º 27
0
 @Test
 public void testSettersForParameters() throws Exception {
   final TreeWalker treeWalker = new TreeWalker();
   treeWalker.setTabWidth(1);
   treeWalker.configure(new DefaultConfiguration("default config"));
   treeWalker.setCacheFile(temporaryFolder.newFile().getPath());
 }
Ejemplo n.º 28
0
  @Test
  @Category(UnitTest.class)
  public void readSplits() throws IOException {
    File splitfile = folder.newFile(testName.getMethodName());

    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();

    FileInputStream in = new FileInputStream(splitfile);
    Splits splits = new PartitionerSplit();
    splits.readSplits(in);

    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());
    }

    in.close();
  }
  /**
   * Test with a subtitle with multiple format to read.
   *
   * @throws IOException if there was an I/O error.
   */
  @Test
  public void testMultipleFormatSubtitle() throws IOException {
    final SubtitleFormat subtitleFormat = mock(SubtitleFormat.class);
    final SubtitleReader subtitleReader = mock(SubtitleReader.class);
    final SubtitleFile subtitleFile = mock(SubtitleFile.class);
    final Path file = subtitleFolder.newFile("single.srt").toPath();

    when(subtitleFormatManager.getFormatByPath(file))
        .thenReturn(new HashSet<>(Arrays.asList(subtitleFormat, mock(SubtitleFormat.class))));
    when(userPrompt.askChoice(
            anyCollectionOf(SubtitleFormat.class),
            eq(TRANSLATION_KEY.chooseSubtitleFormat()),
            eq(file)))
        .thenReturn(subtitleFormat);
    when(subtitleFormat.getReader()).thenReturn(subtitleReader);
    when(subtitleReader.readFile(file)).thenReturn(subtitleFile);
    final Map<SubtitleFile, SubtitleFormat> subtitles = subtitleProvider.loadSubtitles(file);
    assertEquals(1, subtitles.size());
    final Entry<SubtitleFile, SubtitleFormat> loaded = subtitles.entrySet().iterator().next();
    assertEquals(subtitleFile, loaded.getKey());
    assertEquals(subtitleFormat, loaded.getValue());
    verify(userPrompt)
        .askChoice(
            anyCollectionOf(SubtitleFormat.class),
            eq(TRANSLATION_KEY.chooseSubtitleFormat()),
            eq(file));
  }
Ejemplo n.º 30
0
 @Test
 public void testExistingTargetFilePlainOutputToFileWithoutRwPermissions() throws Exception {
   final File file = temporaryFolder.newFile("file.output");
   assertTrue(file.setReadable(true, true));
   assertTrue(file.setWritable(false, false));
   exit.expectSystemExitWithStatus(-1);
   exit.checkAssertionAfterwards(
       new Assertion() {
         @Override
         public void checkAssertion() throws IOException {
           assertEquals(
               "Permission denied : '" + file.getCanonicalPath() + "'." + System.lineSeparator(),
               systemOut.getLog());
           assertEquals("", systemErr.getLog());
         }
       });
   Main.main(
       "-c",
       getPath("config-classname.xml"),
       "-f",
       "plain",
       "-o",
       file.getCanonicalPath(),
       getPath("InputMain.java"));
 }