@Test public void testIdQuery() throws Exception { Reference ref = createReference("_id", DataTypes.STRING); Query query = convert(whereClause(EqOperator.NAME, ref, Literal.newLiteral("i1"))); assertThat(query, instanceOf(TermQuery.class)); assertThat(query.toString(), is("_uid:default#i1")); }
@Test public void testUsingAnOrQuery() throws Exception { template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class); PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId(); p1.setFirstName("Sven"); p1.setAge(11); template.insert(p1); PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId(); p2.setFirstName("Mary"); p2.setAge(21); template.insert(p2); PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId(); p3.setFirstName("Ann"); p3.setAge(31); template.insert(p3); PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId(); p4.setFirstName("John"); p4.setAge(41); template.insert(p4); Query orQuery = new Query(new Criteria().orOperator(where("age").in(11, 21), where("age").is(31))); List<PersonWithIdPropertyOfTypeObjectId> results = template.find(orQuery, PersonWithIdPropertyOfTypeObjectId.class); assertThat(results.size(), is(3)); for (PersonWithIdPropertyOfTypeObjectId p : results) { assertThat(p.getAge(), isOneOf(11, 21, 31)); } }
@Test public void testRemovingDocument() throws Exception { PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId(); p1.setFirstName("Sven_to_be_removed"); p1.setAge(51); template.insert(p1); Query q1 = new Query(Criteria.where("id").is(p1.getId())); PersonWithIdPropertyOfTypeObjectId found1 = template.findOne(q1, PersonWithIdPropertyOfTypeObjectId.class); assertThat(found1, notNullValue()); Query _q = new Query(Criteria.where("_id").is(p1.getId())); template.remove(_q, PersonWithIdPropertyOfTypeObjectId.class); PersonWithIdPropertyOfTypeObjectId notFound1 = template.findOne(q1, PersonWithIdPropertyOfTypeObjectId.class); assertThat(notFound1, nullValue()); PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId(); p2.setFirstName("Bubba_to_be_removed"); p2.setAge(51); template.insert(p2); Query q2 = new Query(Criteria.where("id").is(p2.getId())); PersonWithIdPropertyOfTypeObjectId found2 = template.findOne(q2, PersonWithIdPropertyOfTypeObjectId.class); assertThat(found2, notNullValue()); template.remove(q2, PersonWithIdPropertyOfTypeObjectId.class); PersonWithIdPropertyOfTypeObjectId notFound2 = template.findOne(q2, PersonWithIdPropertyOfTypeObjectId.class); assertThat(notFound2, nullValue()); }
@Test @SuppressWarnings("unchecked") public void getComponentSubscriptionByAnAuthenticatedUser() throws Exception { WebResource resource = resource(); UserDetailWithProfiles user = new UserDetailWithProfiles(); user.setFirstName("Bart"); user.setLastName("Simpson"); user.setId("10"); user.addProfile(COMPONENT_ID, SilverpeasRole.writer); user.addProfile(COMPONENT_ID, SilverpeasRole.user); String sessionKey = authenticate(user); SubscriptionService mockedSubscriptionService = mock(SubscriptionService.class); ComponentSubscription subscription = new ComponentSubscription("10", COMPONENT_ID); Collection<ComponentSubscription> subscriptions = Lists.newArrayList(subscription); when((Collection<ComponentSubscription>) mockedSubscriptionService.getUserSubscriptionsByComponent("10", COMPONENT_ID)) .thenReturn(subscriptions); getTestResources() .getMockableSubscriptionService() .setImplementation(mockedSubscriptionService); SubscriptionEntity[] entities = resource .path(SUBSCRIPTION_RESOURCE_PATH) .header(HTTP_SESSIONKEY, sessionKey) .accept(MediaType.APPLICATION_JSON) .get(SubscriptionEntity[].class); assertNotNull(entities); assertThat(entities.length, is(1)); assertThat(entities[0], SubscriptionEntityMatcher.matches((Subscription) subscription)); }
@Test public void testUsingAnInQueryWithStringId() throws Exception { template.remove(new Query(), PersonWithIdPropertyOfTypeString.class); PersonWithIdPropertyOfTypeString p1 = new PersonWithIdPropertyOfTypeString(); p1.setFirstName("Sven"); p1.setAge(11); template.insert(p1); PersonWithIdPropertyOfTypeString p2 = new PersonWithIdPropertyOfTypeString(); p2.setFirstName("Mary"); p2.setAge(21); template.insert(p2); PersonWithIdPropertyOfTypeString p3 = new PersonWithIdPropertyOfTypeString(); p3.setFirstName("Ann"); p3.setAge(31); template.insert(p3); PersonWithIdPropertyOfTypeString p4 = new PersonWithIdPropertyOfTypeString(); p4.setFirstName("John"); p4.setAge(41); template.insert(p4); Query q1 = new Query(Criteria.where("age").in(11, 21, 41)); List<PersonWithIdPropertyOfTypeString> results1 = template.find(q1, PersonWithIdPropertyOfTypeString.class); Query q2 = new Query(Criteria.where("firstName").in("Ann", "Mary")); List<PersonWithIdPropertyOfTypeString> results2 = template.find(q2, PersonWithIdPropertyOfTypeString.class); Query q3 = new Query(Criteria.where("id").in(p3.getId(), p4.getId())); List<PersonWithIdPropertyOfTypeString> results3 = template.find(q3, PersonWithIdPropertyOfTypeString.class); assertThat(results1.size(), is(3)); assertThat(results2.size(), is(2)); assertThat(results3.size(), is(2)); }
@Test public void shouldAggregate() { createTagDocuments(); Aggregation agg = newAggregation( // project("tags"), // unwind("tags"), // group("tags") // .count() .as("n"), // project("n") // .and("tag") .previousOperation(), // sort(DESC, "n") // ); AggregationResults<TagCount> results = mongoTemplate.aggregate(agg, INPUT_COLLECTION, TagCount.class); assertThat(results, is(notNullValue())); assertThat(results.getServerUsed(), is("/127.0.0.1:27017")); List<TagCount> tagCount = results.getMappedResults(); assertThat(tagCount, is(notNullValue())); assertThat(tagCount.size(), is(3)); assertTagCount("spring", 3, tagCount.get(0)); assertTagCount("mongodb", 2, tagCount.get(1)); assertTagCount("nosql", 1, tagCount.get(2)); }
@Test public void shouldDetectResultMismatch() { createTagDocuments(); Aggregation aggregation = newAggregation( // project("tags"), // unwind("tags"), // group("tags") // .count() .as("count"), // count field not present limit(2) // ); AggregationResults<TagCount> results = mongoTemplate.aggregate(aggregation, INPUT_COLLECTION, TagCount.class); assertThat(results, is(notNullValue())); assertThat(results.getServerUsed(), is("/127.0.0.1:27017")); List<TagCount> tagCount = results.getMappedResults(); assertThat(tagCount, is(notNullValue())); assertThat(tagCount.size(), is(2)); assertTagCount(null, 0, tagCount.get(0)); assertTagCount(null, 0, tagCount.get(1)); }
@Test public void testSvValues() throws IOException { int numDocs = 1000000; int numOrdinals = numDocs / 4; Map<Integer, Long> controlDocToOrdinal = new HashMap<>(); OrdinalsBuilder builder = new OrdinalsBuilder(numDocs); long ordinal = builder.currentOrdinal(); for (int doc = 0; doc < numDocs; doc++) { if (doc % numOrdinals == 0) { ordinal = builder.nextOrdinal(); } controlDocToOrdinal.put(doc, ordinal); builder.addDoc(doc); } Ordinals ords = builder.build(ImmutableSettings.EMPTY); assertThat(ords, instanceOf(SinglePackedOrdinals.class)); RandomAccessOrds docs = ords.ordinals(); final SortedDocValues singleOrds = DocValues.unwrapSingleton(docs); assertNotNull(singleOrds); for (Map.Entry<Integer, Long> entry : controlDocToOrdinal.entrySet()) { assertThat(entry.getValue(), equalTo((long) singleOrds.getOrd(entry.getKey()))); } }
@Test public void testPutWarmerAcknowledgement() { createIndex("test"); // make sure one shard is started so the search during put warmer will not fail index("test", "type", "1", "f", 1); assertAcked( client() .admin() .indices() .preparePutWarmer("custom_warmer") .setSearchRequest( client() .prepareSearch("test") .setTypes("test") .setQuery(QueryBuilders.matchAllQuery()))); for (Client client : clients()) { GetWarmersResponse getWarmersResponse = client.admin().indices().prepareGetWarmers().setLocal(true).get(); assertThat(getWarmersResponse.warmers().size(), equalTo(1)); ObjectObjectCursor<String, List<IndexWarmersMetaData.Entry>> entry = getWarmersResponse.warmers().iterator().next(); assertThat(entry.key, equalTo("test")); assertThat(entry.value.size(), equalTo(1)); assertThat(entry.value.get(0).name(), equalTo("custom_warmer")); } }
/** parses standard date string. */ @Test public void parse_standard() { Date date = Date.valueOf("1234-01-02", Date.Format.STANDARD); assertThat(date.getYear(), is(1234)); assertThat(date.getMonth(), is(1)); assertThat(date.getDay(), is(2)); }
@Test @LocalData @Issue("jenkinsci/docker-plugin/issues/263") public void load080Config() { final DockerCloud dock = (DockerCloud) j.getInstance().getCloud("someCloud"); assertThat(dock.getTemplates(), hasSize(6)); final DockerTemplate template = dock.getTemplate("somedomain.com:5000/dockerbuild"); assertThat(template, notNullValue()); assertThat(template.getLabelString(), equalTo("dockerbuild-local")); assertThat(template.remoteFs, equalTo("/home/jenkins")); final DockerTemplateBase tBase = template.getDockerTemplateBase(); assertThat(tBase, notNullValue()); assertThat(tBase.getDockerCommandArray()[0], equalTo("/usr/bin/start-jenkins-slave.sh")); assertThat(tBase.getDnsString(), equalTo("8.8.8.8")); assertThat(tBase.getVolumesString(), equalTo("/dev/log:/dev/log")); assertThat(asList(tBase.getVolumes()), hasSize(1)); assertThat(tBase.getVolumes()[0], equalTo("/dev/log:/dev/log")); assertFalse(tBase.bindAllPorts); assertTrue(tBase.privileged); }
/** 単純な文字列解析。 */ @Test public void parse() { Date date = Date.valueOf("12340102", Date.Format.SIMPLE); assertThat(date.getYear(), is(1234)); assertThat(date.getMonth(), is(1)); assertThat(date.getDay(), is(2)); }
/** 大きな日付の文字列解析。 */ @Test public void parse_big() { Date date = Date.valueOf("29991231", Date.Format.SIMPLE); assertThat(date.getYear(), is(2999)); assertThat(date.getMonth(), is(12)); assertThat(date.getDay(), is(31)); }
/** 最初の日付の文字列解析。 */ @Test public void parse_zero() { Date date = Date.valueOf("00010101", Date.Format.SIMPLE); assertThat(date.getYear(), is(1)); assertThat(date.getMonth(), is(1)); assertThat(date.getDay(), is(1)); }
/** * Show environment variables. * * @throws Exception if failed */ @Test public void environment() throws Exception { String target = new File(getAsakusaHome(), ProcessHadoopScriptHandler.PATH_EXECUTE).getAbsolutePath(); File shell = putScript("environment.sh", new File(target)); HadoopScript script = new HadoopScript( "testing", set(), "com.example.Client", map(), map("script", "SCRIPT", "override", "SCRIPT")); HadoopScriptHandler handler = handler( "env.ASAKUSA_HOME", getAsakusaHome().getAbsolutePath(), "env.handler", "HANDLER", "env.override", "HANDLER"); execute(script, handler); List<String> results = getOutput(shell); assertThat(results, has(equalToIgnoringWhiteSpace("script=SCRIPT"))); assertThat(results, has(equalToIgnoringWhiteSpace("handler=HANDLER"))); assertThat(results, has(equalToIgnoringWhiteSpace("override=SCRIPT"))); }
@Test public void updateAnExistingComment() { theComment.newText("a new text"); CommentEntity entity = putAt(aResourceURI(), theComment); assertThat(entity, equalTo(theComment)); assertThat(entity.getText(), equalTo(theComment.getText())); }
/** @see DATAJPA-472 */ @Test public void shouldSupportFindAllWithPageableAndEntityWithIdClass() throws Exception { if (Package.getPackage("org.hibernate.cfg").getImplementationVersion().startsWith("4.1.")) { // we expect this test to fail on 4.1.x - due to a bug in hibernate - remove as soon as 4.1.x // fixes the issue. expectedException.expect(InvalidDataAccessApiUsageException.class); expectedException.expectMessage("No supertype found"); } IdClassExampleDepartment dep = new IdClassExampleDepartment(); dep.setName("TestDepartment"); dep.setDepartmentId(-1); IdClassExampleEmployee emp = new IdClassExampleEmployee(); emp.setDepartment(dep); emp = employeeRepositoryWithIdClass.save(emp); Page<IdClassExampleEmployee> page = employeeRepositoryWithIdClass.findAll(new PageRequest(0, 10)); assertThat(page, is(notNullValue())); assertThat(page.getTotalElements(), is(1L)); }
@Test @Slow public void testIndexActions() throws Exception { startNode("server1"); logger.info("Running Cluster Health (waiting for node to startup properly)"); ClusterHealthResponse clusterHealth = client("server1") .admin() .cluster() .health(clusterHealthRequest().waitForGreenStatus()) .actionGet(); logger.info("Done Cluster Health, status " + clusterHealth.getStatus()); assertThat(clusterHealth.isTimedOut(), equalTo(false)); assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN)); client("server1").admin().indices().create(createIndexRequest("test")).actionGet(); closeNode("server1"); startNode("server1"); Thread.sleep(500); try { client("server1").admin().indices().create(createIndexRequest("test")).actionGet(); assert false : "index should exists"; } catch (IndexAlreadyExistsException e) { // all is well } }
@Test public void shouldAggregateEmptyCollection() { Aggregation aggregation = newAggregation( // project("tags"), // unwind("tags"), // group("tags") // .count() .as("n"), // project("n") // .and("tag") .previousOperation(), // sort(DESC, "n") // ); AggregationResults<TagCount> results = mongoTemplate.aggregate(aggregation, INPUT_COLLECTION, TagCount.class); assertThat(results, is(notNullValue())); assertThat(results.getServerUsed(), is("/127.0.0.1:27017")); List<TagCount> tagCount = results.getMappedResults(); assertThat(tagCount, is(notNullValue())); assertThat(tagCount.size(), is(0)); }
@Test public void testPartitionedByNestedColumns() throws Exception { CreateTableAnalyzedStatement analysis = (CreateTableAnalyzedStatement) analyze( "create table my_table (" + " id integer," + " no_index string index off," + " o object as (" + " name string" + " )," + " date timestamp" + ") partitioned by (date, o['name'])"); assertThat(analysis.partitionedBy().size(), is(2)); Map<String, Object> oMapping = (Map<String, Object>) analysis.mappingProperties().get("o"); assertThat( mapToSortedString(oMapping), is( "doc_values=false, dynamic=true, index=not_analyzed, properties={" + "name={doc_values=false, index=no, store=false, type=string}}, store=false, type=object")); assertThat( (Map<String, Object>) ((Map) analysis.mapping().get("_meta")).get("columns"), not(hasKey("date"))); Map metaColumns = (Map) ((Map) analysis.mapping().get("_meta")).get("columns"); assertNull(metaColumns); assertThat(analysis.partitionedBy().get(0), contains("date", "date")); assertThat(analysis.partitionedBy().get(1), contains("o.name", "string")); }
@Test @SuppressWarnings("unchecked") public void getComponentSubscribersByAnAuthenticatedUser() throws Exception { WebResource resource = resource(); UserDetailWithProfiles user = new UserDetailWithProfiles(); user.setFirstName("Bart"); user.setLastName("Simpson"); user.setId("10"); user.addProfile(COMPONENT_ID, SilverpeasRole.writer); user.addProfile(COMPONENT_ID, SilverpeasRole.user); String sessionKey = authenticate(user); SubscriptionService mockedSubscriptionService = mock(SubscriptionService.class); List<String> subscribers = Lists.newArrayList("5", "6", "7", "20"); when(mockedSubscriptionService.getSubscribers(new ForeignPK("0", COMPONENT_ID))) .thenReturn(subscribers); getTestResources() .getMockableSubscriptionService() .setImplementation(mockedSubscriptionService); String[] entities = resource .path(SUBSCRIPTION_RESOURCE_PATH + "/subscribers/0") .header(HTTP_SESSIONKEY, sessionKey) .accept(MediaType.APPLICATION_JSON) .get(String[].class); assertNotNull(entities); assertThat(entities.length, is(4)); assertThat(entities, is(new String[] {"5", "6", "7", "20"})); }
@Test public void executesPagedSpecificationsCorrectly() throws Exception { Page<User> result = executeSpecWithSort(null); assertThat(result.asList(), anyOf(hasItem(firstUser), hasItem(thirdUser))); assertThat(result.asList(), not(hasItem(secondUser))); }
@Test public void testTwoLikes() { SparseVector vec = sum.summarize(History.forUser(42, Like.create(42, 39), Like.create(42, 67))); assertThat(vec.size(), equalTo(2)); assertThat(vec.get(39), equalTo(1.0)); assertThat(vec.get(67), equalTo(1.0)); }
private void checkSids(List<Ex1> results) { assertThat(results.size(), is(10)); assertThat(results.get(0).getSidOption().isNull(), is(true)); for (int i = 1; i < 10; i++) { assertThat(results.get(i).getSid(), is((long) i)); } }
@Test public void testUsingRegexQueryWithOptions() throws Exception { template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class); PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId(); p1.setFirstName("Sven"); p1.setAge(11); template.insert(p1); PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId(); p2.setFirstName("Mary"); p2.setAge(21); template.insert(p2); PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId(); p3.setFirstName("Ann"); p3.setAge(31); template.insert(p3); PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId(); p4.setFirstName("samantha"); p4.setAge(41); template.insert(p4); Query q1 = new Query(Criteria.where("firstName").regex("S.*")); List<PersonWithIdPropertyOfTypeObjectId> results1 = template.find(q1, PersonWithIdPropertyOfTypeObjectId.class); Query q2 = new Query(Criteria.where("firstName").regex("S.*", "i")); List<PersonWithIdPropertyOfTypeObjectId> results2 = template.find(q2, PersonWithIdPropertyOfTypeObjectId.class); assertThat(results1.size(), is(1)); assertThat(results2.size(), is(2)); }
/** * Test method for {@link * net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec#EdDSAPrivateKeySpec(byte[], * net.i2p.crypto.eddsa.spec.EdDSAParameterSpec)}. */ @Test public void testEdDSAPrivateKeySpecFromSeed() { EdDSAPrivateKeySpec key = new EdDSAPrivateKeySpec(ZERO_SEED, ed25519); assertThat(key.getSeed(), is(equalTo(ZERO_SEED))); assertThat(key.getH(), is(equalTo(ZERO_H))); assertThat(key.getA().toByteArray(), is(equalTo(ZERO_PK))); }
@Test public void testUsingUpdateWithMultipleSet() throws Exception { template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class); PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId(); p1.setFirstName("Sven"); p1.setAge(11); template.insert(p1); PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId(); p2.setFirstName("Mary"); p2.setAge(21); template.insert(p2); Update u = new Update().set("firstName", "Bob").set("age", 10); WriteResult wr = template.updateMulti(new Query(), u, PersonWithIdPropertyOfTypeObjectId.class); assertThat(wr.getN(), is(2)); Query q1 = new Query(Criteria.where("age").in(11, 21)); List<PersonWithIdPropertyOfTypeObjectId> r1 = template.find(q1, PersonWithIdPropertyOfTypeObjectId.class); assertThat(r1.size(), is(0)); Query q2 = new Query(Criteria.where("age").is(10)); List<PersonWithIdPropertyOfTypeObjectId> r2 = template.find(q2, PersonWithIdPropertyOfTypeObjectId.class); assertThat(r2.size(), is(2)); for (PersonWithIdPropertyOfTypeObjectId p : r2) { assertThat(p.getAge(), is(10)); assertThat(p.getFirstName(), is("Bob")); } }
/** * Test method for {@link * net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec#EdDSAPrivateKeySpec(net.i2p.crypto.eddsa.spec.EdDSAParameterSpec, * byte[])}. */ @Test public void testEdDSAPrivateKeySpecFromH() { EdDSAPrivateKeySpec key = new EdDSAPrivateKeySpec(ed25519, ZERO_H); assertThat(key.getSeed(), is(nullValue())); assertThat(key.getH(), is(equalTo(ZERO_H))); assertThat(key.getA().toByteArray(), is(equalTo(ZERO_PK))); }
@Test public void testVectorHighlighter() throws Exception { Directory dir = new RAMDirectory(); IndexWriter indexWriter = new IndexWriter(dir, Lucene.STANDARD_ANALYZER, true, IndexWriter.MaxFieldLength.UNLIMITED); indexWriter.addDocument( doc() .add(field("_id", "1")) .add( field( "content", "the big bad dog", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)) .build()); IndexReader reader = indexWriter.getReader(); IndexSearcher searcher = new IndexSearcher(reader); TopDocs topDocs = searcher.search(new TermQuery(new Term("_id", "1")), 1); assertThat(topDocs.totalHits, equalTo(1)); FastVectorHighlighter highlighter = new FastVectorHighlighter(); String fragment = highlighter.getBestFragment( highlighter.getFieldQuery(new TermQuery(new Term("content", "bad"))), reader, topDocs.scoreDocs[0].doc, "content", 30); assertThat(fragment, notNullValue()); System.out.println(fragment); }
@Test public void testVersioningIndexConflictWithFlush() { ParsedDocument doc = testParsedDocument( "1", "1", "test", null, -1, -1, testDocument(), Lucene.STANDARD_ANALYZER, B_1, false); Engine.Index index = new Engine.Index(null, newUid("1"), doc); engine.index(index); assertThat(index.version(), equalTo(1l)); index = new Engine.Index(null, newUid("1"), doc); engine.index(index); assertThat(index.version(), equalTo(2l)); engine.flush(new Engine.Flush()); index = new Engine.Index(null, newUid("1"), doc).version(1l); try { engine.index(index); assert false; } catch (VersionConflictEngineException e) { // all is well } // future versions should not work as well index = new Engine.Index(null, newUid("1"), doc).version(3l); try { engine.index(index); assert false; } catch (VersionConflictEngineException e) { // all is well } }