@Test
    public void write() throws IOException
    {
        int bufferedDataBlocks = 3;
        int expectedOnProgressCallWithBuffer = bufferedDataBlocks;
        int expectedOnFinishCall = 1;

        final int[] actualOnProgressCall = {0};
        final int[] actualOnFinishCall = {0};

        byte[] bytes = new byte[InputStreamExtensions.IO_BUFFER_SIZE * bufferedDataBlocks];

        ByteArrayOutputStream os = new ByteArrayOutputStream(bytes.length);
        ProgressBufferedOutputStream progressBufferedOutputStream
                = new ProgressBufferedOutputStream(os, new StreamProgressListener(bytes.length, new ProgressListener<Long>()
        {
            @Override
            public void onProgress(int progress)
            {
                actualOnProgressCall[0]++;
            }

            @Override
            public void onFinish(Long toalBytes)
            {
                actualOnFinishCall[0]++;
            }
        }));

        _._(new ByteArrayInputStream(new byte[bytes.length])).copyTo(progressBufferedOutputStream,true,true);

        MatcherAssert.assertThat(actualOnProgressCall[0], is(expectedOnProgressCallWithBuffer));
        MatcherAssert.assertThat(actualOnFinishCall[0], is(expectedOnFinishCall));
    }
  @BenchmarkOptions(benchmarkRounds = 1, warmupRounds = 0)
  @Test
  public void validateRetieveItemWithLastAccessUpdateTimeDelay() throws Exception {
    // need to ensure we wait 100 ms
    int wait = 100;

    ((DefaultAttributesHandler) repository.getAttributesHandler()).setLastRequestedResolution(wait);
    Thread.sleep(wait);

    AttributeStorage attributeStorageSpy =
        Mockito.spy(repository.getAttributesHandler().getAttributeStorage());
    repository.getAttributesHandler().setAttributeStorage(attributeStorageSpy);

    ResourceStoreRequest resourceRequest = new ResourceStoreRequest(testFilePath);
    resourceRequest.getRequestContext().put(AccessManager.REQUEST_REMOTE_ADDRESS, "127.0.0.1");

    AbstractStorageItem storageItem =
        localRepositoryStorageUnderTest.retrieveItem(repository, resourceRequest);

    MatcherAssert.assertThat(storageItem, Matchers.notNullValue());
    MatcherAssert.assertThat(
        storageItem.getLastRequested(), Matchers.greaterThan(originalLastAccessTime));

    Mockito.verify(attributeStorageSpy, Mockito.times(1))
        .putAttributes(Mockito.<RepositoryItemUid>any(), Mockito.<Attributes>any());
    Mockito.verify(attributeStorageSpy, Mockito.times(1))
        .getAttributes(Mockito.<RepositoryItemUid>any());
  }
 /**
  * Cacheable can cache static calls.
  *
  * @throws Exception If something goes wrong
  */
 @Test
 public void cachesSimpleStaticCall() throws Exception {
   final String first = CacheableTest.Foo.staticGet();
   MatcherAssert.assertThat(first, Matchers.equalTo(CacheableTest.Foo.staticGet()));
   CacheableTest.Foo.staticFlush();
   MatcherAssert.assertThat(CacheableTest.Foo.staticGet(), Matchers.not(Matchers.equalTo(first)));
 }
  @BenchmarkOptions(benchmarkRounds = 10, warmupRounds = 1)
  @Test
  public void validateRetieveItemWithOutLastAccessUpdateTimeDelay()
      throws LocalStorageException, ItemNotFoundException, IOException {
    // do the test, but make sure the _iterations_ will not get out of the "resolution" span!
    // Note: this test is just broken as is, what guarantees it will finish the cycles in given X
    // millis?
    // Meaning, the assertions + rounds is wrong.
    ((DefaultAttributesHandler) repository.getAttributesHandler())
        .setLastRequestedResolution(30000L);
    AttributeStorage attributeStorageSpy =
        Mockito.spy(repository.getAttributesHandler().getAttributeStorage());
    repository.getAttributesHandler().setAttributeStorage(attributeStorageSpy);

    ResourceStoreRequest resourceRequest = new ResourceStoreRequest(testFilePath);
    resourceRequest.getRequestContext().put(AccessManager.REQUEST_REMOTE_ADDRESS, "127.0.0.1");

    AbstractStorageItem storageItem =
        localRepositoryStorageUnderTest.retrieveItem(repository, resourceRequest);

    MatcherAssert.assertThat(storageItem, Matchers.notNullValue());
    MatcherAssert.assertThat(
        storageItem.getLastRequested(), Matchers.equalTo(originalLastAccessTime));

    Mockito.verify(attributeStorageSpy, Mockito.times(0))
        .putAttributes(Mockito.<RepositoryItemUid>any(), Mockito.<Attributes>any());
    Mockito.verify(attributeStorageSpy, Mockito.times(1))
        .getAttributes(Mockito.<RepositoryItemUid>any());
  }
  @Test
  public void testLatLonInOneValue() throws Exception {
    String mapping =
        XContentFactory.contentTextBuilder(XContentType.JSON)
            .startObject()
            .startObject("type")
            .startObject("properties")
            .startObject("point")
            .field("type", "geo_point")
            .field("geohash", true)
            .field("lat_lon", false)
            .endObject()
            .endObject()
            .endObject()
            .endObject()
            .string();

    XContentDocumentMapper defaultMapper = XContentMapperTests.newParser().parse(mapping);

    ParsedDocument doc =
        defaultMapper.parse(
            "type",
            "1",
            XContentFactory.jsonBuilder()
                .startObject()
                .field("point", "1.2,1.3")
                .endObject()
                .copiedBytes());

    MatcherAssert.assertThat(doc.doc().getField("point.lat"), nullValue());
    MatcherAssert.assertThat(doc.doc().getField("point.lon"), nullValue());
    MatcherAssert.assertThat(
        doc.doc().get("point.geohash"), equalTo(GeoHashUtils.encode(1.2, 1.3)));
  }
  @Test
  public void includeAsClasses() throws Exception {
    String baseDir = testIssue("flexmojos-247").getBasedir();
    File target = new File(baseDir, "target");
    Assert.assertTrue(target.exists());

    File swc = new File(target, "flexmojos-247-1.0-SNAPSHOT.swc");
    Assert.assertTrue(swc.exists());

    String catalog;
    ZipFile zf = new ZipFile(swc);
    try {
      InputStream in = zf.getInputStream(zf.getEntry("catalog.xml"));
      catalog = IOUtils.toString(in);
      in.close();
    } finally {
      zf.close();
    }

    // must have both classes and the uri
    MatcherAssert.assertThat(catalog, StringContains.containsString("AClass"));
    MatcherAssert.assertThat(catalog, StringContains.containsString("BClass"));
    MatcherAssert.assertThat(
        catalog, StringContains.containsString("http://flexmojos.sonatype.org/tests"));
  }
 /**
  * RtRepoCommits can compare two commits and return result in patch mode.
  *
  * @throws Exception if there is no github key provided
  */
 @Test
 public final void compareCommitsPatch() throws Exception {
   final String patch = RtRepoCommitsITCase.repo().commits().patch("5339b8e35b", "9b2e6efde9");
   MatcherAssert.assertThat(
       patch, Matchers.startsWith("From 9b2e6efde94fabec5876dc481b38811e8b4e992f"));
   MatcherAssert.assertThat(
       patch, Matchers.containsString("Issue #430 RepoCommit interface was added"));
 }
 /**
  * Cacheable can cache calls.
  *
  * @throws Exception If something goes wrong
  */
 @Test
 public void cachesSimpleCall() throws Exception {
   final CacheableTest.Foo foo = new CacheableTest.Foo(1L);
   final String first = foo.get().toString();
   MatcherAssert.assertThat(first, Matchers.equalTo(foo.get().toString()));
   foo.flush();
   MatcherAssert.assertThat(foo.get().toString(), Matchers.not(Matchers.equalTo(first)));
 }
 /**
  * RtReleases can remove a release.
  *
  * @throws Exception if any problem inside
  */
 @Test
 public void canRemoveRelease() throws Exception {
   final Releases releases = repo.releases();
   final Release release = releases.create(RandomStringUtils.randomAlphanumeric(Tv.TEN));
   MatcherAssert.assertThat(releases.iterate(), Matchers.hasItem(release));
   releases.remove(release.number());
   MatcherAssert.assertThat(releases.iterate(), Matchers.not(Matchers.hasItem(release)));
 }
Beispiel #10
0
 /**
  * FkHost can match a host.
  *
  * @throws IOException If some problem inside
  */
 @Test
 public void matchesByHost() throws IOException {
   MatcherAssert.assertThat(
       new FkHost("www.example.com", new TkEmpty()).route(new RqFake("GET", "/hel?a=1")).has(),
       Matchers.is(true));
   MatcherAssert.assertThat(
       new FkHost("google.com", new TkEmpty()).route(new RqFake("PUT", "/?test")).has(),
       Matchers.is(false));
 }
Beispiel #11
0
 /**
  * CcBase64 can encode and decode.
  *
  * @throws IOException If some problem inside
  */
 @Test
 public void encodesAndDecodes() throws IOException {
   final String urn = "urn:test:Hello World!";
   final Map<String, String> properties = ImmutableMap.of("userName", "user");
   final Codec codec = new CcBase64(new CcPlain());
   final Identity expected = codec.decode(codec.encode(new Identity.Simple(urn, properties)));
   MatcherAssert.assertThat(expected.urn(), Matchers.equalTo(urn));
   MatcherAssert.assertThat(expected.properties(), Matchers.equalTo(properties));
 }
Beispiel #12
0
 public static void verifyOrderedList(SortedSet<Bid> bids) {
   if (bids.size() > 0) {
     double firstPrice = bids.first().getPrice();
     double lastPrice = bids.last().getPrice();
     for (Bid bid : bids) {
       MatcherAssert.assertThat(bid.getPrice(), greaterThanOrEqualTo(firstPrice));
       MatcherAssert.assertThat(bid.getPrice(), lessThanOrEqualTo(lastPrice));
     }
   }
 }
 /**
  * ArrayMap can be equal to another map.
  *
  * @throws Exception If some problem inside
  */
 @Test
 public void comparesCorrectlyWithAnotherMap() throws Exception {
   MatcherAssert.assertThat(
       new ArrayMap<Integer, Integer>().with(1, 1).with(2, 2),
       Matchers.equalTo(new ArrayMap<Integer, Integer>().with(2, 2).with(1, 1)));
   MatcherAssert.assertThat(
       new ArrayMap<Class<?>, Integer>().with(String.class, 1).with(Integer.class, 2),
       Matchers.equalTo(
           new ArrayMap<Class<?>, Integer>().with(Integer.class, 2).with(String.class, 1)));
 }
 /**
  * Cacheable can Asynchronous update.
  *
  * @throws Exception If something goes wrong
  */
 @Test
 public void asyncUpdateCacheSimpleCall() throws Exception {
   final CacheableTest.Foo foo = new CacheableTest.Foo(1L);
   final String first = foo.asyncGet().toString();
   MatcherAssert.assertThat(first, Matchers.equalTo(foo.asyncGet().toString()));
   TimeUnit.SECONDS.sleep(2);
   MatcherAssert.assertThat(first, Matchers.equalTo(foo.asyncGet().toString()));
   TimeUnit.SECONDS.sleep(2);
   MatcherAssert.assertThat(first, Matchers.not(Matchers.equalTo(foo.asyncGet().toString())));
 }
 /** AwsRules can cache results of get() and iterator() as same rules. */
 @Test
 public void returnsGetAndIteratorAsSameRules() {
   final Item item = Mockito.mock(Item.class);
   final String name = "rule-name-foo";
   Mockito.doReturn(new AttributeValue(name)).when(item).get(Mockito.anyString());
   final Region region = new RegionMocker().with(item).mock();
   final Rules rules = new AwsRules(region, Mockito.mock(SQSClient.class), new URN());
   MatcherAssert.assertThat(rules.get(name).name(), Matchers.equalTo(name));
   MatcherAssert.assertThat(rules.iterator().next().name(), Matchers.equalTo(name));
   Mockito.verify(item, Mockito.times(1)).get(Mockito.anyString());
 }
Beispiel #16
0
 /**
  * DyAlias can make an alias.
  *
  * @throws Exception If there is some problem inside
  */
 @Test
 public void makesAlias() throws Exception {
   final Aliases aliases = new DyBase().user(new URN("urn:test:12")).aliases();
   final String name = "walter";
   aliases.add(name);
   MatcherAssert.assertThat(aliases.check(name), Matchers.not(Matchers.isEmptyOrNullString()));
   final Alias alias = aliases.iterate().iterator().next();
   MatcherAssert.assertThat(alias, new Alias.HasName(Matchers.equalTo(name)));
   alias.photo(new URI("http://localhost#test"));
   MatcherAssert.assertThat(alias.photo().toString(), Matchers.containsString("#test"));
 }
  @Test
  public void listAll() {
    Mockito.when(repository.all(QSampleEntity.sampleEntity, QSampleEntity.sampleEntity))
        .thenReturn(getList());
    List<SampleEntity> list = service.list("");

    Mockito.verify(repository).all(QSampleEntity.sampleEntity, QSampleEntity.sampleEntity);

    MatcherAssert.assertThat(list, Matchers.hasSize(1));
    MatcherAssert.assertThat(list, Matchers.contains(createSampleEntity(ID, null)));
  }
 /**
  * RtReleases can fetch a single release.
  *
  * @throws Exception if any error inside
  */
 @Test
 public void canFetchRelease() throws Exception {
   final Releases releases = repo.releases();
   final String tag = "v1.0";
   final Release release = releases.create(tag);
   MatcherAssert.assertThat(
       releases.get(release.number()).number(), Matchers.equalTo(release.number()));
   MatcherAssert.assertThat(
       new Release.Smart(releases.get(release.number())).tag(), Matchers.equalTo(tag));
   releases.remove(release.number());
 }
  @Test
  public void testEntrySet() {
    Map<Integer, String> map = redisson.getMap("simple12");
    map.put(1, "12");
    map.put(2, "33");
    map.put(3, "43");

    Assert.assertEquals(3, map.entrySet().size());
    MatcherAssert.assertThat(map, Matchers.hasEntry(Matchers.equalTo(1), Matchers.equalTo("12")));
    MatcherAssert.assertThat(map, Matchers.hasEntry(Matchers.equalTo(2), Matchers.equalTo("33")));
    MatcherAssert.assertThat(map, Matchers.hasEntry(Matchers.equalTo(3), Matchers.equalTo("43")));
  }
  @BenchmarkOptions(benchmarkRounds = 10, warmupRounds = 1)
  @Test
  public void testRetieveItemWithoutLastAccessUpdate()
      throws LocalStorageException, ItemNotFoundException {
    ResourceStoreRequest resourceRequest = new ResourceStoreRequest(testFilePath);

    AbstractStorageItem storageItem =
        localRepositoryStorageUnderTest.retrieveItem(repository, resourceRequest);

    MatcherAssert.assertThat(storageItem, Matchers.notNullValue());
    MatcherAssert.assertThat(
        storageItem.getLastRequested(), Matchers.equalTo(originalLastAccessTime));
  }
 /**
  * AwsUser can work with real data.
  *
  * @throws Exception If some problem inside
  */
 @Test
 public void worksWithRealDynamoDb() throws Exception {
   final URN urn = new URN("urn:github:66");
   final User user = new AwsUser(this.region, Mockito.mock(SQSClient.class), urn);
   MatcherAssert.assertThat(user.urn(), Matchers.equalTo(urn));
   for (Rule rule : user.rules()) {
     user.rules().remove(rule.name());
   }
   final String name = "simple-rule";
   user.rules().create(name);
   MatcherAssert.assertThat(user.rules(), Matchers.<Rule>iterableWithSize(1));
   MatcherAssert.assertThat(user.rules().contains(name), Matchers.is(true));
 }
  @BenchmarkOptions(benchmarkRounds = 10, warmupRounds = 1)
  @Test
  public void testRetieveItemWithLastAccessUpdate()
      throws LocalStorageException, ItemNotFoundException {
    ResourceStoreRequest resourceRequest = new ResourceStoreRequest(testFilePath);
    resourceRequest.getRequestContext().put(AccessManager.REQUEST_REMOTE_ADDRESS, "127.0.0.1");

    AbstractStorageItem storageItem =
        localRepositoryStorageUnderTest.retrieveItem(repository, resourceRequest);

    MatcherAssert.assertThat(storageItem, Matchers.notNullValue());
    MatcherAssert.assertThat(
        storageItem.getLastRequested(), Matchers.greaterThan(originalLastAccessTime));
  }
 /**
  * RtReleases can create a release.
  *
  * @throws Exception if any error inside
  */
 @Test
 public void canCreateRelease() throws Exception {
   final Releases releases = repo.releases();
   final Release created = releases.create("0.1");
   final int number = created.number();
   try {
     final Release obtained = releases.get(number);
     MatcherAssert.assertThat(created, Matchers.is(obtained));
     MatcherAssert.assertThat(
         new Release.Smart(created).tag(), Matchers.equalTo(new Release.Smart(obtained).tag()));
   } finally {
     releases.remove(number);
   }
 }
Beispiel #24
0
  public static void transactionVerification(Queue<Transaction> transactions) {
    for (Transaction transaction : transactions) {

      MatcherAssert.assertThat(
          transaction.getBuy().getStock(), is(transaction.getSell().getStock()));

      double buyPrice = transaction.getBuy().getPrice();
      double sellPrice = transaction.getSell().getPrice();
      double transactionPrice = transaction.getPrice();

      MatcherAssert.assertThat(buyPrice, greaterThanOrEqualTo(sellPrice));
      MatcherAssert.assertThat(
          transactionPrice, anyOf(closeTo(buyPrice, 0.0001), closeTo(sellPrice, 0.0001)));
    }
  }
  @Test
  public void testWordListPath() throws Exception {
    Environment env = new Environment(ImmutableSettings.Builder.EMPTY_SETTINGS);
    String[] words = new String[] {"donau", "dampf", "schiff", "spargel", "creme", "suppe"};

    File wordListFile = generateWordList(words);
    Settings settings =
        settingsBuilder()
            .loadFromSource("index: \n  word_list_path: " + wordListFile.getAbsolutePath())
            .build();

    Set<String> wordList = Analysis.getWordSet(env, settings, "index.word_list");
    MatcherAssert.assertThat(wordList.size(), equalTo(6));
    MatcherAssert.assertThat(wordList, hasItems(words));
  }
 /**
  * WebLinkingResponse can follow a link.
  *
  * @throws Exception If something goes wrong inside
  */
 @Test
 public void followsLinksInHeaders() throws Exception {
   final WebLinkingResponse response =
       new WebLinkingResponse(
           new FakeRequest()
               .withHeader("Link", "</a>; rel=\"first\", <http://localhost/o>; rel=\"second\"")
               .uri()
               .set(new URI("http://localhost/test"))
               .back()
               .fetch());
   MatcherAssert.assertThat(
       response.follow("first").uri().get(), Matchers.equalTo(new URI("http://localhost/a")));
   MatcherAssert.assertThat(
       response.follow("second").uri().get(), Matchers.equalTo(new URI("http://localhost/o")));
 }
Beispiel #27
0
 /**
  * AwsUser can have a name.
  *
  * @throws Exception If some problem inside
  */
 @Test
 public void hasName() throws Exception {
   final Region region = Mockito.mock(Region.class);
   final URN urn = new URN("urn:facebook:444");
   final User user = new AwsUser(region, Mockito.mock(SQSClient.class), urn);
   MatcherAssert.assertThat(user.urn(), Matchers.equalTo(urn));
 }
  @Test
  public void testOnInsertString() {
    // Given:
    selectedTU = currentPageRows.get(0);
    when(editor.getId()).thenReturn(selectedTU.getId());
    when(display.getId()).thenReturn(selectedTU.getId());
    when(display.getEditors()).thenReturn(Lists.newArrayList(editor));
    when(tableEditorMessages.notifyCopied()).thenReturn("copied");
    when(sourceContentPresenter.getSourceContent(selectedTU.getId()))
        .thenReturn(Optional.of("source content"));

    presenter.setStatesForTesting(selectedTU.getId(), 0, display);

    // When:
    presenter.onInsertString(new InsertStringInEditorEvent("", "suggestion"));

    // Then:
    verify(editor).insertTextInCursorPosition("suggestion");

    verify(eventBus, atLeastOnce()).fireEvent(eventCaptor.capture());
    NotificationEvent notificationEvent =
        TestFixture.extractFromEvents(eventCaptor.getAllValues(), NotificationEvent.class);
    MatcherAssert.assertThat(notificationEvent.getMessage(), Matchers.equalTo("copied"));

    RunValidationEvent runValidationEvent =
        TestFixture.extractFromEvents(eventCaptor.getAllValues(), RunValidationEvent.class);
    assertThat(runValidationEvent.getSourceContent(), equalTo("source content"));
  }
 /** MkAnswerMatchers can match MkAnswer body bytes. */
 @Test
 public void canMatchBodyBytes() {
   final byte[] body = {0x01, 0x45, 0x21};
   final MkAnswer query = Mockito.mock(MkAnswer.class);
   Mockito.doReturn(body).when(query).bodyBytes();
   MatcherAssert.assertThat(query, MkAnswerMatchers.hasBodyBytes(Matchers.is(body)));
 }
 /** MkAnswerMatchers should be able to match MkAnswer body. */
 @Test
 public void canMatchBody() {
   final String body = "Hello \u20ac!";
   final MkAnswer query = Mockito.mock(MkAnswer.class);
   Mockito.doReturn(body).when(query).body();
   MatcherAssert.assertThat(query, MkAnswerMatchers.hasBody(Matchers.is(body)));
 }