diff options
Diffstat (limited to 'vendor/ruflin/elastica/test/lib')
135 files changed, 16309 insertions, 0 deletions
diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/AvgTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/AvgTest.php new file mode 100644 index 00000000..5c6fe13d --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/AvgTest.php @@ -0,0 +1,38 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\Avg; +use Elastica\Document; +use Elastica\Index; +use Elastica\Query; + +class AvgTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex('avg'); + $docs = array( + new Document('1', array('price' => 5)), + new Document('2', array('price' => 8)), + new Document('3', array('price' => 1)), + new Document('4', array('price' => 3)), + ); + $this->_index->getType('test')->addDocuments($docs); + $this->_index->refresh(); + } + + public function testAvgAggregation() + { + $agg = new Avg("avg"); + $agg->setField('price'); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregations(); + $this->assertEquals((5 + 8 + 1 + 3) / 4.0, $results['avg']['value']); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/BaseAggregationTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/BaseAggregationTest.php new file mode 100644 index 00000000..5569ca78 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/BaseAggregationTest.php @@ -0,0 +1,28 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Index; +use Elastica\Test\Base; + +abstract class BaseAggregationTest extends Base +{ + /** + * @var Index + */ + protected $_index; + + protected function tearDown() + { + parent::tearDown(); + if ($this->_index instanceof Index) { + $this->_index->delete(); + } + } + + protected function _createIndex($name = 'test', $delete = true, $shards = 1) + { + return parent::_createIndex('test_aggregation_' . $name, $delete, $shards); + } +}
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/CardinalityTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/CardinalityTest.php new file mode 100644 index 00000000..d2f4d2be --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/CardinalityTest.php @@ -0,0 +1,38 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\Cardinality; +use Elastica\Document; +use Elastica\Query; + +class CardinalityTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex("cardinality"); + $docs = array( + new Document("1", array("color" => "blue")), + new Document("2", array("color" => "blue")), + new Document("3", array("color" => "red")), + new Document("4", array("color" => "green")), + ); + $this->_index->getType("test")->addDocuments($docs); + $this->_index->refresh(); + } + + public function testCardinalityAggregation() + { + $agg = new Cardinality("cardinality"); + $agg->setField("color"); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("cardinality"); + + $this->assertEquals(3, $results['value']); + } +} + diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/DateHistogramTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/DateHistogramTest.php new file mode 100644 index 00000000..d5bd878c --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/DateHistogramTest.php @@ -0,0 +1,43 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\DateHistogram; +use Elastica\Document; +use Elastica\Query; +use Elastica\Type\Mapping; + +class DateHistogramTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex("date_histogram"); + $mapping = new Mapping(); + $mapping->setProperties(array( + "created" => array("type" => "date") + )); + $type = $this->_index->getType("test"); + $type->setMapping($mapping); + $docs = array( + new Document("1", array("created" => 1390962135000)), + new Document("2", array("created" => 1390965735000)), + new Document("3", array("created" => 1390954935000)), + ); + $type->addDocuments($docs); + $this->_index->refresh(); + } + + public function testDateHistogramAggregation() + { + $agg = new DateHistogram("hist", "created", "1h"); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("hist"); + + $this->assertEquals(3, sizeof($results['buckets'])); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/DateRangeTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/DateRangeTest.php new file mode 100644 index 00000000..781f2112 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/DateRangeTest.php @@ -0,0 +1,51 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\DateRange; +use Elastica\Document; +use Elastica\Query; +use Elastica\Type\Mapping; + +class DateRangeTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex("date_range"); + $mapping = new Mapping(); + $mapping->setProperties(array( + "created" => array("type" => "date") + )); + $type = $this->_index->getType("test"); + $type->setMapping($mapping); + $docs = array( + new Document("1", array("created" => 1390962135000)), + new Document("2", array("created" => 1390965735000)), + new Document("3", array("created" => 1390954935000)), + ); + $type->addDocuments($docs); + $this->_index->refresh(); + } + + public function testDateRangeAggregation() + { + $agg = new DateRange("date"); + $agg->setField("created"); + $agg->addRange(1390958535000)->addRange(null, 1390958535000); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("date"); + + foreach ($results['buckets'] as $bucket) { + if (array_key_exists('to', $bucket)) { + $this->assertEquals(1, $bucket['doc_count']); + } else if (array_key_exists('from', $bucket)) { + $this->assertEquals(2, $bucket['doc_count']); + } + } + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/ExtendedStatsTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/ExtendedStatsTest.php new file mode 100644 index 00000000..e125c9c9 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/ExtendedStatsTest.php @@ -0,0 +1,43 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\ExtendedStats; +use Elastica\Document; +use Elastica\Query; + +class ExtendedStatsTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex("extended_stats"); + $docs = array( + new Document("1", array("price" => 5)), + new Document("2", array("price" => 8)), + new Document("3", array("price" => 1)), + new Document("4", array("price" => 3)), + ); + $this->_index->getType("test")->addDocuments($docs); + $this->_index->refresh(); + } + + public function testExtendedStatsAggregation() + { + $agg = new ExtendedStats("stats"); + $agg->setField("price"); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("stats"); + + $this->assertEquals(4, $results['count']); + $this->assertEquals(1, $results['min']); + $this->assertEquals(8, $results['max']); + $this->assertEquals((5 + 8 + 1 + 3) / 4.0, $results['avg']); + $this->assertEquals((5 + 8 + 1 + 3), $results['sum']); + $this->assertTrue(array_key_exists('sum_of_squares', $results)); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/FilterTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/FilterTest.php new file mode 100644 index 00000000..dd4d4c2d --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/FilterTest.php @@ -0,0 +1,78 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\Avg; +use Elastica\Aggregation\Filter; +use Elastica\Document; +use Elastica\Filter\Range; +use Elastica\Filter\Term; +use Elastica\Query; + +class FilterTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex("filter"); + $docs = array( + new Document("1", array("price" => 5, "color" => "blue")), + new Document("2", array("price" => 8, "color" => "blue")), + new Document("3", array("price" => 1, "color" => "red")), + new Document("4", array("price" => 3, "color" => "green")), + ); + $this->_index->getType("test")->addDocuments($docs); + $this->_index->refresh(); + } + + public function testToArray() + { + $expected = array( + "filter" => array("range" => array("stock" => array("gt" => 0))), + "aggs" => array( + "avg_price" => array("avg" => array("field" => "price")) + ) + ); + + $agg = new Filter("in_stock_products"); + $agg->setFilter(new Range("stock", array("gt" => 0))); + $avg = new Avg("avg_price"); + $avg->setField("price"); + $agg->addAggregation($avg); + + $this->assertEquals($expected, $agg->toArray()); + } + + public function testFilterAggregation() + { + $agg = new Filter("filter"); + $agg->setFilter(new Term(array("color" => "blue"))); + $avg = new Avg("price"); + $avg->setField("price"); + $agg->addAggregation($avg); + + $query = new Query(); + $query->addAggregation($agg); + + $results = $this->_index->search($query)->getAggregation("filter"); + $results = $results['price']['value']; + + $this->assertEquals((5 + 8) / 2.0, $results); + } + + public function testFilterNoSubAggregation() + { + $agg = new Avg("price"); + $agg->setField("price"); + + $query = new Query(); + $query->addAggregation($agg); + + $results = $this->_index->search($query)->getAggregation("price"); + $results = $results['value']; + + $this->assertEquals((5 + 8 + 1 + 3) / 4.0, $results); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/GeoDistanceTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/GeoDistanceTest.php new file mode 100644 index 00000000..7fd677b1 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/GeoDistanceTest.php @@ -0,0 +1,45 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\GeoDistance; +use Elastica\Document; +use Elastica\Query; +use Elastica\Type\Mapping; + +class GeoDistanceTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex("geo_distance"); + $mapping = new Mapping(); + $mapping->setProperties(array( + "location" => array("type" => "geo_point") + )); + $type = $this->_index->getType("test"); + $type->setMapping($mapping); + $docs = array( + new Document("1", array("location" => array("lat" => 32.849437, "lon" => -117.271732))), + new Document("2", array("location" => array("lat" => 32.798320, "lon" => -117.246648))), + new Document("3", array("location" => array("lat" => 37.782439, "lon" => -122.392560))), + ); + $type->addDocuments($docs); + $this->_index->refresh(); + } + + public function testGeoDistanceAggregation() + { + $agg = new GeoDistance("geo", "location", array("lat" => 32.804654, "lon" => -117.242594)); + $agg->addRange(null, 100); + $agg->setUnit("mi"); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("geo"); + + $this->assertEquals(2, $results['buckets'][0]['doc_count']); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/GeohashGridTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/GeohashGridTest.php new file mode 100644 index 00000000..38a047f7 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/GeohashGridTest.php @@ -0,0 +1,45 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\GeohashGrid; +use Elastica\Document; +use Elastica\Query; +use Elastica\Type\Mapping; + +class GeohashGridTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex("geohash_grid"); + $mapping = new Mapping(); + $mapping->setProperties(array( + "location" => array("type" => "geo_point") + )); + $type = $this->_index->getType("test"); + $type->setMapping($mapping); + $docs = array( + new Document("1", array("location" => array("lat" => 32.849437, "lon" => -117.271732))), + new Document("2", array("location" => array("lat" => 32.798320, "lon" => -117.246648))), + new Document("3", array("location" => array("lat" => 37.782439, "lon" => -122.392560))), + ); + $type->addDocuments($docs); + $this->_index->refresh(); + } + + public function testGeohashGridAggregation() + { + $agg = new GeohashGrid("hash", "location"); + $agg->setPrecision(3); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("hash"); + + $this->assertEquals(2, $results['buckets'][0]['doc_count']); + $this->assertEquals(1, $results['buckets'][1]['doc_count']); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/GlobalAggregationTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/GlobalAggregationTest.php new file mode 100644 index 00000000..80366f50 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/GlobalAggregationTest.php @@ -0,0 +1,27 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\Avg; +use Elastica\Aggregation\GlobalAggregation; + +class GlobalAggregationTest extends BaseAggregationTest +{ + public function testToArray() + { + $expected = array( + "global" => new \stdClass(), + "aggs" => array( + "avg_price" => array("avg" => array("field" => "price")) + ) + ); + + $agg = new GlobalAggregation("all_products"); + $avg = new Avg("avg_price"); + $avg->setField("price"); + $agg->addAggregation($avg); + $this->assertEquals($expected, $agg->toArray()); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/HistogramTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/HistogramTest.php new file mode 100644 index 00000000..35032f43 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/HistogramTest.php @@ -0,0 +1,45 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Document; +use Elastica\Aggregation\Histogram; +use Elastica\Query; + +class HistogramTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex("histogram"); + $docs = array( + new Document("1", array("price" => 5, "color" => "blue")), + new Document("2", array("price" => 8, "color" => "blue")), + new Document("3", array("price" => 1, "color" => "red")), + new Document("4", array("price" => 30, "color" => "green")), + new Document("5", array("price" => 40, "color" => "red")), + new Document("6", array("price" => 35, "color" => "green")), + new Document("7", array("price" => 42, "color" => "red")), + new Document("8", array("price" => 41, "color" => "blue")), + ); + $this->_index->getType("test")->addDocuments($docs); + $this->_index->refresh(); + } + + public function testHistogramAggregation() + { + $agg = new Histogram("hist", "price", 10); + $agg->setMinimumDocumentCount(0); // should return empty buckets + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("hist"); + + $buckets = $results['buckets']; + $this->assertEquals(5, sizeof($buckets)); + $this->assertEquals(30, $buckets[3]['key']); + $this->assertEquals(2, $buckets[3]['doc_count']); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/IpRangeTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/IpRangeTest.php new file mode 100644 index 00000000..fce6f857 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/IpRangeTest.php @@ -0,0 +1,56 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\IpRange; +use Elastica\Document; +use Elastica\Query; +use Elastica\Type\Mapping; + +class IpRangeTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex("ip_range"); + $mapping = new Mapping(); + $mapping->setProperties(array( + "address" => array("type" => "ip") + )); + $type = $this->_index->getType("test"); + $type->setMapping($mapping); + $docs = array( + new Document("1", array("address" => "192.168.1.100")), + new Document("2", array("address" => "192.168.1.150")), + new Document("3", array("address" => "192.168.1.200")), + ); + $type->addDocuments($docs); + $this->_index->refresh(); + } + + public function testIpRangeAggregation() + { + $agg = new IpRange("ip", "address"); + $agg->addRange("192.168.1.101"); + $agg->addRange(null, "192.168.1.200"); + + $cidrRange = "192.168.1.0/24"; + $agg->addMaskRange($cidrRange); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("ip"); + + foreach ($results['buckets'] as $bucket) { + if (array_key_exists('key', $bucket) && $bucket['key'] == $cidrRange) { + // the CIDR mask + $this->assertEquals(3, $bucket['doc_count']); + } else { + // the normal ip ranges + $this->assertEquals(2, $bucket['doc_count']); + } + } + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/MaxTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/MaxTest.php new file mode 100644 index 00000000..0f5475b3 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/MaxTest.php @@ -0,0 +1,72 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\Max; +use Elastica\Document; +use Elastica\Query; +use Elastica\Script; + +class MaxTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex('max'); + $docs = array( + new Document('1', array('price' => 5)), + new Document('2', array('price' => 8)), + new Document('3', array('price' => 1)), + new Document('4', array('price' => 3)), + ); + $this->_index->getType('test')->addDocuments($docs); + $this->_index->refresh(); + } + + public function testToArray() + { + $expected = array( + "max" => array( + "field" => "price", + "script" => "_value * conversion_rate", + "params" => array( + "conversion_rate" => 1.2 + ) + ), + "aggs" => array( + "subagg" => array("max" => array("field" => "foo")) + ) + ); + + $agg = new Max("min_price_in_euros"); + $agg->setField("price"); + $agg->setScript(new Script("_value * conversion_rate", array('conversion_rate' => 1.2))); + $max = new Max("subagg"); + $max->setField("foo"); + $agg->addAggregation($max); + + $this->assertEquals($expected, $agg->toArray()); + } + + public function testMaxAggregation() + { + $agg = new Max("min_price"); + $agg->setField("price"); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("min_price"); + + $this->assertEquals(8, $results['value']); + + // test using a script + $agg->setScript(new Script("_value * conversion_rate", array("conversion_rate" => 1.2))); + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("min_price"); + + $this->assertEquals(8 * 1.2, $results['value']); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/MinTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/MinTest.php new file mode 100644 index 00000000..44b52fb4 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/MinTest.php @@ -0,0 +1,38 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\Min; +use Elastica\Document; +use Elastica\Query; + +class MinTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex('min'); + $docs = array( + new Document('1', array('price' => 5)), + new Document('2', array('price' => 8)), + new Document('3', array('price' => 1)), + new Document('4', array('price' => 3)), + ); + $this->_index->getType('test')->addDocuments($docs); + $this->_index->refresh(); + } + + public function testMinAggregation() + { + $agg = new Min("min_price"); + $agg->setField("price"); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("min_price"); + + $this->assertEquals(1, $results['value']); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/MissingTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/MissingTest.php new file mode 100644 index 00000000..2a852ed0 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/MissingTest.php @@ -0,0 +1,37 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\Missing; +use Elastica\Document; +use Elastica\Query; + +class MissingTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex('missing'); + $docs = array( + new Document('1', array('price' => 5, "color" => "blue")), + new Document('2', array('price' => 8, "color" => "blue")), + new Document('3', array('price' => 1)), + new Document('4', array('price' => 3, "color" => "green")), + ); + $this->_index->getType('test')->addDocuments($docs); + $this->_index->refresh(); + } + + public function testMissingAggregation() + { + $agg = new Missing("missing", "color"); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("missing"); + + $this->assertEquals(1, $results['doc_count']); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/NestedTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/NestedTest.php new file mode 100644 index 00000000..ed6de99e --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/NestedTest.php @@ -0,0 +1,62 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\Min; +use Elastica\Aggregation\Nested; +use Elastica\Document; +use Elastica\Query; +use Elastica\Type\Mapping; + +class NestedTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex("nested"); + $mapping = new Mapping(); + $mapping->setProperties(array( + "resellers" => array( + "type" => "nested", + "properties" => array( + "name" => array("type" => "string"), + "price" => array("type" => "double") + ) + ) + )); + $type = $this->_index->getType("test"); + $type->setMapping($mapping); + $docs = array( + new Document("1", array( + "resellers" => array( + "name" => "spacely sprockets", + "price" => 5.55 + ) + )), + new Document("1", array( + "resellers" => array( + "name" => "cogswell cogs", + "price" => 4.98 + ) + )) + ); + $type->addDocuments($docs); + $this->_index->refresh(); + } + + public function testNestedAggregation() + { + $agg = new Nested("resellers", "resellers"); + $min = new Min("min_price"); + $min->setField("price"); + $agg->addAggregation($min); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("resellers"); + + $this->assertEquals(4.98, $results['min_price']['value']); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/RangeTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/RangeTest.php new file mode 100644 index 00000000..fb5ca2fe --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/RangeTest.php @@ -0,0 +1,41 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\Range; +use Elastica\Document; +use Elastica\Query; + +class RangeTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex('range'); + $docs = array( + new Document('1', array('price' => 5)), + new Document('2', array('price' => 8)), + new Document('3', array('price' => 1)), + new Document('4', array('price' => 3)), + new Document('5', array('price' => 1.5)), + new Document('6', array('price' => 2)), + ); + $this->_index->getType('test')->addDocuments($docs); + $this->_index->refresh(); + } + + public function testRangeAggregation() + { + $agg = new Range("range"); + $agg->setField("price"); + $agg->addRange(1.5, 5); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("range"); + + $this->assertEquals(2, $results['buckets'][0]['doc_count']); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/ReverseNestedTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/ReverseNestedTest.php new file mode 100644 index 00000000..215dac63 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/ReverseNestedTest.php @@ -0,0 +1,124 @@ +<?php + +namespace Elastica\Test\Aggregation; + +use Elastica\Aggregation\Terms; +use Elastica\Aggregation\Nested; +use Elastica\Aggregation\ReverseNested; +use Elastica\Document; +use Elastica\Query; +use Elastica\Type\Mapping; + +class ReverseNestedTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex("nested"); + $mapping = new Mapping(); + $mapping->setProperties(array( + "comments" => array( + "type" => "nested", + "properties" => array( + "name" => array("type" => "string"), + "body" => array("type" => "string") + ) + ) + )); + $type = $this->_index->getType("test"); + $type->setMapping($mapping); + $docs = array( + new Document("1", array( + "comments" => array( + array( + "name" => "bob", + "body" => "this is bobs comment", + ), + array( + "name" => "john", + "body" => "this is johns comment", + ), + ), + "tags" => array("foo", "bar"), + )), + new Document("2", array( + "comments" => array( + array( + "name" => "bob", + "body" => "this is another comment from bob", + ), + array( + "name" => "susan", + "body" => "this is susans comment", + ), + ), + "tags" => array("foo", "baz"), + )) + ); + $type->addDocuments($docs); + $this->_index->refresh(); + } + + public function testPathNotSetIfNull() + { + $agg = new ReverseNested('nested'); + $this->assertFalse($agg->hasParam('path')); + } + + public function testPathSetIfNotNull() + { + $agg = new ReverseNested('nested', 'some_field'); + $this->assertEquals('some_field', $agg->getParam('path')); + } + + public function testReverseNestedAggregation() + { + $agg = new Nested("comments", "comments"); + $names = new Terms("name"); + $names->setField("comments.name"); + + $tags = new Terms("tags"); + $tags->setField("tags"); + + $reverseNested = new ReverseNested("main"); + $reverseNested->addAggregation($tags); + + $names->addAggregation($reverseNested); + + $agg->addAggregation($names); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("comments"); + + $this->assertArrayHasKey('name', $results); + $nameResults = $results['name']; + + $this->assertCount(3, $nameResults['buckets']); + + // bob + $this->assertEquals('bob', $nameResults['buckets'][0]['key']); + $tags = array( + array('key' => 'foo', 'doc_count' => 2), + array('key' => 'bar', 'doc_count' => 1), + array('key' => 'baz', 'doc_count' => 1), + ); + $this->assertEquals($tags, $nameResults['buckets'][0]['main']['tags']['buckets']); + + // john + $this->assertEquals('john', $nameResults['buckets'][1]['key']); + $tags = array( + array('key' => 'bar', 'doc_count' => 1), + array('key' => 'foo', 'doc_count' => 1), + ); + $this->assertEquals($tags, $nameResults['buckets'][1]['main']['tags']['buckets']); + + // susan + $this->assertEquals('susan', $nameResults['buckets'][2]['key']); + $tags = array( + array('key' => 'baz', 'doc_count' => 1), + array('key' => 'foo', 'doc_count' => 1), + ); + $this->assertEquals($tags, $nameResults['buckets'][2]['main']['tags']['buckets']); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/StatsTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/StatsTest.php new file mode 100644 index 00000000..2d315abf --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/StatsTest.php @@ -0,0 +1,42 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\Stats; +use Elastica\Document; +use Elastica\Query; + +class StatsTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex('stats'); + $docs = array( + new Document('1', array('price' => 5)), + new Document('2', array('price' => 8)), + new Document('3', array('price' => 1)), + new Document('4', array('price' => 3)), + ); + $this->_index->getType('test')->addDocuments($docs); + $this->_index->refresh(); + } + + public function testStatsAggregation() + { + $agg = new Stats("stats"); + $agg->setField("price"); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("stats"); + + $this->assertEquals(4, $results['count']); + $this->assertEquals(1, $results['min']); + $this->assertEquals(8, $results['max']); + $this->assertEquals((5 + 8 + 1 + 3) / 4.0, $results['avg']); + $this->assertEquals((5 + 8 + 1 + 3), $results['sum']); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/SumTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/SumTest.php new file mode 100644 index 00000000..3b3c56a2 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/SumTest.php @@ -0,0 +1,38 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\Sum; +use Elastica\Document; +use Elastica\Query; + +class SumTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex('sum'); + $docs = array( + new Document('1', array('price' => 5)), + new Document('2', array('price' => 8)), + new Document('3', array('price' => 1)), + new Document('4', array('price' => 3)), + ); + $this->_index->getType('test')->addDocuments($docs); + $this->_index->refresh(); + } + + public function testSumAggregation() + { + $agg = new Sum("sum"); + $agg->setField("price"); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("sum"); + + $this->assertEquals(5 + 8 + 1 + 3, $results['value']); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/TermsTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/TermsTest.php new file mode 100644 index 00000000..d9f37a20 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/TermsTest.php @@ -0,0 +1,39 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\Terms; +use Elastica\Document; +use Elastica\Query; + +class TermsTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex("terms"); + $docs = array( + new Document("1", array("color" => "blue")), + new Document("2", array("color" => "blue")), + new Document("3", array("color" => "red")), + new Document("4", array("color" => "green")), + ); + $this->_index->getType("test")->addDocuments($docs); + $this->_index->refresh(); + } + + public function testTermsAggregation() + { + $agg = new Terms("terms"); + $agg->setField("color"); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("terms"); + + $this->assertEquals(2, $results['buckets'][0]['doc_count']); + $this->assertEquals("blue", $results['buckets'][0]['key']); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/ValueCountTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/ValueCountTest.php new file mode 100644 index 00000000..5eba9ea4 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/ValueCountTest.php @@ -0,0 +1,38 @@ +<?php + +namespace Elastica\Test\Aggregation; + + +use Elastica\Aggregation\ValueCount; +use Elastica\Document; +use Elastica\Query; + +class ValueCountTest extends BaseAggregationTest +{ + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex('value_count'); + $docs = array( + new Document('1', array('price' => 5)), + new Document('2', array('price' => 8)), + new Document('3', array('price' => 1)), + new Document('4', array('price' => 3)), + new Document('5', array('price' => 3)), + ); + $this->_index->getType('test')->addDocuments($docs); + $this->_index->refresh(); + } + + public function testValueCountAggregation() + { + $agg = new ValueCount("count", "price"); + + $query = new Query(); + $query->addAggregation($agg); + $results = $this->_index->search($query)->getAggregation("count"); + + $this->assertEquals(5, $results['value']); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Base.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Base.php new file mode 100644 index 00000000..55cd8873 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Base.php @@ -0,0 +1,31 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Client; + +class Base extends \PHPUnit_Framework_TestCase +{ + protected function _getClient() + { + return new Client(array( + 'host' => getenv('ES_HOST') ?: 'localhost', + 'port' => getenv('ES_PORT') ?: 9200, + )); + } + + /** + * @param string $name Index name + * @param bool $delete Delete index if it exists + * @param int $shards Number of shards to create + * @return \Elastica\Index + */ + protected function _createIndex($name = 'test', $delete = true, $shards = 1) + { + $client = $this->_getClient(); + $index = $client->getIndex('elastica_' . $name); + $index->create(array('index' => array('number_of_shards' => $shards, 'number_of_replicas' => 0)), $delete); + + return $index; + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Bulk/ActionTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Bulk/ActionTest.php new file mode 100644 index 00000000..178883a8 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Bulk/ActionTest.php @@ -0,0 +1,69 @@ +<?php + +namespace Elastica\Test\Bulk; + +use Elastica\Bulk\Action; +use Elastica\Bulk; +use Elastica\Client; +use Elastica\Exception\Bulk\ResponseException; +use Elastica\Index; +use Elastica\Test\Base as BaseTest; +use Elastica\Bulk\ResponseSet; +use Elastica\Response; +use Elastica\Type; + +class ActionTest extends BaseTest +{ + public function testAction() + { + $action = new Action(); + $this->assertEquals('index', $action->getOpType()); + $this->assertFalse($action->hasSource()); + + $expected = '{"index":{}}' . "\n"; + $this->assertEquals($expected, $action->toString()); + + $action->setIndex('index'); + + $expected = '{"index":{"_index":"index"}}' . "\n"; + $this->assertEquals($expected, $action->toString()); + + $action->setType('type'); + + $expected = '{"index":{"_index":"index","_type":"type"}}' . "\n"; + $this->assertEquals($expected, $action->toString()); + + $action->setId(1); + $expected = '{"index":{"_index":"index","_type":"type","_id":1}}' . "\n"; + $this->assertEquals($expected, $action->toString()); + + $action->setRouting(1); + $expected = '{"index":{"_index":"index","_type":"type","_id":1,"_routing":1}}' . "\n"; + $this->assertEquals($expected, $action->toString()); + + $client = new Client(); + $index = new Index($client, 'index2'); + $type = new Type($index, 'type2'); + + $action->setIndex($index); + + $expected = '{"index":{"_index":"index2","_type":"type","_id":1,"_routing":1}}' . "\n"; + $this->assertEquals($expected, $action->toString()); + + $action->setType($type); + + $expected = '{"index":{"_index":"index2","_type":"type2","_id":1,"_routing":1}}' . "\n"; + $this->assertEquals($expected, $action->toString()); + + $action->setSource(array('user' => 'name')); + + $expected = '{"index":{"_index":"index2","_type":"type2","_id":1,"_routing":1}}' . "\n"; + $expected.= '{"user":"name"}' . "\n"; + + $this->assertEquals($expected, $action->toString()); + $this->assertTrue($action->hasSource()); + + $this->assertFalse(Action::isValidOpType('foo')); + $this->assertTrue(Action::isValidOpType('delete')); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Bulk/ResponseSetTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Bulk/ResponseSetTest.php new file mode 100644 index 00000000..d1495fce --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Bulk/ResponseSetTest.php @@ -0,0 +1,188 @@ +<?php + +namespace Elastica\Test\Bulk; + +use Elastica\Bulk\Action; +use Elastica\Bulk; +use Elastica\Exception\Bulk\ResponseException; +use Elastica\Test\Base as BaseTest; +use Elastica\Bulk\ResponseSet; +use Elastica\Response; + +class ResponseSetTest extends BaseTest +{ + /** + * @dataProvider isOkDataProvider + */ + public function testIsOk($responseData, $actions, $expected) + { + $responseSet = $this->_createResponseSet($responseData, $actions); + $this->assertEquals($expected, $responseSet->isOk()); + } + + public function testGetError() + { + list($responseData, $actions) = $this->_getFixture(); + $responseData['items'][1]['index']['ok'] = false; + $responseData['items'][1]['index']['error'] = 'SomeExceptionMessage'; + $responseData['items'][2]['index']['ok'] = false; + $responseData['items'][2]['index']['error'] = 'AnotherExceptionMessage'; + + try { + $this->_createResponseSet($responseData, $actions); + $this->fail('Bulk request should fail'); + } catch (ResponseException $e) { + $responseSet = $e->getResponseSet(); + + $this->assertInstanceOf('Elastica\\Bulk\\ResponseSet', $responseSet); + + $this->assertTrue($responseSet->hasError()); + $this->assertNotEquals('AnotherExceptionMessage', $responseSet->getError()); + $this->assertEquals('SomeExceptionMessage', $responseSet->getError()); + + $actionExceptions = $e->getActionExceptions(); + $this->assertEquals(2, count($actionExceptions)); + + $this->assertInstanceOf('Elastica\Exception\Bulk\Response\ActionException', $actionExceptions[0]); + $this->assertSame($actions[1], $actionExceptions[0]->getAction()); + $this->assertContains('SomeExceptionMessage', $actionExceptions[0]->getMessage()); + $this->assertTrue($actionExceptions[0]->getResponse()->hasError()); + + $this->assertInstanceOf('Elastica\Exception\Bulk\Response\ActionException', $actionExceptions[1]); + $this->assertSame($actions[2], $actionExceptions[1]->getAction()); + $this->assertContains('AnotherExceptionMessage', $actionExceptions[1]->getMessage()); + $this->assertTrue($actionExceptions[1]->getResponse()->hasError()); + } + } + + public function testGetBulkResponses() + { + list($responseData, $actions) = $this->_getFixture(); + + $responseSet = $this->_createResponseSet($responseData, $actions); + + $bulkResponses = $responseSet->getBulkResponses(); + $this->assertInternalType('array', $bulkResponses); + $this->assertEquals(3, count($bulkResponses)); + + foreach ($bulkResponses as $i => $bulkResponse) { + $this->assertInstanceOf('Elastica\\Bulk\\Response', $bulkResponse); + $bulkResponseData = $bulkResponse->getData(); + $this->assertInternalType('array', $bulkResponseData); + $this->assertArrayHasKey('_id', $bulkResponseData); + $this->assertEquals($responseData['items'][$i]['index']['_id'], $bulkResponseData['_id']); + $this->assertSame($actions[$i], $bulkResponse->getAction()); + $this->assertEquals('index', $bulkResponse->getOpType()); + } + } + + public function testIterator() + { + list($responseData, $actions) = $this->_getFixture(); + + $responseSet = $this->_createResponseSet($responseData, $actions); + + $this->assertEquals(3, count($responseSet)); + + foreach ($responseSet as $i => $bulkResponse) { + $this->assertInstanceOf('Elastica\Bulk\Response', $bulkResponse); + $bulkResponseData = $bulkResponse->getData(); + $this->assertInternalType('array', $bulkResponseData); + $this->assertArrayHasKey('_id', $bulkResponseData); + $this->assertEquals($responseData['items'][$i]['index']['_id'], $bulkResponseData['_id']); + $this->assertSame($actions[$i], $bulkResponse->getAction()); + $this->assertEquals('index', $bulkResponse->getOpType()); + } + + $this->assertFalse($responseSet->valid()); + $this->assertNotInstanceOf('Elastica\Bulk\Response', $responseSet->current()); + $this->assertFalse($responseSet->current()); + + $responseSet->next(); + + $this->assertFalse($responseSet->valid()); + $this->assertNotInstanceOf('Elastica\Bulk\Response', $responseSet->current()); + $this->assertFalse($responseSet->current()); + + $responseSet->rewind(); + + $this->assertEquals(0, $responseSet->key()); + $this->assertTrue($responseSet->valid()); + $this->assertInstanceOf('Elastica\Bulk\Response', $responseSet->current()); + } + + public function isOkDataProvider() + { + list($responseData, $actions) = $this->_getFixture(); + + $return = array(); + $return[] = array($responseData, $actions, true); + $responseData['items'][2]['index']['ok'] = false; + $return[] = array($responseData, $actions, false); + return $return; + } + + /** + * @param array $responseData + * @param array $actions + * @return \Elastica\Bulk\ResponseSet + */ + protected function _createResponseSet(array $responseData, array $actions) + { + $client = $this->getMock('Elastica\\Client', array('request')); + + $client->expects($this->once()) + ->method('request') + ->withAnyParameters() + ->will($this->returnValue(new Response($responseData))); + + $bulk = new Bulk($client); + $bulk->addActions($actions); + return $bulk->send(); + } + + /** + * @return array + */ + protected function _getFixture() + { + $responseData = array( + 'took' => 5, + 'items' => array( + array( + 'index' => array( + '_index' => 'index', + '_type' => 'type', + '_id' => '1', + '_version' => 1, + 'ok' => true, + ) + ), + array( + 'index' => array( + '_index' => 'index', + '_type' => 'type', + '_id' => '2', + '_version' => 1, + 'ok' => true, + ) + ), + array( + 'index' => array( + '_index' => 'index', + '_type' => 'type', + '_id' => '3', + '_version' => 1, + 'ok' => true, + ) + ) + ) + ); + $bulkResponses = array( + new Action(), + new Action(), + new Action(), + ); + return array($responseData, $bulkResponses); + } +}
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/BulkTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/BulkTest.php new file mode 100644 index 00000000..3396fe86 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/BulkTest.php @@ -0,0 +1,711 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Bulk; +use Elastica\Bulk\Action; +use Elastica\Client; +use Elastica\Document; +use Elastica\Exception\Bulk\ResponseException; +use Elastica\Exception\InvalidException; +use Elastica\Exception\NotFoundException; +use Elastica\Test\Base as BaseTest; +use Elastica\Bulk\Action\AbstractDocument; +use Elastica\Filter\Script; + +class BulkTest extends BaseTest +{ + + public function testSend() + { + $index = $this->_createIndex(); + $type = $index->getType('bulk_test'); + $type2 = $index->getType('bulk_test2'); + $client = $index->getClient(); + + $newDocument1 = $type->createDocument(1, array('name' => 'Mister Fantastic')); + $newDocument2 = new Document(2, array('name' => 'Invisible Woman')); + $newDocument3 = $type->createDocument(3, array('name' => 'The Human Torch')); + $newDocument4 = $type->createDocument(null, array('name' => 'The Thing')); + + $newDocument1->setPercolate('*'); + $newDocument3->setOpType(Document::OP_TYPE_CREATE); + + $documents = array( + $newDocument1, + $newDocument2, + $newDocument3, + $newDocument4 + ); + + $bulk = new Bulk($client); + $bulk->setType($type2); + $bulk->addDocuments($documents); + + $actions = $bulk->getActions(); + + $this->assertInstanceOf('Elastica\Bulk\Action\IndexDocument', $actions[0]); + $this->assertEquals('index', $actions[0]->getOpType()); + $this->assertSame($newDocument1, $actions[0]->getDocument()); + + $this->assertInstanceOf('Elastica\Bulk\Action\IndexDocument', $actions[1]); + $this->assertEquals('index', $actions[1]->getOpType()); + $this->assertSame($newDocument2, $actions[1]->getDocument()); + + $this->assertInstanceOf('Elastica\Bulk\Action\CreateDocument', $actions[2]); + $this->assertEquals('create', $actions[2]->getOpType()); + $this->assertSame($newDocument3, $actions[2]->getDocument()); + + $this->assertInstanceOf('Elastica\Bulk\Action\IndexDocument', $actions[3]); + $this->assertEquals('index', $actions[3]->getOpType()); + $this->assertSame($newDocument4, $actions[3]->getDocument()); + + $data = $bulk->toArray(); + + $expected = array( + array('index' => array('_index' => 'elastica_test', '_type' => 'bulk_test', '_id' => 1, '_percolate' => '*')), + array('name' => 'Mister Fantastic'), + array('index' => array('_id' => 2)), + array('name' => 'Invisible Woman'), + array('create' => array('_index' => 'elastica_test', '_type' => 'bulk_test', '_id' => 3)), + array('name' => 'The Human Torch'), + array('index' => array('_index' => 'elastica_test', '_type' => 'bulk_test')), + array('name' => 'The Thing'), + ); + $this->assertEquals($expected, $data); + + $expected = '{"index":{"_index":"elastica_test","_type":"bulk_test","_id":1,"_percolate":"*"}} +{"name":"Mister Fantastic"} +{"index":{"_id":2}} +{"name":"Invisible Woman"} +{"create":{"_index":"elastica_test","_type":"bulk_test","_id":3}} +{"name":"The Human Torch"} +{"index":{"_index":"elastica_test","_type":"bulk_test"}} +{"name":"The Thing"} +'; + + $expected = str_replace(PHP_EOL, "\n", $expected); + $this->assertEquals($expected, (string)str_replace(PHP_EOL, "\n", (string)$bulk)); + + $response = $bulk->send(); + + $this->assertInstanceOf('Elastica\Bulk\ResponseSet', $response); + + $this->assertTrue($response->isOk()); + $this->assertFalse($response->hasError()); + + foreach ($response as $i => $bulkResponse) { + $this->assertInstanceOf('Elastica\Bulk\Response', $bulkResponse); + $this->assertTrue($bulkResponse->isOk()); + $this->assertFalse($bulkResponse->hasError()); + $this->assertSame($actions[$i], $bulkResponse->getAction()); + } + + $type->getIndex()->refresh(); + $type2->getIndex()->refresh(); + + $this->assertEquals(3, $type->count()); + $this->assertEquals(1, $type2->count()); + + + $bulk = new Bulk($client); + $bulk->addDocument($newDocument3, Action::OP_TYPE_DELETE); + + $data = $bulk->toArray(); + + $expected = array( + array('delete' => array('_index' => 'elastica_test', '_type' => 'bulk_test', '_id' => 3)), + ); + $this->assertEquals($expected, $data); + + $bulk->send(); + + $type->getIndex()->refresh(); + + $this->assertEquals(2, $type->count()); + + try { + $type->getDocument(3); + $this->fail('Document #3 should be deleted'); + } catch (NotFoundException $e) { + $this->assertTrue(true); + } + } + + public function testUnicodeBulkSend() + { + $index = $this->_createIndex(); + $type = $index->getType('bulk_test'); + $type2 = $index->getType('bulk_test2'); + $client = $index->getClient(); + + $newDocument1 = $type->createDocument(1, array('name' => 'Сегодня, я вижу, особенно грустен твой взгляд,')); + $newDocument2 = new Document(2, array('name' => 'И руки особенно тонки, колени обняв.')); + $newDocument3 = $type->createDocument(3, array('name' => 'Послушай: далеко, далеко, на озере Чад / Изысканный бродит жираф.')); + + $documents = array( + $newDocument1, + $newDocument2, + $newDocument3 + ); + + $bulk = new Bulk($client); + $bulk->setType($type2); + $bulk->addDocuments($documents); + + $actions = $bulk->getActions(); + + $this->assertSame($newDocument1, $actions[0]->getDocument()); + $this->assertSame($newDocument2, $actions[1]->getDocument()); + $this->assertSame($newDocument3, $actions[2]->getDocument()); + } + + public function testSetIndexType() + { + $client = new Client(); + $index = $client->getIndex('index'); + $type = $index->getType('type'); + + $index2 = $client->getIndex('index2'); + $type2 = $index2->getType('type2'); + + $bulk = new Bulk($client); + + $this->assertFalse($bulk->hasIndex()); + $this->assertFalse($bulk->hasType()); + + $bulk->setIndex($index); + $this->assertTrue($bulk->hasIndex()); + $this->assertFalse($bulk->hasType()); + $this->assertEquals('index', $bulk->getIndex()); + + $bulk->setType($type2); + $this->assertTrue($bulk->hasIndex()); + $this->assertTrue($bulk->hasType()); + $this->assertEquals('index2', $bulk->getIndex()); + $this->assertEquals('type2', $bulk->getType()); + + $bulk->setType($type); + $this->assertTrue($bulk->hasIndex()); + $this->assertTrue($bulk->hasType()); + $this->assertEquals('index', $bulk->getIndex()); + $this->assertEquals('type', $bulk->getType()); + + $bulk->setIndex($index2); + $this->assertTrue($bulk->hasIndex()); + $this->assertTrue($bulk->hasType()); + $this->assertEquals('index2', $bulk->getIndex()); + $this->assertEquals('type', $bulk->getType()); + } + + public function testAddActions() + { + $client = new Client(); + $bulk = new Bulk($client); + + $action1 = new Action(Action::OP_TYPE_DELETE); + $action1->setIndex('index'); + $action1->setType('type'); + $action1->setId(1); + + $action2 = new Action(Action::OP_TYPE_INDEX); + $action2->setIndex('index'); + $action2->setType('type'); + $action2->setId(1); + $action2->setSource(array('name' => 'Batman')); + + $actions = array( + $action1, + $action2 + ); + + $bulk->addActions($actions); + + $getActions = $bulk->getActions(); + + $this->assertSame($action1, $getActions[0]); + $this->assertSame($action2, $getActions[1]); + } + + public function testAddRawData() + { + $bulk = new Bulk($this->_getClient()); + + $rawData = array( + array('index' => array('_index' => 'test', '_type' => 'user', '_id' => '1')), + array('user' => array('name' => 'hans')), + array('delete' => array('_index' => 'test', '_type' => 'user', '_id' => '2')), + array('delete' => array('_index' => 'test', '_type' => 'user', '_id' => '3')), + array('create' => array('_index' => 'test', '_type' => 'user', '_id' => '4')), + array('user' => array('name' => 'mans')), + array('delete' => array('_index' => 'test', '_type' => 'user', '_id' => '5')), + ); + + $bulk->addRawData($rawData); + + $actions = $bulk->getActions(); + + $this->assertInternalType('array', $actions); + $this->assertEquals(5, count($actions)); + + $this->assertInstanceOf('Elastica\Bulk\Action', $actions[0]); + $this->assertEquals('index', $actions[0]->getOpType()); + $this->assertEquals($rawData[0]['index'], $actions[0]->getMetadata()); + $this->assertTrue($actions[0]->hasSource()); + $this->assertEquals($rawData[1], $actions[0]->getSource()); + + $this->assertInstanceOf('Elastica\Bulk\Action', $actions[1]); + $this->assertEquals('delete', $actions[1]->getOpType()); + $this->assertEquals($rawData[2]['delete'], $actions[1]->getMetadata()); + $this->assertFalse($actions[1]->hasSource()); + + $this->assertInstanceOf('Elastica\Bulk\Action', $actions[2]); + $this->assertEquals('delete', $actions[2]->getOpType()); + $this->assertEquals($rawData[3]['delete'], $actions[2]->getMetadata()); + $this->assertFalse($actions[2]->hasSource()); + + $this->assertInstanceOf('Elastica\Bulk\Action', $actions[3]); + $this->assertEquals('create', $actions[3]->getOpType()); + $this->assertEquals($rawData[4]['create'], $actions[3]->getMetadata()); + $this->assertTrue($actions[3]->hasSource()); + $this->assertEquals($rawData[5], $actions[3]->getSource()); + + $this->assertInstanceOf('Elastica\Bulk\Action', $actions[4]); + $this->assertEquals('delete', $actions[4]->getOpType()); + $this->assertEquals($rawData[6]['delete'], $actions[4]->getMetadata()); + $this->assertFalse($actions[4]->hasSource()); + } + + /** + * @dataProvider invalidRawDataProvider + * @expectedException \Elastica\Exception\InvalidException + */ + public function testInvalidRawData($rawData, $failMessage) + { + $bulk = new Bulk($this->_getClient()); + + $bulk->addRawData($rawData); + + $this->fail($failMessage); + } + + public function invalidRawDataProvider() + { + return array( + array( + array( + array('index' => array('_index' => 'test', '_type' => 'user', '_id' => '1')), + array('user' => array('name' => 'hans')), + array('user' => array('name' => 'mans')), + ), + 'Two sources for one action' + ), + array( + array( + array('index' => array('_index' => 'test', '_type' => 'user', '_id' => '1')), + array('user' => array('name' => 'hans')), + array('upsert' => array('_index' => 'test', '_type' => 'user', '_id' => '2')), + ), + 'Invalid optype for action' + ), + array( + array( + array('user' => array('name' => 'mans')), + ), + 'Source without action' + ), + array( + array( + array(), + ), + 'Empty array' + ), + array( + array( + 'dummy', + ), + 'String as data' + ) + ); + } + + public function testCreateAbstractDocumentWithInvalidData() + { + //Wrong class type + try { + $badDocument = new \stdClass(); + AbstractDocument::create($badDocument); + $this->fail('Tried to create an abstract document with an object that is not a Document or Script, but no exception was thrown'); + } catch (\Exception $e) { + //Excepted exception was thrown. + } + + //Try to create document with a script + try { + $script = new Script(); + AbstractDocument::create($script, AbstractDocument::OP_TYPE_CREATE); + $this->fail('Tried to create an abstract document with a Script, but no exception was thrown'); + } catch (\Exception $e) { + //Excepted exception was thrown. + } + } + + public function testErrorRequest() + { + $index = $this->_createIndex(); + $type = $index->getType('bulk_test'); + $client = $index->getClient(); + + $documents = array( + $type->createDocument(1, array('name' => 'Mister Fantastic')), + $type->createDocument(2, array('name' => 'Invisible Woman')), + $type->createDocument(2, array('name' => 'The Human Torch')), + ); + + $documents[2]->setOpType(Document::OP_TYPE_CREATE); + + $bulk = new Bulk($client); + $bulk->addDocuments($documents); + + try { + $bulk->send(); + $bulk->fail('3rd document create should produce error'); + } catch (ResponseException $e) { + $this->assertContains('DocumentAlreadyExists', $e->getMessage()); + $failures = $e->getFailures(); + $this->assertInternalType('array', $failures); + $this->assertArrayHasKey(0, $failures); + $this->assertContains('DocumentAlreadyExists', $failures[0]); + } + } + + public function testRawDocumentDataRequest() + { + $index = $this->_createIndex(); + $type = $index->getType('bulk_test'); + $client = $index->getClient(); + + $documents = array( + new Document(null, '{"name":"Mister Fantastic"}'), + new Document(null, '{"name":"Invisible Woman"}'), + new Document(null, '{"name":"The Human Torch"}'), + ); + + $bulk = new Bulk($client); + $bulk->addDocuments($documents); + $bulk->setType($type); + + $expectedJson = '{"index":{}} +{"name":"Mister Fantastic"} +{"index":{}} +{"name":"Invisible Woman"} +{"index":{}} +{"name":"The Human Torch"} +'; + $expectedJson = str_replace(PHP_EOL, "\n", $expectedJson); + $this->assertEquals($expectedJson, $bulk->toString()); + + $response = $bulk->send(); + $this->assertTrue($response->isOk()); + + $type->getIndex()->refresh(); + + $response = $type->search(); + $this->assertEquals(3, $response->count()); + + foreach (array("Mister", "Invisible", "Torch") as $name) { + $result = $type->search($name); + $this->assertEquals(1, count($result->getResults())); + } + } + + /** + * @dataProvider udpDataProvider + */ + public function testUdp($clientConfig, $host, $port, $shouldFail = false) + { + if (!function_exists('socket_create')) { + $this->markTestSkipped('Function socket_create() does not exist.'); + } + $client = new Client($clientConfig); + $index = $client->getIndex('elastica_test'); + $index->create(array('index' => array('number_of_shards' => 1, 'number_of_replicas' => 0)), true); + $type = $index->getType('udp_test'); + $client = $index->getClient(); + + $type->setMapping(array('name' => array('type' => 'string'))); + + $docs = array( + $type->createDocument(1, array('name' => 'Mister Fantastic')), + $type->createDocument(2, array('name' => 'Invisible Woman')), + $type->createDocument(3, array('name' => 'The Human Torch')), + $type->createDocument(4, array('name' => 'The Thing')), + $type->createDocument(5, array('name' => 'Mole Man')), + $type->createDocument(6, array('name' => 'The Skrulls')), + ); + + $bulk = new Bulk($client); + $bulk->addDocuments($docs); + + $bulk->sendUdp($host, $port); + + $i = 0; + $limit = 20; + do { + usleep(200000); + } while ($type->count() < 6 && ++$i < $limit); + + if ($shouldFail) { + $this->assertEquals($limit, $i, 'Invalid udp connection data. Test should fail'); + } else { + $this->assertLessThan($limit, $i, 'It took too much time waiting for UDP request result'); + + foreach ($docs as $doc) { + $getDoc = $type->getDocument($doc->getId()); + $this->assertEquals($doc->getData(), $getDoc->getData()); + } + } + } + + public function testUpdate() + { + $index = $this->_createIndex(); + $type = $index->getType('bulk_test'); + $client = $index->getClient(); + + $doc1 = $type->createDocument(1, array('name' => 'John')); + $doc2 = $type->createDocument(2, array('name' => 'Paul')); + $doc3 = $type->createDocument(3, array('name' => 'George')); + $doc4 = $type->createDocument(4, array('name' => 'Ringo')); + $documents = array($doc1, $doc2, $doc3, $doc4); + + //index some documents + $bulk = new Bulk($client); + $bulk->setType($type); + $bulk->addDocuments($documents); + $response = $bulk->send(); + + $this->assertTrue($response->isOk()); + $this->assertFalse($response->hasError()); + + $index->refresh(); + + //test updating via document + $doc2 = $type->createDocument(2, array('name' => 'The Walrus')); + $bulk = new Bulk($client); + $bulk->setType($type); + $updateAction = new \Elastica\Bulk\Action\UpdateDocument($doc2); + $bulk->addAction($updateAction); + $response = $bulk->send(); + + $this->assertTrue($response->isOk()); + $this->assertFalse($response->hasError()); + + $index->refresh(); + + $doc = $type->getDocument(2); + $docData = $doc->getData(); + $this->assertEquals('The Walrus', $docData['name']); + + //test updating via script + $script = new \Elastica\Script('ctx._source.name += param1;', array('param1' => ' was Paul'), null, 2); + $doc2 = new Document(); + $script->setUpsert($doc2); + $updateAction = Action\AbstractDocument::create($script, Action::OP_TYPE_UPDATE); + $bulk = new Bulk($client); + $bulk->setType($type); + $bulk->addAction($updateAction); + $response = $bulk->send(); + + $this->assertTrue($response->isOk()); + $this->assertFalse($response->hasError()); + + $index->refresh(); + + $doc2 = $type->getDocument(2); + $this->assertEquals('The Walrus was Paul', $doc2->name); + + //test upsert + $script = new \Elastica\Script('ctx._scource.counter += count', array('count' => 1), null, 5); + $doc = new Document('', array('counter' => 1)); + $script->setUpsert($doc); + $updateAction = Action\AbstractDocument::create($script, Action::OP_TYPE_UPDATE); + $bulk = new Bulk($client); + $bulk->setType($type); + $bulk->addAction($updateAction); + $response = $bulk->send(); + + $this->assertTrue($response->isOk()); + $this->assertFalse($response->hasError()); + + $index->refresh(); + $doc = $type->getDocument(5); + $this->assertEquals(1, $doc->counter); + + //test doc_as_upsert + $doc = new \Elastica\Document(6, array('test' => 'test')); + $doc->setDocAsUpsert(true); + $updateAction = Action\AbstractDocument::create($doc, Action::OP_TYPE_UPDATE); + $bulk = new Bulk($client); + $bulk->setType($type); + $bulk->addAction($updateAction); + $response = $bulk->send(); + + $this->assertTrue($response->isOk()); + $this->assertFalse($response->hasError()); + + $index->refresh(); + $doc = $type->getDocument(6); + $this->assertEquals('test', $doc->test); + + //test doc_as_upsert with set of documents (use of addDocuments) + $doc1 = new \Elastica\Document(7, array('test' => 'test1')); + $doc1->setDocAsUpsert(true); + $doc2 = new \Elastica\Document(8, array('test' => 'test2')); + $doc2->setDocAsUpsert(true); + $docs = array($doc1, $doc2); + $bulk = new Bulk($client); + $bulk->setType($type); + $bulk->addDocuments($docs, \Elastica\Bulk\Action::OP_TYPE_UPDATE); + $response = $bulk->send(); + + $this->assertTrue($response->isOk()); + $this->assertFalse($response->hasError()); + + $index->refresh(); + $doc = $type->getDocument(7); + $this->assertEquals('test1', $doc->test); + $doc = $type->getDocument(8); + $this->assertEquals('test2', $doc->test); + + //test updating via document with json string as data + $doc3 = $type->createDocument(2); + $bulk = new Bulk($client); + $bulk->setType($type); + $doc3->setData('{"name" : "Paul it is"}'); + $updateAction = new \Elastica\Bulk\Action\UpdateDocument($doc3); + $bulk->addAction($updateAction); + $response = $bulk->send(); + + $this->assertTrue($response->isOk()); + $this->assertFalse($response->hasError()); + + $index->refresh(); + + $doc = $type->getDocument(2); + $docData = $doc->getData(); + $this->assertEquals('Paul it is', $docData['name']); + + $index->delete(); + } + + public function testGetPath() + { + $client = $this->_getClient(); + $bulk = new Bulk($client); + + $this->assertEquals('_bulk', $bulk->getPath()); + + $indexName = 'testIndex'; + + $bulk->setIndex($indexName); + $this->assertEquals($indexName . '/_bulk', $bulk->getPath()); + + $typeName = 'testType'; + $bulk->setType($typeName); + $this->assertEquals($indexName . '/' . $typeName . '/_bulk', $bulk->getPath()); + } + + public function testRetry() + { + $index = $this->_createIndex(); + $type = $index->getType('bulk_test'); + $client = $index->getClient(); + + $doc1 = $type->createDocument(1, array('name' => 'Mister Fantastic')); + $doc1->setOpType(Action::OP_TYPE_UPDATE); + $doc1->setRetryOnConflict(5); + + $bulk = new Bulk($client); + $bulk->addDocument($doc1); + + $actions = $bulk->getActions(); + + $metadata = $actions[0]->getMetadata(); + $this->assertEquals(5, $metadata[ '_retry_on_conflict' ]); + + $script = new \Elastica\Script( '' ); + $script->setRetryOnConflict(5); + + $bulk = new Bulk($client); + $bulk->addScript($script); + + $actions = $bulk->getActions(); + + $metadata = $actions[0]->getMetadata(); + $this->assertEquals(5, $metadata[ '_retry_on_conflict' ]); + } + + public function udpDataProvider() + { + return array( + array( + array(), + null, + null + ), + array( + array(), + 'localhost', + null + ), + array( + array(), + null, + 9700 + ), + array( + array(), + 'localhost', + 9700 + ), + array( + array( + 'udp' => array( + 'host' => 'localhost', + 'port' => 9700, + ) + ), + null, + null + ), + array( + array( + 'udp' => array( + 'host' => 'localhost', + 'port' => 9800, + ) + ), + 'localhost', + 9700 + ), + array( + array( + 'udp' => array( + 'host' => 'localhost', + 'port' => 9800, + ) + ), + null, + null, + true + ), + array( + array(), + 'localhost', + 9800, + true + ), + ); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/ClientTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/ClientTest.php new file mode 100644 index 00000000..94ee2ead --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/ClientTest.php @@ -0,0 +1,1008 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Client; +use Elastica\Connection; +use Elastica\Document; +use Elastica\Exception\ClientException; +use Elastica\Exception\Connection\HttpException; +use Elastica\Script; +use Elastica\Index; +use Elastica\Request; +use Elastica\Test\Base as BaseTest; +use Elastica\Type; + +class ClientTest extends BaseTest +{ + + public function testConstruct() + { + $client = $this->_getClient(); + $this->assertCount(1, $client->getConnections()); + } + + public function testConnectionsArray() + { + // Creates a new index 'xodoa' and a type 'user' inside this index + $client = new Client(array('connections' => array(array('host' => 'localhost', 'port' => 9200)))); + $index = $client->getIndex('elastica_test1'); + $index->create(array(), true); + + $type = $index->getType('user'); + + // Adds 1 document to the index + $doc1 = new Document(1, + array('username' => 'hans', 'test' => array('2', '3', '5')) + ); + $type->addDocument($doc1); + + // Adds a list of documents with _bulk upload to the index + $docs = array(); + $docs[] = new Document(2, + array('username' => 'john', 'test' => array('1', '3', '6')) + ); + $docs[] = new Document(3, + array('username' => 'rolf', 'test' => array('2', '3', '7')) + ); + $type->addDocuments($docs); + + // Refresh index + $index->refresh(); + + $resultSet = $type->search('rolf'); + } + + public function testTwoServersSame() + { + // Creates a new index 'xodoa' and a type 'user' inside this index + $client = new Client(array('connections' => array( + array('host' => 'localhost', 'port' => 9200), + array('host' => 'localhost', 'port' => 9200), + ))); + $index = $client->getIndex('elastica_test1'); + $index->create(array(), true); + + $type = $index->getType('user'); + + // Adds 1 document to the index + $doc1 = new Document(1, + array('username' => 'hans', 'test' => array('2', '3', '5')) + ); + $type->addDocument($doc1); + + // Adds a list of documents with _bulk upload to the index + $docs = array(); + $docs[] = new Document(2, + array('username' => 'john', 'test' => array('1', '3', '6')) + ); + $docs[] = new Document(3, + array('username' => 'rolf', 'test' => array('2', '3', '7')) + ); + $type->addDocuments($docs); + + // Refresh index + $index->refresh(); + + $resultSet = $type->search('rolf'); + } + + public function testConnectionParamsArePreparedForConnectionsOption() + { + $client = new Client(array('connections' => array(array('url' => 'https://localhost:9200')))); + $connection = $client->getConnection(); + + $this->assertEquals('https://localhost:9200', $connection->getConfig('url')); + } + + public function testConnectionParamsArePreparedForServersOption() + { + $client = new Client(array('servers' => array(array('url' => 'https://localhost:9200')))); + $connection = $client->getConnection(); + + $this->assertEquals('https://localhost:9200', $connection->getConfig('url')); + } + + public function testConnectionParamsArePreparedForDefaultOptions() + { + $client = new Client(array('url' => 'https://localhost:9200')); + $connection = $client->getConnection(); + + $this->assertEquals('https://localhost:9200', $connection->getConfig('url')); + } + + public function testBulk() + { + $client = $this->_getClient(); + + $params = array( + array('index' => array('_index' => 'test', '_type' => 'user', '_id' => '1')), + array('user' => array('name' => 'hans')), + array('index' => array('_index' => 'test', '_type' => 'user', '_id' => '2')), + array('user' => array('name' => 'peter')), + ); + + $client->bulk($params); + } + + public function testOptimizeAll() + { + $client = $this->_getClient(); + $response = $client->optimizeAll(); + + $this->assertFalse($response->hasError()); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testAddDocumentsEmpty() + { + $client = $this->_getClient(); + $client->addDocuments(array()); + } + + /** + * Test bulk operations on Index + */ + public function testBulkIndex() + { + $index = $this->_getClient()->getIndex('cryptocurrencies'); + + $anonCoin = new Document(1, array('name' => 'anoncoin'), 'altcoin'); + $ixCoin = new Document(2, array('name' => 'ixcoin'), 'altcoin'); + + $index->addDocuments(array($anonCoin, $ixCoin)); + + $this->assertEquals('anoncoin', $index->getType('altcoin')->getDocument(1)->get('name')); + $this->assertEquals('ixcoin', $index->getType('altcoin')->getDocument(2)->get('name')); + + $index->updateDocuments(array( + new Document(1, array('name' => 'AnonCoin'), 'altcoin'), + new Document(2, array('name' => 'iXcoin'), 'altcoin') + )); + + $this->assertEquals('AnonCoin', $index->getType('altcoin')->getDocument(1)->get('name')); + $this->assertEquals('iXcoin', $index->getType('altcoin')->getDocument(2)->get('name')); + + $ixCoin->setIndex(null); // Make sure the index gets set properly if missing + $index->deleteDocuments(array($anonCoin, $ixCoin)); + + $this->setExpectedException('Elastica\Exception\NotFoundException'); + $index->getType('altcoin')->getDocument(1); + $index->getType('altcoin')->getDocument(2); + } + + /** + * Test bulk operations on Type + */ + public function testBulkType() + { + $type = $this->_getClient()->getIndex('cryptocurrencies')->getType('altcoin'); + + $liteCoin = new Document(1, array('name' => 'litecoin')); + $nameCoin = new Document(2, array('name' => 'namecoin')); + + $type->addDocuments(array($liteCoin, $nameCoin)); + + $this->assertEquals('litecoin', $type->getDocument(1)->get('name')); + $this->assertEquals('namecoin', $type->getDocument(2)->get('name')); + + $type->updateDocuments(array( + new Document(1, array('name' => 'LiteCoin')), + new Document(2, array('name' => 'NameCoin')) + )); + + $this->assertEquals('LiteCoin', $type->getDocument(1)->get('name')); + $this->assertEquals('NameCoin', $type->getDocument(2)->get('name')); + + $nameCoin->setType(null); // Make sure the type gets set properly if missing + $type->deleteDocuments(array($liteCoin, $nameCoin)); + + $this->setExpectedException('Elastica\Exception\NotFoundException'); + $type->getDocument(1); + $type->getDocument(2); + } + + public function testUpdateDocuments() + { + $indexName = 'test'; + $typeName = 'people'; + + $client = $this->_getClient(); + $type = $client->getIndex($indexName)->getType($typeName); + + $initialValue = 28; + $modifiedValue = 27; + + $doc1 = new Document( + 1, + array('name' => 'hans', 'age' => $initialValue), + $typeName, + $indexName + ); + $doc2 = new Document( + 2, + array('name' => 'anna', 'age' => $initialValue), + $typeName, + $indexName + ); + $data = array($doc1, $doc2); + $client->addDocuments($data); + + foreach ($data as $i => $doc) { + $data[$i]->age = $modifiedValue; + } + $client->updateDocuments($data); + + $docData1 = $type->getDocument(1)->getData(); + $docData2 = $type->getDocument(2)->getData(); + + $this->assertEquals($modifiedValue, $docData1['age']); + $this->assertEquals($modifiedValue, $docData2['age']); + } + + /** + * Test deleteIds method using string parameters + * + * This test ensures that the deleteIds method of + * the \Elastica\Client can properly accept and use + * an $index parameter and $type parameter that are + * strings + * + * This test is a bit more verbose than just sending the + * values to deleteIds and checking for exceptions or + * warnings. + * + * It will add a document, search for it, then delete it + * using the parameter types we are interested in, and then + * re-search to verify that they have been deleted + */ + public function testDeleteIdsIdxStringTypeString() + { + $data = array('username' => 'hans'); + $userSearch = 'username:hans'; + + $index = $this->_createIndex('test', true, 2); + + // Create the index, deleting it first if it already exists + $index->create(array(), true); + $type = $index->getType('user'); + + // Adds 1 document to the index + $doc = new Document(null, $data); + $doc->setRouting(1); + $result = $type->addDocument($doc); + + // Refresh index + $index->refresh(); + + $resultData = $result->getData(); + $ids = array($resultData['_id']); + + // Check to make sure the document is in the index + $resultSet = $type->search($userSearch); + $totalHits = $resultSet->getTotalHits(); + $this->assertEquals(1, $totalHits); + + // And verify that the variables we are doing to send to + // deleteIds are the type we are testing for + $idxString = $index->getName(); + $typeString = $type->getName(); + $this->assertEquals(true, is_string($idxString)); + $this->assertEquals(true, is_string($typeString)); + + // Try to delete doc with a routing value which hashes to + // a different shard then the id. + $resp = $index->getClient()->deleteIds($ids, $index, $type, 2); + + // Refresh the index + $index->refresh(); + + // Research the index to verify that the items are still there + $resultSet = $type->search($userSearch); + $totalHits = $resultSet->getTotalHits(); + $this->assertEquals(1, $totalHits); + + // Using the existing $index and $type variables which + // are \Elastica\Index and \Elastica\Type objects respectively + $resp = $index->getClient()->deleteIds($ids, $index, $type, 1); + + // Refresh the index to clear out deleted ID information + $index->refresh(); + + // Research the index to verify that the items have been deleted + $resultSet = $type->search($userSearch); + $totalHits = $resultSet->getTotalHits(); + $this->assertEquals(0, $totalHits); + } + + /** + * Test deleteIds method using string parameter for $index + * and object parameter for $type + * + * This test ensures that the deleteIds method of + * the \Elastica\Client can properly accept and use + * an $index parameter that is a string and a $type + * parameter that is of type \Elastica\Type + * + * This test is a bit more verbose than just sending the + * values to deleteIds and checking for exceptions or + * warnings. + * + * It will add a document, search for it, then delete it + * using the parameter types we are interested in, and then + * re-search to verify that they have been deleted + */ + public function testDeleteIdsIdxStringTypeObject() + { + $data = array('username' => 'hans'); + $userSearch = 'username:hans'; + + $index = $this->_createIndex(); + + // Create the index, deleting it first if it already exists + $index->create(array(), true); + $type = $index->getType('user'); + + // Adds 1 document to the index + $doc = new Document(null, $data); + $result = $type->addDocument($doc); + + // Refresh index + $index->refresh(); + + $resultData = $result->getData(); + $ids = array($resultData['_id']); + + // Check to make sure the document is in the index + $resultSet = $type->search($userSearch); + $totalHits = $resultSet->getTotalHits(); + $this->assertEquals(1, $totalHits); + + // And verify that the variables we are doing to send to + // deleteIds are the type we are testing for + $idxString = $index->getName(); + $this->assertEquals(true, is_string($idxString)); + $this->assertEquals(true, ($type instanceof Type)); + + // Using the existing $index and $type variables which + // are \Elastica\Index and \Elastica\Type objects respectively + $resp = $index->getClient()->deleteIds($ids, $index, $type); + + // Refresh the index to clear out deleted ID information + $index->refresh(); + + // Research the index to verify that the items have been deleted + $resultSet = $type->search($userSearch); + $totalHits = $resultSet->getTotalHits(); + $this->assertEquals(0, $totalHits); + } + + /** + * Test deleteIds method using object parameter for $index + * and string parameter for $type + * + * This test ensures that the deleteIds method of + * the \Elastica\Client can properly accept and use + * an $index parameter that is of type Elasitca_Index + * and a $type parameter that is a string + * + * This test is a bit more verbose than just sending the + * values to deleteIds and checking for exceptions or + * warnings. + * + * It will add a document, search for it, then delete it + * using the parameter types we are interested in, and then + * re-search to verify that they have been deleted + */ + public function testDeleteIdsIdxObjectTypeString() + { + $data = array('username' => 'hans'); + $userSearch = 'username:hans'; + + $index = $this->_createIndex(); + + // Create the index, deleting it first if it already exists + $index->create(array(), true); + $type = $index->getType('user'); + + // Adds 1 document to the index + $doc = new Document(null, $data); + $result = $type->addDocument($doc); + + // Refresh index + $index->refresh(); + + $resultData = $result->getData(); + $ids = array($resultData['_id']); + + // Check to make sure the document is in the index + $resultSet = $type->search($userSearch); + $totalHits = $resultSet->getTotalHits(); + $this->assertEquals(1, $totalHits); + + // And verify that the variables we are doing to send to + // deleteIds are the type we are testing for + $typeString = $type->getName(); + $this->assertEquals(true, ($index instanceof Index)); + $this->assertEquals(true, is_string($typeString)); + + // Using the existing $index and $type variables which + // are \Elastica\Index and \Elastica\Type objects respectively + $resp = $index->getClient()->deleteIds($ids, $index, $type); + + // Refresh the index to clear out deleted ID information + $index->refresh(); + + // Research the index to verify that the items have been deleted + $resultSet = $type->search($userSearch); + $totalHits = $resultSet->getTotalHits(); + $this->assertEquals(0, $totalHits); + } + + /** + * Test deleteIds method using object parameter for $index + * and object parameter for $type + * + * This test ensures that the deleteIds method of + * the \Elastica\Client can properly accept and use + * an $index parameter that is an object and a $type + * parameter that is of type \Elastica\Type + * + * This test is a bit more verbose than just sending the + * values to deleteIds and checking for exceptions or + * warnings. + * + * It will add a document, search for it, then delete it + * using the parameter types we are interested in, and then + * re-search to verify that they have been deleted + */ + public function testDeleteIdsIdxObjectTypeObject() + { + $data = array('username' => 'hans'); + $userSearch = 'username:hans'; + + $index = $this->_createIndex(); + + // Create the index, deleting it first if it already exists + $index->create(array(), true); + $type = $index->getType('user'); + + // Adds 1 document to the index + $doc = new Document(null, $data); + $result = $type->addDocument($doc); + + // Refresh index + $index->refresh(); + + $resultData = $result->getData(); + $ids = array($resultData['_id']); + + // Check to make sure the document is in the index + $resultSet = $type->search($userSearch); + $totalHits = $resultSet->getTotalHits(); + $this->assertEquals(1, $totalHits); + + // And verify that the variables we are doing to send to + // deleteIds are the type we are testing for + $this->assertEquals(true, ($index instanceof Index)); + $this->assertEquals(true, ($type instanceof Type)); + + // Using the existing $index and $type variables which + // are \Elastica\Index and \Elastica\Type objects respectively + $resp = $index->getClient()->deleteIds($ids, $index, $type); + + // Refresh the index to clear out deleted ID information + $index->refresh(); + + // Research the index to verify that the items have been deleted + $resultSet = $type->search($userSearch); + $totalHits = $resultSet->getTotalHits(); + $this->assertEquals(0, $totalHits); + } + + public function testOneInvalidConnection() + { + $client = $this->_getClient(); + + // First connection work, second should not work + $connection1 = new Connection(array('port' => '9100', 'timeout' => 2)); + $connection2 = new Connection(array('port' => '9200', 'timeout' => 2)); + + $client->setConnections(array($connection1, $connection2)); + + $client->request('_status', Request::GET); + + $connections = $client->getConnections(); + + // two connections are setup + $this->assertEquals(2, count($connections)); + + // One connection has to be disabled + $this->assertTrue($connections[0]->isEnabled() == false || $connections[1]->isEnabled() == false); + } + + public function testTwoInvalidConnection() + { + $client = $this->_getClient(); + + // First connection work, second should not work + $connection1 = new Connection(array('port' => '9101', 'timeout' => 2)); + $connection2 = new Connection(array('port' => '9102', 'timeout' => 2)); + + $client->setConnections(array($connection1, $connection2)); + + try { + $client->request('_status', Request::GET); + $this->fail('Should throw exception as no connection valid'); + } catch (HttpException $e) { + $this->assertTrue(true); + } + + $connections = $client->getConnections(); + + // two connections are setup + $this->assertEquals(2, count($connections)); + + // One connection has to be disabled + $this->assertTrue($connections[0]->isEnabled() == false || $connections[1]->isEnabled() == false); + } + + /** + * Tests if the callback works in case a connection is down + */ + public function testCallback() + { + $count = 0; + $object = $this; + + // Callback function which verifies that disabled connection objects are returned + $callback = function($connection, $exception, $client) use (&$object, &$count) { + $object->assertInstanceOf('Elastica\Connection', $connection); + $object->assertInstanceOf('Elastica\Exception\ConnectionException', $exception); + $object->assertInstanceOf('Elastica\Client', $client); + $object->assertFalse($connection->isEnabled()); + $count++; + }; + + $client = new Client(array(), $callback); + + // First connection work, second should not work + $connection1 = new Connection(array('port' => '9101', 'timeout' => 2)); + $connection2 = new Connection(array('port' => '9102', 'timeout' => 2)); + + $client->setConnections(array($connection1, $connection2)); + + $this->assertEquals(0, $count); + + try { + $client->request('_status', Request::GET); + $this->fail('Should throw exception as no connection valid'); + } catch (HttpException $e) { + $this->assertTrue(true); + } + + // Two disabled connections (from closure call) + $this->assertEquals(2, $count); + } + + public function testUrlConstructor() + { + $url = 'http://localhost:9200/'; + + // Url should overwrite invalid host + $client = new Client(array('url' => $url, 'port' => '9101', 'timeout' => 2)); + + $response = $client->request('_status'); + $this->assertInstanceOf('Elastica\Response', $response); + } + + public function testUpdateDocumentByDocument() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + $client = $index->getClient(); + + $newDocument = new Document(1, array('field1' => 'value1', 'field2' => 'value2')); + $type->addDocument($newDocument); + + $updateDocument = new Document(1, array('field2' => 'value2changed', 'field3' => 'value3added')); + $client->updateDocument(1, $updateDocument, $index->getName(), $type->getName()); + + $document = $type->getDocument(1); + + $this->assertInstanceOf('Elastica\Document', $document); + $data = $document->getData(); + $this->assertArrayHasKey('field1', $data); + $this->assertEquals('value1', $data['field1']); + $this->assertArrayHasKey('field2', $data); + $this->assertEquals('value2changed', $data['field2']); + $this->assertArrayHasKey('field3', $data); + $this->assertEquals('value3added', $data['field3']); + } + + public function testUpdateDocumentByScript() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + $client = $index->getClient(); + + $newDocument = new Document(1, array('field1' => 'value1', 'field2' => 10, 'field3' => 'should be removed', 'field4' => 'should be changed')); + $type->addDocument($newDocument); + + $script = new Script('ctx._source.field2 += 5; ctx._source.remove("field3"); ctx._source.field4 = "changed"'); + $client->updateDocument(1, $script, $index->getName(), $type->getName()); + + $document = $type->getDocument(1); + + $this->assertInstanceOf('Elastica\Document', $document); + $data = $document->getData(); + $this->assertArrayHasKey('field1', $data); + $this->assertEquals('value1', $data['field1']); + $this->assertArrayHasKey('field2', $data); + $this->assertEquals(15, $data['field2']); + $this->assertArrayHasKey('field2', $data); + $this->assertEquals('changed', $data['field4']); + $this->assertArrayNotHasKey('field3', $data); + } + + public function testUpdateDocumentByScriptWithUpsert() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + $client = $index->getClient(); + + $script = new Script('ctx._source.field2 += count; ctx._source.remove("field3"); ctx._source.field4 = "changed"'); + $script->setParam('count', 5); + $script->setUpsert(array('field1' => 'value1', 'field2' => 10, 'field3' => 'should be removed', 'field4' => 'value4')); + + // should use document fields because document does not exist, script is avoided + $client->updateDocument(1, $script, $index->getName(), $type->getName(), array('fields' => '_source')); + + $document = $type->getDocument(1); + + $this->assertInstanceOf('Elastica\Document', $document); + $data = $document->getData(); + $this->assertArrayHasKey('field1', $data); + $this->assertEquals('value1', $data['field1']); + $this->assertArrayHasKey('field2', $data); + $this->assertEquals(10, $data['field2']); + $this->assertArrayHasKey('field3', $data); + $this->assertEquals('should be removed', $data['field3']); + $this->assertArrayHasKey('field4', $data); + $this->assertEquals('value4', $data['field4']); + + // should use script because document exists, document values are ignored + $client->updateDocument(1, $script, $index->getName(), $type->getName(), array('fields' => '_source')); + + $document = $type->getDocument(1); + + $this->assertInstanceOf('Elastica\Document', $document); + $data = $document->getData(); + $this->assertArrayHasKey('field1', $data); + $this->assertEquals('value1', $data['field1']); + $this->assertArrayHasKey('field2', $data); + $this->assertEquals(15, $data['field2']); + $this->assertArrayHasKey('field4', $data); + $this->assertEquals('changed', $data['field4']); + $this->assertArrayNotHasKey('field3', $data); + } + + public function testUpdateDocumentByRawData() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + $client = $index->getClient(); + + $newDocument = new Document(1, array('field1' => 'value1')); + $type->addDocument($newDocument); + + $rawData = array( + 'doc' => array( + 'field2' => 'value2', + ) + ); + + $response = $client->updateDocument(1, $rawData, $index->getName(), $type->getName(), array('retry_on_conflict' => 1)); + $this->assertTrue($response->isOk()); + + $document = $type->getDocument(1); + + $this->assertInstanceOf('Elastica\Document', $document); + $data = $document->getData(); + $this->assertArrayHasKey('field1', $data); + $this->assertEquals('value1', $data['field1']); + $this->assertArrayHasKey('field2', $data); + $this->assertEquals('value2', $data['field2']); + } + + public function testUpdateDocumentByDocumentWithUpsert() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + $client = $index->getClient(); + + $newDocument = new Document(1, array('field1' => 'value1updated', 'field2' => 'value2updated')); + $upsert = new Document(1, array('field1' => 'value1', 'field2' => 'value2')); + $newDocument->setUpsert($upsert); + $client->updateDocument(1, $newDocument, $index->getName(), $type->getName(), array('fields' => '_source')); + + $document = $type->getDocument(1); + $this->assertInstanceOf('Elastica\Document', $document); + $data = $document->getData(); + $this->assertArrayHasKey('field1', $data); + $this->assertEquals('value1', $data['field1']); + $this->assertArrayHasKey('field2', $data); + $this->assertEquals('value2', $data['field2']); + + // should use update document because document exists, upsert document values are ignored + $client->updateDocument(1, $newDocument, $index->getName(), $type->getName(), array('fields' => '_source')); + + $document = $type->getDocument(1); + $this->assertInstanceOf('Elastica\Document', $document); + $data = $document->getData(); + $this->assertArrayHasKey('field1', $data); + $this->assertEquals('value1updated', $data['field1']); + $this->assertArrayHasKey('field2', $data); + $this->assertEquals('value2updated', $data['field2']); + } + + public function testDocAsUpsert() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + $client = $index->getClient(); + + //Confirm document one does not exist + try { + $document = $type->getDocument(1); + $this->fail('Exception was not thrown. Maybe the document exists?'); + } catch (\Exception $e) { + //Ignore the exception because we expect the document to not exist. + } + + $newDocument = new Document(1, array('field1' => 'value1', 'field2' => 'value2')); + $newDocument->setDocAsUpsert(true); + $client->updateDocument(1, $newDocument, $index->getName(), $type->getName(), array('fields' => '_source')); + + $document = $type->getDocument(1); + $this->assertInstanceOf('Elastica\Document', $document); + $data = $document->getData(); + $this->assertArrayHasKey('field1', $data); + $this->assertEquals('value1', $data['field1']); + $this->assertArrayHasKey('field2', $data); + $this->assertEquals('value2', $data['field2']); + } + + public function testUpdateWithInvalidType() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + $client = $index->getClient(); + + //Try to update using a stdClass object + $badDocument = new \stdClass(); + + try { + $client->updateDocument(1, $badDocument, $index->getName(), $type->getName()); + $this->fail('Tried to update using an object that is not a Document or a Script but no exception was thrown'); + } catch (\Exception $e) { + //Good. An exception was thrown. + } + } + + public function testDeleteDocuments() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + $client = $index->getClient(); + + $docs = array( + new Document(1, array('field' => 'value1'), $type, $index), + new Document(2, array('field' => 'value2'), $type, $index), + new Document(3, array('field' => 'value3'), $type, $index), + ); + + $response = $client->addDocuments($docs); + + $this->assertInstanceOf('Elastica\Bulk\ResponseSet', $response); + $this->assertEquals(3, count($response)); + $this->assertTrue($response->isOk()); + $this->assertFalse($response->hasError()); + $this->assertEquals('', $response->getError()); + + $index->refresh(); + + $this->assertEquals(3, $type->count()); + + $deleteDocs = array( + $docs[0], + $docs[2], + ); + + $response = $client->deleteDocuments($deleteDocs); + + $this->assertInstanceOf('Elastica\Bulk\ResponseSet', $response); + $this->assertEquals(2, count($response)); + $this->assertTrue($response->isOk()); + $this->assertFalse($response->hasError()); + $this->assertEquals('', $response->getError()); + + $index->refresh(); + + $this->assertEquals(1, $type->count()); + } + + public function testLastRequestResponse() + { + $client = new Client(); + $response = $client->request('_status'); + + $this->assertInstanceOf('Elastica\Response', $response); + + $lastRequest = $client->getLastRequest(); + + $this->assertInstanceOf('Elastica\Request', $lastRequest); + $this->assertEquals('_status', $lastRequest->getPath()); + + $lastResponse = $client->getLastResponse(); + $this->assertInstanceOf('Elastica\Response', $lastResponse); + $this->assertSame($response, $lastResponse); + } + + public function testUpdateDocumentPopulateFields() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + $client = $index->getClient(); + + $newDocument = new Document(1, array('field1' => 'value1', 'field2' => 10, 'field3' => 'should be removed', 'field4' => 'value4')); + $newDocument->setAutoPopulate(); + $type->addDocument($newDocument); + + $script = new Script('ctx._source.field2 += count; ctx._source.remove("field3"); ctx._source.field4 = "changed"'); + $script->setParam('count', 5); + $script->setUpsert($newDocument); + + $client->updateDocument( + 1, + $script, + $index->getName(), + $type->getName(), + array('fields' => '_source') + ); + + $data = $type->getDocument(1)->getData(); + $this->assertArrayHasKey('field1', $data); + $this->assertEquals('value1', $data['field1']); + $this->assertArrayHasKey('field2', $data); + $this->assertEquals(15, $data['field2']); + $this->assertArrayHasKey('field4', $data); + $this->assertEquals('changed', $data['field4']); + $this->assertArrayNotHasKey('field3', $data); + + $script = new Script('ctx._source.field2 += count; ctx._source.remove("field4"); ctx._source.field1 = field1;'); + $script->setParam('count', 5); + $script->setParam('field1', 'updated'); + $script->setUpsert($newDocument); + + $client->updateDocument( + 1, + $script, + $index->getName(), + $type->getName(), + array('fields' => 'field2,field4') + ); + + $document = $type->getDocument(1); + + $data = $document->getData(); + + $this->assertArrayHasKey('field1', $data); + $this->assertEquals('updated', $data['field1']); + $this->assertArrayHasKey('field2', $data); + $this->assertEquals(20, $data['field2']); + $this->assertArrayNotHasKey('field3', $data); + $this->assertArrayNotHasKey('field4', $data); + } + + public function testAddDocumentsWithoutIds() + { + $docs = array(); + for ($i = 0; $i < 10; $i++) { + $docs[] = new Document(null, array('pos' => $i)); + } + + foreach ($docs as $doc) { + $this->assertFalse($doc->hasId()); + } + + $index = $this->_createIndex(); + + $client = $index->getClient(); + $client->setConfigValue('document', array('autoPopulate' => true)); + + $type = $index->getType('pos'); + $type->addDocuments($docs); + + foreach ($docs as $doc) { + $this->assertTrue($doc->hasId()); + $this->assertTrue($doc->hasVersion()); + $this->assertEquals(1, $doc->getVersion()); + } + } + + public function testConfigValue() + { + $config = array( + 'level1' => array( + 'level2' => array( + 'level3' => 'value3', + ), + 'level21' => 'value21' + ), + 'level11' => 'value11' + ); + $client = new Client($config); + + $this->assertNull($client->getConfigValue('level12')); + $this->assertFalse($client->getConfigValue('level12', false)); + $this->assertEquals(10, $client->getConfigValue('level12', 10)); + + $this->assertEquals('value11', $client->getConfigValue('level11')); + $this->assertNotNull($client->getConfigValue('level11')); + $this->assertNotEquals(false, $client->getConfigValue('level11', false)); + $this->assertNotEquals(10, $client->getConfigValue('level11', 10)); + + $this->assertEquals('value3', $client->getConfigValue(array('level1', 'level2', 'level3'))); + $this->assertInternalType('array', $client->getConfigValue(array('level1', 'level2'))); + } + + + public function testArrayQuery() + { + $client = new Client(); + + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('test'); + $type->addDocument(new Document(1, array('username' => 'ruflin'))); + $index->refresh(); + + $query = array( + 'query' => array( + 'query_string' => array( + 'query' => 'ruflin', + ) + ) + ); + + $path = $index->getName() . '/' . $type->getName() . '/_search'; + + $response = $client->request($path, Request::GET, $query); + $responseArray = $response->getData(); + + $this->assertEquals(1, $responseArray['hits']['total']); + } + + public function testJSONQuery() + { + $client = new Client(); + + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('test'); + $type->addDocument(new Document(1, array('username' => 'ruflin'))); + $index->refresh(); + + $query = '{"query":{"query_string":{"query":"ruflin"}}}'; + + $path = $index->getName() . '/' . $type->getName() . '/_search'; + + $response = $client->request($path, Request::GET, $query); + $responseArray = $response->getData(); + + $this->assertEquals(1, $responseArray['hits']['total']); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Cluster/Health/IndexTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Cluster/Health/IndexTest.php new file mode 100644 index 00000000..085ac13a --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Cluster/Health/IndexTest.php @@ -0,0 +1,113 @@ +<?php + +namespace Elastica\Test\Cluster\Health; + +use Elastica\Cluster\Health\Index as HealthIndex; +use Elastica\Test\Base as BaseTest; + +class IndexTest extends BaseTest +{ + /** + * @var \Elastica\Cluster\Health\Index + */ + protected $_index; + + public function setUp() + { + $data = array( + "status" => "yellow", + "number_of_shards" => 1, + "number_of_replicas" => 2, + "active_primary_shards" => 3, + "active_shards" => 4, + "relocating_shards" => 5, + "initializing_shards" => 6, + "unassigned_shards" => 7, + "shards" => array( + "0" => array( + "status" => "yellow", + "primary_active" => false, + "active_shards" => 0, + "relocating_shards" => 1, + "initializing_shards" => 0, + "unassigned_shards" => 1 + ), + "1" => array( + "status" => "yellow", + "primary_active" => true, + "active_shards" => 1, + "relocating_shards" => 0, + "initializing_shards" => 0, + "unassigned_shards" => 1 + ), + "2" => array( + "status" => "green", + "primary_active" => true, + "active_shards" => 1, + "relocating_shards" => 0, + "initializing_shards" => 0, + "unassigned_shards" => 0, + ), + ) + ); + + $this->_index = new HealthIndex('test', $data); + } + + public function testGetName() + { + $this->assertEquals('test', $this->_index->getName()); + } + + public function testGetStatus() + { + $this->assertEquals('yellow', $this->_index->getStatus()); + } + + public function testGetNumberOfShards() + { + $this->assertEquals(1, $this->_index->getNumberOfShards()); + } + + public function testGetNumberOfReplicas() + { + $this->assertEquals(2, $this->_index->getNumberOfReplicas()); + } + + public function testGetActivePrimaryShards() + { + $this->assertEquals(3, $this->_index->getActivePrimaryShards()); + } + + public function testGetActiveShards() + { + $this->assertEquals(4, $this->_index->getActiveShards()); + } + + public function testGetRelocatingShards() + { + $this->assertEquals(5, $this->_index->getRelocatingShards()); + } + + public function testGetInitializingShards() + { + $this->assertEquals(6, $this->_index->getInitializingShards()); + } + + public function testGetUnassignedShards() + { + $this->assertEquals(7, $this->_index->getUnassignedShards()); + } + + public function testGetShards() + { + $shards = $this->_index->getShards(); + + $this->assertInternalType('array', $shards); + $this->assertEquals(3, count($shards)); + + foreach ($shards as $shard) { + $this->assertInstanceOf('Elastica\Cluster\Health\Shard', $shard); + } + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Cluster/Health/ShardTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Cluster/Health/ShardTest.php new file mode 100644 index 00000000..b63195a0 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Cluster/Health/ShardTest.php @@ -0,0 +1,63 @@ +<?php + +namespace Elastica\Test\Cluster\Health; + +use Elastica\Cluster\Health\Shard as HealthShard; +use Elastica\Test\Base as BaseTest; + +class ShardTest extends BaseTest +{ + /** + * @var \Elastica\Cluster\Health\Shard + */ + protected $_shard; + + public function setUp() + { + $shardData = array( + 'status' => 'red', + 'primary_active' => true, + 'active_shards' => 1, + 'relocating_shards' => 0, + 'initializing_shards' => 0, + 'unassigned_shards' => 1, + ); + + $this->_shard = new HealthShard(2, $shardData); + } + + public function testGetShardNumber() + { + $this->assertEquals(2, $this->_shard->getShardNumber()); + } + + public function testGetStatus() + { + $this->assertEquals('red', $this->_shard->getStatus()); + } + + public function testisPrimaryActive() + { + $this->assertTrue($this->_shard->isPrimaryActive()); + } + + public function testIsActive() + { + $this->assertTrue($this->_shard->isActive()); + } + + public function testIsRelocating() + { + $this->assertFalse($this->_shard->isRelocating()); + } + + public function testIsInitialized() + { + $this->assertFalse($this->_shard->isInitialized()); + } + + public function testIsUnassigned() + { + $this->assertTrue($this->_shard->isUnassigned()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Cluster/HealthTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Cluster/HealthTest.php new file mode 100644 index 00000000..054af3f7 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Cluster/HealthTest.php @@ -0,0 +1,113 @@ +<?php + +namespace Elastica\Test\Cluster; + +use Elastica\Test\Base as BaseTest; + +class HealthTest extends BaseTest +{ + /** + * @var \Elastica\Cluster\Health + */ + protected $_health; + + public function setUp() + { + $data = array( + 'cluster_name' => 'test_cluster', + 'status' => 'green', + 'timed_out' => false, + 'number_of_nodes' => 10, + 'number_of_data_nodes' => 8, + 'active_primary_shards' => 3, + 'active_shards' => 4, + 'relocating_shards' => 2, + 'initializing_shards' => 7, + 'unassigned_shards' => 5, + 'indices' => array( + 'index_one' => array( + ), + 'index_two' => array( + ), + ), + ); + + $health = $this + ->getMockBuilder('Elastica\Cluster\Health') + ->setConstructorArgs(array($this->_getClient())) + ->setMethods(array('_retrieveHealthData')) + ->getMock(); + + $health + ->expects($this->any()) + ->method('_retrieveHealthData') + ->will($this->returnValue($data)); + + // need to explicitly refresh because the mocking won't refresh the data in the constructor + $health->refresh(); + + $this->_health = $health; + } + + public function testGetClusterName() + { + $this->assertEquals('test_cluster', $this->_health->getClusterName()); + } + + public function testGetStatus() + { + $this->assertEquals('green', $this->_health->getStatus()); + } + + public function testGetTimedOut() + { + $this->assertFalse($this->_health->getTimedOut()); + } + + public function testGetNumberOfNodes() + { + $this->assertEquals(10, $this->_health->getNumberOfNodes()); + } + + public function testGetNumberOfDataNodes() + { + $this->assertEquals(8, $this->_health->getNumberOfDataNodes()); + } + + public function testGetActivePrimaryShards() + { + $this->assertEquals(3, $this->_health->getActivePrimaryShards()); + } + + public function testGetActiveShards() + { + $this->assertEquals(4, $this->_health->getActiveShards()); + } + + public function testGetRelocatingShards() + { + $this->assertEquals(2, $this->_health->getRelocatingShards()); + } + + public function testGetInitializingShards() + { + $this->assertEquals(7, $this->_health->getInitializingShards()); + } + + public function testGetUnassignedShards() + { + $this->assertEquals(5, $this->_health->getUnassignedShards()); + } + + public function testGetIndices() + { + $indices = $this->_health->getIndices(); + + $this->assertInternalType('array', $indices); + $this->assertEquals(2, count($indices)); + + foreach ($indices as $index) { + $this->assertInstanceOf('Elastica\Cluster\Health\Index', $index); + } + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Cluster/SettingsTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Cluster/SettingsTest.php new file mode 100644 index 00000000..a093feef --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Cluster/SettingsTest.php @@ -0,0 +1,110 @@ +<?php + +namespace Elastica\Test\Cluster; + +use Elastica\Document; +use Elastica\Exception\ResponseException; +use Elastica\Test\Base as BaseTest; +use Elastica\Cluster\Settings; + +class SettingsTest extends BaseTest +{ + public function testSetTransient() + { + $index = $this->_createIndex(); + + if (count($index->getClient()->getCluster()->getNodes()) < 2) { + $this->markTestSkipped('At least two master nodes have to be running for this test'); + } + + $settings = new Settings($index->getClient()); + + $settings->setTransient('discovery.zen.minimum_master_nodes', 2); + $data = $settings->get(); + $this->assertEquals(2, $data['transient']['discovery.zen.minimum_master_nodes']); + + $settings->setTransient('discovery.zen.minimum_master_nodes', 1); + $data = $settings->get(); + $this->assertEquals(1, $data['transient']['discovery.zen.minimum_master_nodes']); + } + + public function testSetPersistent() + { + $index = $this->_createIndex(); + + if (count($index->getClient()->getCluster()->getNodes()) < 2) { + $this->markTestSkipped('At least two master nodes have to be running for this test'); + } + + $settings = new Settings($index->getClient()); + + $settings->setPersistent('discovery.zen.minimum_master_nodes', 2); + $data = $settings->get(); + $this->assertEquals(2, $data['persistent']['discovery.zen.minimum_master_nodes']); + + $settings->setPersistent('discovery.zen.minimum_master_nodes', 1); + $data = $settings->get(); + $this->assertEquals(1, $data['persistent']['discovery.zen.minimum_master_nodes']); + } + + public function testSetReadOnly() + { + // Create two indices to check that the complete cluster is read only + $settings = new Settings($this->_getClient()); + $settings->setReadOnly(false); + $index1 = $this->_createIndex('test1'); + $index2 = $this->_createIndex('test2'); + + + $doc1 = new Document(null, array('hello' => 'world')); + $doc2 = new Document(null, array('hello' => 'world')); + $doc3 = new Document(null, array('hello' => 'world')); + $doc4 = new Document(null, array('hello' => 'world')); + $doc5 = new Document(null, array('hello' => 'world')); + $doc6 = new Document(null, array('hello' => 'world')); + + // Check that adding documents work + $index1->getType('test')->addDocument($doc1); + $index2->getType('test')->addDocument($doc2); + + $response = $settings->setReadOnly(true); + $this->assertFalse($response->hasError()); + $setting = $settings->getTransient('cluster.blocks.read_only'); + $this->assertEquals('true', $setting); + + // Make sure both index are read only + try { + $index1->getType('test')->addDocument($doc3); + $this->fail('should throw read only exception'); + } catch (ResponseException $e) { + $message = $e->getMessage(); + $this->assertContains('ClusterBlockException', $message); + $this->assertContains('cluster read-only', $message); + } + + try { + $index2->getType('test')->addDocument($doc4); + $this->fail('should throw read only exception'); + } catch (ResponseException $e) { + $message = $e->getMessage(); + $this->assertContains('ClusterBlockException', $message); + $this->assertContains('cluster read-only', $message); + } + + $response = $settings->setReadOnly(false); + $this->assertFalse($response->hasError()); + $setting = $settings->getTransient('cluster.blocks.read_only'); + $this->assertEquals('false', $setting); + + // Check that adding documents works again + $index1->getType('test')->addDocument($doc5); + $index2->getType('test')->addDocument($doc6); + + $index1->refresh(); + $index2->refresh(); + + // 2 docs should be in each index + $this->assertEquals(2, $index1->count()); + $this->assertEquals(2, $index2->count()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/ClusterTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/ClusterTest.php new file mode 100644 index 00000000..ae5fb980 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/ClusterTest.php @@ -0,0 +1,89 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Client; +use Elastica\Cluster; +use Elastica\Test\Base as BaseTest; + +class ClusterTest extends BaseTest +{ + + public function testGetNodeNames() + { + $client = $this->_getClient(); + + $cluster = new Cluster($client); + + $names = $cluster->getNodeNames(); + + $this->assertInternalType('array', $names); + $this->assertGreaterThan(0, count($names)); + } + + public function testGetNodes() + { + $client = $this->_getClient(); + $cluster = $client->getCluster(); + + $nodes = $cluster->getNodes(); + + foreach ($nodes as $node) { + $this->assertInstanceOf('Elastica\Node', $node); + } + + $this->assertGreaterThan(0, count($nodes)); + } + + public function testGetState() + { + $client = $this->_getClient(); + $cluster = $client->getCluster(); + $state = $cluster->getState(); + $this->assertInternalType('array', $state); + } + + /** + * @expectedException \Elastica\Exception\ConnectionException + */ + public function testShutdown() + { + $this->markTestSkipped('This test shuts down the cluster which means the following tests would not work'); + $client = $this->_getClient(); + $cluster = $client->getCluster(); + + $cluster->shutdown('2s'); + + sleep(5); + + $client->getStatus(); + } + + public function testGetIndexNames() + { + $client = $this->_getClient(); + $cluster = $client->getCluster(); + + $indexName = 'elastica_test999'; + $index = $this->_createIndex($indexName); + $index->delete(); + $cluster->refresh(); + + // Checks that index does not exist + $indexNames = $cluster->getIndexNames(); + $this->assertNotContains($index->getName(), $indexNames); + + $index = $this->_createIndex($indexName); + $cluster->refresh(); + + // Now index should exist + $indexNames = $cluster->getIndexNames(); + $this->assertContains($index->getname(), $indexNames); + } + + public function testGetHealth() + { + $client = $this->_getClient(); + $this->assertInstanceOf('Elastica\Cluster\Health', $client->getCluster()->getHealth()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/ConnectionTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/ConnectionTest.php new file mode 100644 index 00000000..80cab9f0 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/ConnectionTest.php @@ -0,0 +1,103 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Connection; +use Elastica\Request; +use Elastica\Test\Base as BaseTest; + +class ConnectionTest extends BaseTest +{ + + public function testEmptyConstructor() + { + $connection = new Connection(); + $this->assertEquals(Connection::DEFAULT_HOST, $connection->getHost()); + $this->assertEquals(Connection::DEFAULT_PORT, $connection->getPort()); + $this->assertEquals(Connection::DEFAULT_TRANSPORT, $connection->getTransport()); + $this->assertInstanceOf('Elastica\Transport\AbstractTransport', $connection->getTransportObject()); + $this->assertEquals(Connection::TIMEOUT, $connection->getTimeout()); + $this->assertEquals(array(), $connection->getConfig()); + $this->assertTrue($connection->isEnabled()); + } + + public function testEnabledDisable() + { + $connection = new Connection(); + $this->assertTrue($connection->isEnabled()); + $connection->setEnabled(false); + $this->assertFalse($connection->isEnabled()); + $connection->setEnabled(true); + $this->assertTrue($connection->isEnabled()); + } + + /** + * @expectedException \Elastica\Exception\ConnectionException + */ + public function testInvalidConnection() + { + $connection = new Connection(array('port' => 9999)); + + $request = new Request('_status', Request::GET); + $request->setConnection($connection); + + // Throws exception because no valid connection + $request->send(); + } + + public function testCreate() + { + $connection = Connection::create(); + $this->assertInstanceOf('Elastica\Connection', $connection); + + $connection = Connection::create(array()); + $this->assertInstanceOf('Elastica\Connection', $connection); + + $port = 9999; + $connection = Connection::create(array('port' => $port)); + $this->assertInstanceOf('Elastica\Connection', $connection); + $this->assertEquals($port, $connection->getPort()); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + * @expectedException \Elastica\Exception\InvalidException + */ + public function testCreateInvalid() + { + Connection::create('test'); + } + + public function testGetConfig() + { + $url = 'test'; + $connection = new Connection(array('config' => array('url' => $url))); + $this->assertTrue($connection->hasConfig('url')); + $this->assertEquals($url, $connection->getConfig('url')); + } + + public function testGetConfigWithArrayUsedForTransport() + { + $connection = new Connection(array('transport' => array('type' => 'Http'))); + $this->assertInstanceOf('Elastica\Transport\Http', $connection->getTransportObject()); + } + + /** + * @expectedException Elastica\Exception\InvalidException + * @expectedExceptionMessage Invalid transport + */ + public function testGetInvalidConfigWithArrayUsedForTransport() + { + $connection = new Connection(array('transport' => array('type' => 'invalidtransport'))); + $connection->getTransportObject(); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testGetConfigInvalidValue() + { + $connection = new Connection(); + $connection->getConfig('url'); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/DocumentTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/DocumentTest.php new file mode 100644 index 00000000..27fc5184 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/DocumentTest.php @@ -0,0 +1,309 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Document; +use Elastica\Exception\InvalidException; +use Elastica\Script; +use Elastica\Index; +use Elastica\Type; +use Elastica\Test\Base as BaseTest; + +class DocumentTest extends BaseTest +{ + public function testAddFile() + { + $fileName = '/dev/null'; + if(!file_exists($fileName)){ + $this->markTestSkipped("File {$fileName} does not exist."); + } + $doc = new Document(); + $returnValue = $doc->addFile('key', $fileName); + $this->assertInstanceOf('Elastica\Document', $returnValue); + } + + public function testAddGeoPoint() + { + $doc = new Document(); + $returnValue = $doc->addGeoPoint('point', 38.89859, -77.035971); + $this->assertInstanceOf('Elastica\Document', $returnValue); + } + + public function testSetData() + { + $doc = new Document(); + $returnValue = $doc->setData(array('data')); + $this->assertInstanceOf('Elastica\Document', $returnValue); + } + + public function testToArray() + { + $id = 17; + $data = array('hello' => 'world'); + $type = 'testtype'; + $index = 'textindex'; + + $doc = new Document($id, $data, $type, $index); + + $result = array('_index' => $index, '_type' => $type, '_id' => $id, '_source' => $data); + $this->assertEquals($result, $doc->toArray()); + } + + public function testSetType() + { + $document = new Document(); + $document->setType('type'); + + $this->assertEquals('type', $document->getType()); + + $index = new Index($this->_getClient(), 'index'); + $type = $index->getType('type'); + + $document->setIndex('index2'); + $this->assertEquals('index2', $document->getIndex()); + + $document->setType($type); + + $this->assertEquals('index', $document->getIndex()); + $this->assertEquals('type', $document->getType()); + } + + public function testSetIndex() + { + $document = new Document(); + $document->setIndex('index2'); + $document->setType('type2'); + + $this->assertEquals('index2', $document->getIndex()); + $this->assertEquals('type2', $document->getType()); + + $index = new Index($this->_getClient(), 'index'); + + $document->setIndex($index); + + $this->assertEquals('index', $document->getIndex()); + $this->assertEquals('type2', $document->getType()); + } + + public function testHasId() + { + $document = new Document(); + $this->assertFalse($document->hasId()); + $document->setId(''); + $this->assertFalse($document->hasId()); + $document->setId(0); + $this->assertTrue($document->hasId()); + $document->setId('hello'); + $this->assertTrue($document->hasId()); + } + + public function testGetOptions() + { + $document = new Document(); + $document->setIndex('index'); + $document->setOpType('create'); + $document->setParent('2'); + $document->setId(1); + + $options = $document->getOptions(array('index', 'type', 'id', 'parent')); + + $this->assertInternalType('array', $options); + $this->assertEquals(3, count($options)); + $this->assertArrayHasKey('index', $options); + $this->assertArrayHasKey('id', $options); + $this->assertArrayHasKey('parent', $options); + $this->assertEquals('index', $options['index']); + $this->assertEquals(1, $options['id']); + $this->assertEquals('2', $options['parent']); + $this->assertArrayNotHasKey('type', $options); + $this->assertArrayNotHasKey('op_type', $options); + $this->assertArrayNotHasKey('_index', $options); + $this->assertArrayNotHasKey('_id', $options); + $this->assertArrayNotHasKey('_parent', $options); + + $options = $document->getOptions(array('parent', 'op_type', 'percolate'), true); + + $this->assertInternalType('array', $options); + $this->assertEquals(2, count($options)); + $this->assertArrayHasKey('_parent', $options); + $this->assertArrayHasKey('_op_type', $options); + $this->assertEquals('2', $options['_parent']); + $this->assertEquals('create', $options['_op_type']); + $this->assertArrayNotHasKey('percolate', $options); + $this->assertArrayNotHasKey('op_type', $options); + $this->assertArrayNotHasKey('parent', $options); + } + + public function testGetSetHasRemove() + { + $document = new Document(1, array('field1' => 'value1', 'field2' => 'value2', 'field3' => 'value3', 'field4' => null)); + + $this->assertEquals('value1', $document->get('field1')); + $this->assertEquals('value2', $document->get('field2')); + $this->assertEquals('value3', $document->get('field3')); + $this->assertNull($document->get('field4')); + try { + $document->get('field5'); + $this->fail('Undefined field get should throw exception'); + } catch (InvalidException $e) { + $this->assertTrue(true); + } + + $this->assertTrue($document->has('field1')); + $this->assertTrue($document->has('field2')); + $this->assertTrue($document->has('field3')); + $this->assertTrue($document->has('field4')); + $this->assertFalse($document->has('field5'), 'Field5 should not be isset, because it is not set'); + + $data = $document->getData(); + + $this->assertArrayHasKey('field1', $data); + $this->assertEquals('value1', $data['field1']); + $this->assertArrayHasKey('field2', $data); + $this->assertEquals('value2', $data['field2']); + $this->assertArrayHasKey('field3', $data); + $this->assertEquals('value3', $data['field3']); + $this->assertArrayHasKey('field4', $data); + $this->assertNull($data['field4']); + + $returnValue = $document->set('field1', 'changed1'); + $this->assertInstanceOf('Elastica\Document', $returnValue); + $returnValue = $document->remove('field3'); + $this->assertInstanceOf('Elastica\Document', $returnValue); + try { + $document->remove('field5'); + $this->fail('Undefined field unset should throw exception'); + } catch (InvalidException $e) { + $this->assertTrue(true); + } + + $this->assertEquals('changed1', $document->get('field1')); + $this->assertFalse($document->has('field3')); + + $newData = $document->getData(); + + $this->assertNotEquals($data, $newData); + } + + public function testDataPropertiesOverloading() + { + $document = new Document(1, array('field1' => 'value1', 'field2' => 'value2', 'field3' => 'value3', 'field4' => null)); + + $this->assertEquals('value1', $document->field1); + $this->assertEquals('value2', $document->field2); + $this->assertEquals('value3', $document->field3); + $this->assertNull($document->field4); + try { + $document->field5; + $this->fail('Undefined field get should throw exception'); + } catch (InvalidException $e) { + $this->assertTrue(true); + } + + $this->assertTrue(isset($document->field1)); + $this->assertTrue(isset($document->field2)); + $this->assertTrue(isset($document->field3)); + $this->assertFalse(isset($document->field4), 'Field4 should not be isset, because it is null'); + $this->assertFalse(isset($document->field5), 'Field5 should not be isset, because it is not set'); + + $data = $document->getData(); + + $this->assertArrayHasKey('field1', $data); + $this->assertEquals('value1', $data['field1']); + $this->assertArrayHasKey('field2', $data); + $this->assertEquals('value2', $data['field2']); + $this->assertArrayHasKey('field3', $data); + $this->assertEquals('value3', $data['field3']); + $this->assertArrayHasKey('field4', $data); + $this->assertNull($data['field4']); + + $document->field1 = 'changed1'; + unset($document->field3); + try { + unset($document->field5); + $this->fail('Undefined field unset should throw exception'); + } catch (InvalidException $e) { + $this->assertTrue(true); + } + + $this->assertEquals('changed1', $document->field1); + $this->assertFalse(isset($document->field3)); + + $newData = $document->getData(); + + $this->assertNotEquals($data, $newData); + } + + public function testSetTtl() + { + $document = new Document(); + + $this->assertFalse($document->hasTtl()); + $options = $document->getOptions(); + $this->assertArrayNotHasKey('ttl', $options); + + $document->setTtl('1d'); + + $newOptions = $document->getOptions(); + + $this->assertArrayHasKey('ttl', $newOptions); + $this->assertEquals('1d', $newOptions['ttl']); + $this->assertNotEquals($options, $newOptions); + + $this->assertTrue($document->hasTtl()); + $this->assertEquals('1d', $document->getTtl()); + } + + public function testSerializedData() + { + $data = '{"user":"rolf"}'; + $document = new Document(1, $data); + + $this->assertFalse($document->has('user')); + + try { + $document->get('user'); + $this->fail('User field should not be available'); + } catch (InvalidException $e) { + $this->assertTrue(true); + } + + try { + $document->remove('user'); + $this->fail('User field should not be available for removal'); + } catch (InvalidException $e) { + $this->assertTrue(true); + } + + try { + $document->set('name', 'shawn'); + $this->fail('Document should not allow to set new data'); + } catch (InvalidException $e) { + $this->assertTrue(true); + } + } + + public function testUpsert() + { + $document = new Document(); + + $upsert = new Document(); + $upsert->setData(array('someproperty' => 'somevalue')); + + $this->assertFalse($document->hasUpsert()); + + $document->setUpsert($upsert); + + $this->assertTrue($document->hasUpsert()); + $this->assertSame($upsert, $document->getUpsert()); + } + + public function testDocAsUpsert() + { + $document = new Document(); + + $this->assertFalse($document->getDocAsUpsert()); + $this->assertSame($document, $document->setDocAsUpsert(true)); + $this->assertTrue($document->getDocAsUpsert()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/ExampleTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/ExampleTest.php new file mode 100644 index 00000000..0331e389 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/ExampleTest.php @@ -0,0 +1,58 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Client; +use Elastica\Document; +use Elastica\Test\Base as BaseTest; + +/** + * Tests the example code + */ +class ExampleTest extends BaseTest +{ + public function testBasicGettingStarted() { + + $client = new \Elastica\Client(); + $index = $client->getIndex('ruflin'); + $type = $index->getType('users'); + + $id = 2; + $data = array('firstname' => 'Nicolas', 'lastname' => 'Ruflin'); + $doc = new \Elastica\Document($id, $data); + + $type->addDocument($doc); + + } + + public function testExample() + { + // Creates a new index 'xodoa' and a type 'user' inside this index + $client = $this->_getClient(); + $index = $client->getIndex('elastica_test'); + $index->create(array(), true); + + $type = $index->getType('user'); + + // Adds 1 document to the index + $doc1 = new Document(1, + array('username' => 'hans', 'test' => array('2', '3', '5')) + ); + $type->addDocument($doc1); + + // Adds a list of documents with _bulk upload to the index + $docs = array(); + $docs[] = new Document(2, + array('username' => 'john', 'test' => array('1', '3', '6')) + ); + $docs[] = new Document(3, + array('username' => 'rolf', 'test' => array('2', '3', '7')) + ); + $type->addDocuments($docs); + + // Refresh index + $index->refresh(); + + $resultSet = $type->search('rolf'); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Exception/NotImplementedTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Exception/NotImplementedTest.php new file mode 100644 index 00000000..ff704638 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Exception/NotImplementedTest.php @@ -0,0 +1,23 @@ +<?php + +namespace Elastica\Test\Exception; + +use Elastica\Exception\NotImplementedException; +use Elastica\Test\Base as BaseTest; + +class NotImplementedTest extends BaseTest +{ + public function testInstance() + { + $code = 4; + $message = 'Hello world'; + $exception = new NotImplementedException($message, $code); + + $this->assertInstanceOf('Elastica\Exception\NotImplementedException', $exception); + $this->assertInstanceOf('Elastica\Exception\ExceptionInterface', $exception); + $this->assertInstanceOf('Exception', $exception); + + $this->assertEquals($message, $exception->getMessage()); + $this->assertEquals($code, $exception->getCode()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Exception/PartialShardFailureExceptionTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Exception/PartialShardFailureExceptionTest.php new file mode 100644 index 00000000..31698e26 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Exception/PartialShardFailureExceptionTest.php @@ -0,0 +1,55 @@ +<?php + +namespace Elastica\Test\Exception; + +use Elastica\Document; +use Elastica\Exception\PartialShardFailureException; +use Elastica\Query; +use Elastica\ResultSet; +use Elastica\Test\Base as BaseTest; + +class PartialShardFailureExceptionTest extends BaseTest +{ + + public function testPartialFailure() + { + $client = $this->_getClient(); + $index = $client->getIndex('elastica_partial_failure'); + $index->create(array( + 'index' => array( + 'number_of_shards' => 5, + 'number_of_replicas' => 0 + ) + ), true); + + $type = $index->getType('folks'); + + $type->addDocument(new Document('', array('name' => 'ruflin'))); + $type->addDocument(new Document('', array('name' => 'bobrik'))); + $type->addDocument(new Document('', array('name' => 'kimchy'))); + + $index->refresh(); + + $query = Query::create(array( + 'query' => array( + 'filtered' => array( + 'filter' => array( + 'script' => array( + 'script' => 'doc["undefined"] > 8', // compiles, but doesn't work + ), + ), + ), + ), + )); + + try { + $index->search($query); + + $this->fail('PartialShardFailureException should have been thrown'); + } catch (PartialShardFailureException $e) { + $resultSet = new ResultSet($e->getResponse(), $query); + $this->assertEquals(0, count($resultSet->getResults())); + } + } + +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Exception/ResponseExceptionTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Exception/ResponseExceptionTest.php new file mode 100644 index 00000000..06b5462b --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Exception/ResponseExceptionTest.php @@ -0,0 +1,60 @@ +<?php + +namespace Elastica\Test\Exception; + +use Elastica\Document; +use Elastica\Exception\ResponseException; +use Elastica\Test\Base as BaseTest; + +class ResponseExceptionTest extends BaseTest +{ + + public function testCreateExistingIndex() + { + $this->_createIndex('woo', true); + + try { + $this->_createIndex('woo', false); + $this->fail('Index created when it should fail'); + } catch (ResponseException $ex) { + $this->assertEquals('IndexAlreadyExistsException', $ex->getElasticsearchException()->getExceptionName()); + $this->assertEquals(400, $ex->getElasticsearchException()->getCode()); + } + } + + public function testBadType() + { + $index = $this->_createIndex('woo'); + $type = $index->getType('test'); + + $type->setMapping(array( + 'num' => array( + 'type' => 'long' + ) + )); + + try { + $type->addDocument(new Document('', array( + 'num' => 'not number at all', + ))); + $this->fail('Indexing with wrong type should fail'); + } catch (ResponseException $ex) { + $this->assertEquals('MapperParsingException', $ex->getElasticsearchException()->getExceptionName()); + $this->assertEquals(400, $ex->getElasticsearchException()->getCode()); + } + } + + public function testWhatever() + { + $index = $this->_createIndex('woo'); + $index->delete(); + + try { + $index->search(); + } catch (ResponseException $ex) { + $this->assertEquals('IndexMissingException', $ex->getElasticsearchException()->getExceptionName()); + $this->assertEquals(404, $ex->getElasticsearchException()->getCode()); + } + } + +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/DateHistogramTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/DateHistogramTest.php new file mode 100644 index 00000000..46dcdbf9 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/DateHistogramTest.php @@ -0,0 +1,59 @@ +<?php + +namespace Elastica\Test\Facet; + +use Elastica\Document; +use Elastica\Facet\DateHistogram; +use Elastica\Query; +use Elastica\Query\MatchAll; +use Elastica\Test\Base as BaseTest; +use Elastica\Type\Mapping; + +class DateHistogramTest extends BaseTest +{ + public function testClassHierarchy() + { + $facet = new DateHistogram('dateHist1'); + $this->assertInstanceOf('Elastica\Facet\Histogram', $facet); + $this->assertInstanceOf('Elastica\Facet\AbstractFacet', $facet); + unset($facet); + } + + public function testTest() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('helloworld'); + + $mapping = new Mapping($type, array( + 'name' => array('type' => 'string', 'store' => 'no'), + 'dtmPosted' => array('type' => 'date', 'store' => 'no', 'format' => 'yyyy-MM-dd HH:mm:ss') + )); + $type->setMapping($mapping); + + $doc = new Document(1, array('name' => 'nicolas ruflin', 'dtmPosted' => "2011-06-23 21:53:00")); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'raul martinez jr', 'dtmPosted' => "2011-06-23 09:53:00")); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'rachelle clemente', 'dtmPosted' => "2011-07-08 08:53:00")); + $type->addDocument($doc); + $doc = new Document(4, array('name' => 'elastica search', 'dtmPosted' => "2011-07-08 01:53:00")); + $type->addDocument($doc); + + $facet = new DateHistogram('dateHist1'); + $facet->setInterval("day"); + $facet->setField("dtmPosted"); + + $query = new Query(); + $query->addFacet($facet); + $query->setQuery(new MatchAll()); + $index->refresh(); + + $response = $type->search($query); + $facets = $response->getFacets(); + + $this->assertEquals(4, $response->getTotalHits()); + $this->assertEquals(2, count($facets['dateHist1']['entries'])); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/FilterTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/FilterTest.php new file mode 100644 index 00000000..ca6f5ba3 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/FilterTest.php @@ -0,0 +1,40 @@ +<?php + +namespace Elastica\Test\Facet; + +use Elastica\Document; +use Elastica\Filter\Term; +use Elastica\Facet\Filter; +use Elastica\Query; +use Elastica\Test\Base as BaseTest; + +class FilterTest extends BaseTest +{ + public function testFilter() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('helloworld'); + + $type->addDocument(new Document(1, array('color' => 'red'))); + $type->addDocument(new Document(2, array('color' => 'green'))); + $type->addDocument(new Document(3, array('color' => 'blue'))); + + $index->refresh(); + + $filter = new Term(array('color' => 'red')); + + $facet = new Filter('test'); + $facet->setFilter($filter); + + $query = new Query(); + $query->addFacet($facet); + + $resultSet = $type->search($query); + + $facets = $resultSet->getFacets(); + + $this->assertEquals(1, $facets['test']['count']); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/GeoClusterTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/GeoClusterTest.php new file mode 100644 index 00000000..d06b58f9 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/GeoClusterTest.php @@ -0,0 +1,49 @@ +<?php + +namespace Elastica\Test\Facet; + +use Elastica\Test\Base as BaseTest; + +class GeoClusterTest extends BaseTest{ + public function testQuery() { + $client = $this->_getClient(); + $nodes = $client->getCluster()->getNodes(); + if(!$nodes[0]->getInfo()->hasPlugin('geocluster-facet')){ + $this->markTestSkipped('geocluster-facet plugin not installed'); + } + + $index = $this->_createIndex('geocluster_test'); + $type = $index->getType('testQuery'); + $geoField = 'location'; + + $type->setMapping(new \Elastica\Type\Mapping($type, array( + $geoField => array( 'type' => 'geo_point', 'lat_lon' => true ) + ))); + + $doc = new \Elastica\Document(1, array('name' => 'item1', 'location' => array(20,20))); + $type->addDocument($doc); + + $doc = new \Elastica\Document(2, array('name' => 'item2', 'location' => array(20,20))); + $type->addDocument($doc); + + $doc = new \Elastica\Document(3, array('name' => 'item3', 'location' => array(20,20))); + $type->addDocument($doc); + + $index->refresh(); + + $facet = new \Elastica\Facet\GeoCluster('clusters'); + $facet + ->setField($geoField) + ->setFactor(1) + ->setShowIds(false); + $query = new \Elastica\Query(); + $query->setFacets(array($facet)); + + $response = $type->search($query); + $facets = $response->getFacets(); + + $this->assertEquals(1, count($facets['clusters']['clusters'])); + + $index->delete(); + } +}
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/QueryTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/QueryTest.php new file mode 100644 index 00000000..ef5d7ccd --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/QueryTest.php @@ -0,0 +1,40 @@ +<?php + +namespace Elastica\Test\Facet; + +use Elastica\Document; +use Elastica\Facet\Query as FacetQuery; +use Elastica\Query; +use Elastica\Query\Term; +use Elastica\Test\Base as BaseTest; + +class QueryTest extends BaseTest +{ + public function testFilter() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('helloworld'); + + $type->addDocument(new Document(1, array('color' => 'red'))); + $type->addDocument(new Document(2, array('color' => 'green'))); + $type->addDocument(new Document(3, array('color' => 'blue'))); + + $index->refresh(); + + $termQuery = new Term(array('color' => 'red')); + + $facet = new FacetQuery('test'); + $facet->setQuery($termQuery); + + $query = new Query(); + $query->addFacet($facet); + + $resultSet = $type->search($query); + + $facets = $resultSet->getFacets(); + + $this->assertEquals(1, $facets['test']['count']); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/StatisticalTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/StatisticalTest.php new file mode 100644 index 00000000..0b528a79 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/StatisticalTest.php @@ -0,0 +1,82 @@ +<?php + +namespace Elastica\Test\Facet; + +use Elastica\Document; +use Elastica\Facet\Statistical; +use Elastica\Query; +use Elastica\Query\MatchAll; +use Elastica\Test\Base as BaseTest; + +class StatisticalTest extends BaseTest +{ + public function testStatisticalWithSetField() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('helloworld'); + + $doc = new Document(1, array('price' => 10)); + $type->addDocument($doc); + $doc = new Document(2, array('price' => 35)); + $type->addDocument($doc); + $doc = new Document(2, array('price' => 45)); + $type->addDocument($doc); + + $facet = new Statistical('stats'); + $facet->setField('price'); + + $query = new Query(); + $query->addFacet($facet); + $query->setQuery(new MatchAll()); + + $index->refresh(); + + $response = $type->search($query); + $facets = $response->getFacets(); + + $this->assertEquals(55, $facets['stats']['total']); + $this->assertEquals(10, $facets['stats']['min']); + $this->assertEquals(45, $facets['stats']['max']); + } + + public function testStatisticalWithSetFields() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('helloworld'); + + $doc = new Document(1, array('price' => 10, 'price2' => 20)); + $type->addDocument($doc); + $doc = new Document(2, array('price' => 35, 'price2' => 70)); + $type->addDocument($doc); + $doc = new Document(2, array('price' => 45, 'price2' => 90)); + $type->addDocument($doc); + + $facet = new Statistical('stats'); + $facet->setFields(array('price','price2')); + + $query = new Query(); + $query->addFacet($facet); + $query->setQuery(new MatchAll()); + + $index->refresh(); + + $response = $type->search($query); + $facets = $response->getFacets(); + + $this->assertEquals(165, $facets['stats']['total']); + $this->assertEquals(10, $facets['stats']['min']); + $this->assertEquals(90, $facets['stats']['max']); + } + + /** + * @todo + */ + public function testStatisticalWithSetScript() + { + $this->markTestIncomplete('Test for setting the script value'); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/TermsStatsTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/TermsStatsTest.php new file mode 100644 index 00000000..bea9b78d --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/TermsStatsTest.php @@ -0,0 +1,105 @@ +<?php + +namespace Elastica\Test\Facet; + +use Elastica\Document; +use Elastica\Facet\TermsStats; +use Elastica\Query; +use Elastica\Query\MatchAll; +use Elastica\Test\Base as BaseTest; + +class TermsStatsTest extends BaseTest +{ + public function testOrder() + { + $client = $this->_getClient(); + $index = $client->getIndex( 'test' ); + $index->create( array( ), true ); + $type = $index->getType( 'helloworld' ); + + $doc = new Document( 1, array( 'name' => 'tom', 'paid' => 7 ) ); + $type->addDocument( $doc ); + $doc = new Document( 2, array( 'name' => 'tom', 'paid' => 2 ) ); + $type->addDocument( $doc ); + $doc = new Document( 3, array( 'name' => 'tom', 'paid' => 5 ) ); + $type->addDocument( $doc ); + $doc = new Document( 4, array( 'name' => 'mike', 'paid' => 13 ) ); + $type->addDocument( $doc ); + $doc = new Document( 5, array( 'name' => 'mike', 'paid' => 1 ) ); + $type->addDocument( $doc ); + $doc = new Document( 6, array( 'name' => 'mike', 'paid' => 15 ) ); + $type->addDocument( $doc ); + + $facet = new TermsStats( 'test' ); + $facet->setKeyField( 'name' ); + $facet->setValueField( 'paid' ); + $facet->setOrder( 'reverse_total' ); + + $query = new Query(); + $query->addFacet( $facet ); + $query->setQuery( new MatchAll() ); + + $index->refresh(); + + $response = $type->search( $query ); + $facets = $response->getFacets(); + + $this->assertEquals(14, $facets[ 'test' ][ 'terms' ][0]['total'] ); + $this->assertEquals(29, $facets[ 'test' ][ 'terms' ][1]['total'] ); + } + + public function testQuery() + { + $client = $this->_getClient(); + $index = $client->getIndex( 'test' ); + $index->create( array( ), true ); + $type = $index->getType( 'helloworld' ); + + $doc = new Document( 1, array( 'name' => 'tom', 'paid' => 7 ) ); + $type->addDocument( $doc ); + $doc = new Document( 2, array( 'name' => 'tom', 'paid' => 2 ) ); + $type->addDocument( $doc ); + $doc = new Document( 3, array( 'name' => 'tom', 'paid' => 5 ) ); + $type->addDocument( $doc ); + $doc = new Document( 4, array( 'name' => 'mike', 'paid' => 13 ) ); + $type->addDocument( $doc ); + $doc = new Document( 5, array( 'name' => 'mike', 'paid' => 1 ) ); + $type->addDocument( $doc ); + $doc = new Document( 6, array( 'name' => 'mike', 'paid' => 15 ) ); + $type->addDocument( $doc ); + + $facet = new TermsStats( 'test' ); + $facet->setKeyField( 'name' ); + $facet->setValueField( 'paid' ); + + $query = new Query(); + $query->addFacet( $facet ); + $query->setQuery( new MatchAll() ); + + $index->refresh(); + + $response = $type->search( $query ); + $facets = $response->getFacets(); + + $this->assertEquals( 2, count( $facets[ 'test' ][ 'terms' ] ) ); + foreach ($facets[ 'test' ][ 'terms' ] as $facet) { + if ($facet[ 'term' ] === 'tom') { + $this->assertEquals( 14, $facet[ 'total' ] ); + } + if ($facet[ 'term' ] === 'mike') { + $this->assertEquals( 29, $facet[ 'total' ] ); + } + } + } + + public function testSetSize() + { + $facet = new TermsStats( 'test' ); + $facet->setSize(100); + + $data = $facet->toArray(); + + $this->assertArrayHasKey('size', $data['terms_stats']); + $this->assertEquals(100, $data['terms_stats']['size']); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/TermsTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/TermsTest.php new file mode 100644 index 00000000..e8521c5c --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Facet/TermsTest.php @@ -0,0 +1,69 @@ +<?php + +namespace Elastica\Test\Facet; + +use Elastica\Document; +use Elastica\Facet\Terms; +use Elastica\Query; +use Elastica\Query\MatchAll; +use Elastica\Test\Base as BaseTest; + +class TermsTest extends BaseTest +{ + public function testQuery() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('helloworld'); + + $doc = new Document(1, array('name' => 'nicolas ruflin')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'ruflin test')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'nicolas helloworld')); + $type->addDocument($doc); + + $facet = new Terms('test'); + $facet->setField('name'); + + $query = new Query(); + $query->addFacet($facet); + $query->setQuery(new MatchAll()); + + $index->refresh(); + + $response = $type->search($query); + $facets = $response->getFacets(); + + $this->assertEquals(3, count($facets['test']['terms'])); + } + + public function testFacetScript() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('helloworld'); + + $doc = new Document(1, array('name' => 'rodolfo', 'last_name' => 'moraes')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'jose', 'last_name' => 'honjoya')); + $type->addDocument($doc); + + $facet = new Terms('test'); + $facet->setField('name'); + $facet->setScript('term + " "+doc["last_name"].value'); + + $query = new Query(); + $query->addFacet($facet); + $query->setQuery(new MatchAll()); + + $index->refresh(); + + $response = $type->search($query); + $facets = $response->getFacets(); + + $this->assertEquals(2, count($facets['test']['terms'])); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/AbstractTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/AbstractTest.php new file mode 100644 index 00000000..1e47819f --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/AbstractTest.php @@ -0,0 +1,69 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Test\Base as BaseTest; + +class AbstractTest extends BaseTest +{ + public function testSetCached() + { + $stubFilter = $this->getStub(); + + $stubFilter->setCached(true); + $arrayFilter = current($stubFilter->toArray()); + $this->assertTrue($arrayFilter['_cache']); + + $stubFilter->setCached(false); + $arrayFilter = current($stubFilter->toArray()); + $this->assertFalse($arrayFilter['_cache']); + } + + public function testSetCachedDefaultValue() + { + $stubFilter = $this->getStub(); + + $stubFilter->setCached(); + $arrayFilter = current($stubFilter->toArray()); + $this->assertTrue($arrayFilter['_cache']); + } + + public function testSetCacheKey() + { + $stubFilter = $this->getStub(); + + $cacheKey = 'myCacheKey'; + + $stubFilter->setCacheKey($cacheKey); + $arrayFilter = current($stubFilter->toArray()); + $this->assertEquals($cacheKey, $arrayFilter['_cache_key']); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testSetCacheKeyEmptyKey() + { + $stubFilter = $this->getStub(); + + $cacheKey = ''; + + $stubFilter->setCacheKey($cacheKey); + } + + public function testSetName() + { + $stubFilter = $this->getStub(); + + $name = 'myFilter'; + + $stubFilter->setName($name); + $arrayFilter = current($stubFilter->toArray()); + $this->assertEquals($name, $arrayFilter['_name']); + } + + private function getStub() + { + return $this->getMockForAbstractClass('Elastica\Filter\AbstractFilter'); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/BoolAndTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/BoolAndTest.php new file mode 100644 index 00000000..672c6c67 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/BoolAndTest.php @@ -0,0 +1,65 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Document; +use Elastica\Filter\BoolAnd; +use Elastica\Filter\Ids; +use Elastica\Test\Base as BaseTest; + +class BoolAndTest extends BaseTest +{ + public function testToArray() + { + $and = new BoolAnd(); + $this->assertEquals(array('and' => array()), $and->toArray()); + + $idsFilter = new Ids(); + $idsFilter->setIds(12); + + $and->addFilter($idsFilter); + $and->addFilter($idsFilter); + + $expectedArray = array( + 'and' => array( + $idsFilter->toArray(), + $idsFilter->toArray() + ) + ); + + $this->assertEquals($expectedArray, $and->toArray()); + } + + public function testSetCache() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('test'); + + $doc = new Document(1, array('name' => 'hello world')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'nicolas ruflin')); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'ruflin')); + $type->addDocument($doc); + + $and = new BoolAnd(); + + $idsFilter1 = new Ids(); + $idsFilter1->setIds(1); + + $idsFilter2 = new Ids(); + $idsFilter2->setIds(1); + + $and->addFilter($idsFilter1); + $and->addFilter($idsFilter2); + + $index->refresh(); + $and->setCached(true); + + $resultSet = $type->search($and); + + $this->assertEquals(1, $resultSet->count()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/BoolNotTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/BoolNotTest.php new file mode 100644 index 00000000..adcebf45 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/BoolNotTest.php @@ -0,0 +1,25 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Filter\Ids; +use Elastica\Filter\BoolNot; +use Elastica\Test\Base as BaseTest; + +class BoolNotTest extends BaseTest +{ + public function testToArray() + { + $idsFilter = new Ids(); + $idsFilter->setIds(12); + $filter = new BoolNot($idsFilter); + + $expectedArray = array( + 'not' => array( + 'filter' => $idsFilter->toArray() + ) + ); + + $this->assertEquals($expectedArray, $filter->toArray()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/BoolOrTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/BoolOrTest.php new file mode 100644 index 00000000..25234a8c --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/BoolOrTest.php @@ -0,0 +1,42 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Filter\AbstractFilter; +use Elastica\Filter\BoolOr; +use Elastica\Filter\Ids; +use Elastica\Test\Base as BaseTest; + +class BoolOrTest extends BaseTest +{ + public function testAddFilter() + { + $filter = $this->getMockForAbstractClass('Elastica\Filter\AbstractFilter'); + $orFilter = new BoolOr(); + $returnValue = $orFilter->addFilter($filter); + $this->assertInstanceOf('Elastica\Filter\BoolOr', $returnValue); + } + + public function testToArray() + { + $orFilter = new BoolOr(); + + $filter1 = new Ids(); + $filter1->setIds('1'); + + $filter2 = new Ids(); + $filter2->setIds('2'); + + $orFilter->addFilter($filter1); + $orFilter->addFilter($filter2); + + $expectedArray = array( + 'or' => array( + $filter1->toArray(), + $filter2->toArray() + ) + ); + + $this->assertEquals($expectedArray, $orFilter->toArray()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/BoolTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/BoolTest.php new file mode 100644 index 00000000..60eb3a45 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/BoolTest.php @@ -0,0 +1,107 @@ +<?php + +namespace Elastica\Test\Filter; + +use \Elastica\Query; +use Elastica\Filter\Bool; +use Elastica\Filter\Term; +use Elastica\Filter\Ids; +use Elastica\Test\Base as BaseTest; + +class BoolTest extends BaseTest +{ + public function testToArray() + { + $mainBool = new Bool(); + + $idsFilter1 = new Ids(); + $idsFilter1->setIds(1); + $idsFilter2 = new Ids(); + $idsFilter2->setIds(2); + $idsFilter3 = new Ids(); + $idsFilter3->setIds(3); + + $childBool = new Bool(); + $childBool->addShould(array($idsFilter1, $idsFilter2)); + $mainBool->addShould(array($childBool, $idsFilter3)); + + $expectedArray = array( + 'bool' => array( + 'should' => array( + array( + array( + 'bool' => array( + 'should' => array( + array( + $idsFilter1->toArray(), + $idsFilter2->toArray() + ) + ) + ) + ), + $idsFilter3->toArray() + ) + ) + ) + ); + + $this->assertEquals($expectedArray, $mainBool->toArray()); + } + + public function testBoolFilter() + { + $index = $this->_createIndex('bool_filter_test'); + $type = $index->getType('book'); + + //index some test data + $type->addDocument(new \Elastica\Document(1, array('author' => 'Michael Shermer', 'title' => 'The Believing Brain', 'publisher' => 'Robinson'))); + $type->addDocument(new \Elastica\Document(2, array('author' => 'Jared Diamond', 'title' => 'Guns, Germs and Steel', 'publisher' => 'Vintage'))); + $type->addDocument(new \Elastica\Document(3, array('author' => 'Jared Diamond', 'title' => 'Collapse', 'publisher' => 'Penguin'))); + $type->addDocument(new \Elastica\Document(4, array('author' => 'Richard Dawkins', 'title' => 'The Selfish Gene', 'publisher' => 'OUP Oxford'))); + $type->addDocument(new \Elastica\Document(5, array('author' => 'Anthony Burges', 'title' => 'A Clockwork Orange', 'publisher' => 'Penguin'))); + + $index->refresh(); + + //use the terms lookup feature to query for some data + //build query + //must + // should + // author = jared + // author = richard + // must_not + // publisher = penguin + + //construct the query + $query = new Query(); + $mainBoolFilter = new Bool(); + $shouldFilter = new Bool(); + $authorFilter1 = new Term(); + $authorFilter1->setTerm('author', 'jared'); + $authorFilter2 = new Term(); + $authorFilter2->setTerm('author', 'richard'); + $shouldFilter->addShould(array($authorFilter1, $authorFilter2)); + + $mustNotFilter = new Bool(); + $publisherFilter = new Term(); + $publisherFilter->setTerm('publisher', 'penguin'); + $mustNotFilter->addMustNot($publisherFilter); + + $mainBoolFilter->addMust(array($shouldFilter, $mustNotFilter)); + $query->setFilter($mainBoolFilter); + //execute the query + $results = $index->search($query); + + //check the number of results + $this->assertEquals($results->count(), 2, 'Bool filter with child Bool filters: number of results check'); + + //count compare the id's + $ids = array(); + /** @var \Elastica\Result $result **/ + foreach($results as $result){ + $ids[] = $result->getId(); + } + $this->assertEquals($ids, array("2","4"), 'Bool filter with child Bool filters: result ID check'); + + $index->delete(); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/ExistsTests.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/ExistsTests.php new file mode 100644 index 00000000..9e4f5b67 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/ExistsTests.php @@ -0,0 +1,31 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Filter\Exists; +use Elastica\Test\Base as BaseTest; + +class ExistsTest extends BaseTest +{ + public function testToArray() + { + $field = 'test'; + $filter = new Exists($field); + + $expectedArray = array('exists' => array('field' => $field)); + $this->assertEquals($expectedArray, $filter->toArray()); + } + + public function testSetField() + { + $field = 'test'; + $filter = new Exists($field); + + $this->assertEquals($field, $filter->getParam('field')); + + $newField = 'hello world'; + $this->assertInstanceOf('Elastica\Filter\Exists', $filter->setField($newField)); + + $this->assertEquals($newField, $filter->getParam('field')); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeoDistanceRangeTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeoDistanceRangeTest.php new file mode 100644 index 00000000..4c4d2bcc --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeoDistanceRangeTest.php @@ -0,0 +1,218 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Document; +use Elastica\Filter\GeoDistanceRange; +use Elastica\Query; +use Elastica\Query\MatchAll; +use Elastica\Test\Base as BaseTest; + +class GeoDistanceRangeTest extends BaseTest +{ + public function testGeoPoint() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + + $type = $index->getType('test'); + + // Set mapping + $type->setMapping(array('point' => array('type' => 'geo_point'))); + + // Add doc 1 + $doc1 = new Document(1, + array( + 'name' => 'ruflin', + ) + ); + + $doc1->addGeoPoint('point', 17, 19); + $type->addDocument($doc1); + + // Add doc 2 + $doc2 = new Document(2, + array( + 'name' => 'ruflin', + ) + ); + + $doc2->addGeoPoint('point', 30, 40); + $type->addDocument($doc2); + + $index->optimize(); + $index->refresh(); + + // Only one point should be in radius + $query = new Query(); + $geoFilter = new GeoDistanceRange( + 'point', + array('lat' => 30, 'lon' => 40), + array('from' => '0km', 'to' => '2km') + ); + + $query = new Query(new MatchAll()); + $query->setFilter($geoFilter); + $this->assertEquals(1, $type->search($query)->count()); + + // Both points should be inside + $query = new Query(); + $geoFilter = new GeoDistanceRange( + 'point', + array('lat' => 30, 'lon' => 40), + array('gte' => '0km', 'lte' => '40000km') + ); + $query = new Query(new MatchAll()); + $query->setFilter($geoFilter); + $index->refresh(); + + $this->assertEquals(2, $type->search($query)->count()); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testInvalidRange() + { + $geoFilter = new GeoDistanceRange( + 'point', + array('lat' => 30, 'lon' => 40), + array('invalid' => '0km', 'lte' => '40000km') + ); + } + + /** + * @dataProvider invalidLocationDataProvider + * @expectedException \Elastica\Exception\InvalidException + */ + public function testInvalidLocation($location) + { + $geoFilter = new GeoDistanceRange( + 'point', + $location, + array('gt' => '0km', 'lte' => '40000km') + ); + } + + /** + * @dataProvider constructDataProvider + */ + public function testConstruct($key, $location, $ranges, $expected) + { + $filter = new GeoDistanceRange($key, $location, $ranges); + + $data = $filter->toArray(); + + $this->assertEquals($expected, $data); + } + + public function invalidLocationDataProvider() + { + return array( + array( + array('lat' => 1.0), + ), + array( + array('lon' => 1.0), + ), + array( + array(), + ), + array( + new \stdClass(), + ), + array( + null, + ), + array( + true, + ), + array( + false, + ) + ); + } + + public function constructDataProvider() + { + return array( + array( + 'location', + 'u09tvqx', + array( + 'from' => '10km', + 'to' => '20km', + ), + array( + 'geo_distance_range' => array( + 'from' => '10km', + 'to' => '20km', + 'location' => 'u09tvqx', + ) + ) + ), + array( + 'location', + 'u09tvqx', + array( + 'to' => '20km', + 'include_upper' => 0, + 'from' => '10km', + 'include_lower' => 1, + ), + array( + 'geo_distance_range' => array( + 'to' => '20km', + 'include_upper' => false, + 'from' => '10km', + 'include_lower' => true, + 'location' => 'u09tvqx', + ) + ) + ), + array( + 'location', + array( + 'lon' => 2.35, + 'lat' => 48.86, + ), + array( + 'lte' => '20km', + 'gt' => '10km', + ), + array( + 'geo_distance_range' => array( + 'lte' => '20km', + 'gt' => '10km', + 'location' => array( + 'lat' => 48.86, + 'lon' => 2.35, + ), + ) + ) + ), + array( + 'location', + array( + 'lat' => 48.86, + 'lon' => 2.35, + ), + array( + 'lt' => '20km', + 'gte' => '10km', + ), + array( + 'geo_distance_range' => array( + 'lt' => '20km', + 'gte' => '10km', + 'location' => array( + 'lat' => 48.86, + 'lon' => 2.35, + ), + ) + ) + ) + ); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeoDistanceTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeoDistanceTest.php new file mode 100644 index 00000000..a5049914 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeoDistanceTest.php @@ -0,0 +1,129 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Document; +use Elastica\Filter\GeoDistance; +use Elastica\Query; +use Elastica\Query\MatchAll; +use Elastica\Test\Base as BaseTest; + +class GeoDistanceTest extends BaseTest +{ + public function testGeoPoint() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + + $type = $index->getType('test'); + + // Set mapping + $type->setMapping(array('point' => array('type' => 'geo_point'))); + + // Add doc 1 + $doc1 = new Document(1, + array( + 'name' => 'ruflin', + ) + ); + + $doc1->addGeoPoint('point', 17, 19); + $type->addDocument($doc1); + + // Add doc 2 + $doc2 = new Document(2, + array( + 'name' => 'ruflin', + ) + ); + + $doc2->addGeoPoint('point', 30, 40); + $type->addDocument($doc2); + + $index->optimize(); + $index->refresh(); + + // Only one point should be in radius + $query = new Query(); + $geoFilter = new GeoDistance('point', array('lat' => 30, 'lon' => 40), '1km'); + + $query = new Query(new MatchAll()); + $query->setFilter($geoFilter); + $this->assertEquals(1, $type->search($query)->count()); + + // Both points should be inside + $query = new Query(); + $geoFilter = new GeoDistance('point', array('lat' => 30, 'lon' => 40), '40000km'); + $query = new Query(new MatchAll()); + $query->setFilter($geoFilter); + $index->refresh(); + + $this->assertEquals(2, $type->search($query)->count()); + } + + public function testConstructLatlon() + { + $key = 'location'; + $location = array( + 'lat' => 48.86, + 'lon' => 2.35 + ); + $distance = '10km'; + + $filter = new GeoDistance($key, $location, $distance); + + $expected = array( + 'geo_distance' => array( + $key => $location, + 'distance' => $distance + ) + ); + + $data = $filter->toArray(); + + $this->assertEquals($expected, $data); + } + + public function testConstructGeohash() + { + $key = 'location'; + $location = 'u09tvqx'; + $distance = '10km'; + + $filter = new GeoDistance($key, $location, $distance); + + $expected = array( + 'geo_distance' => array( + $key => $location, + 'distance' => $distance + ) + ); + + $data = $filter->toArray(); + + $this->assertEquals($expected, $data); + } + + public function testSetDistanceType() + { + $filter = new GeoDistance('location', array('lat' => 48.86, 'lon' => 2.35), '10km'); + $distanceType = GeoDistance::DISTANCE_TYPE_ARC; + $filter->setDistanceType($distanceType); + + $data = $filter->toArray(); + + $this->assertEquals($distanceType, $data['geo_distance']['distance_type']); + } + + public function testSetOptimizeBbox() + { + $filter = new GeoDistance('location', array('lat' => 48.86, 'lon' => 2.35), '10km'); + $optimizeBbox = GeoDistance::OPTIMIZE_BBOX_MEMORY; + $filter->setOptimizeBbox($optimizeBbox); + + $data = $filter->toArray(); + + $this->assertEquals($optimizeBbox, $data['geo_distance']['optimize_bbox']); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeoPolygonTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeoPolygonTest.php new file mode 100644 index 00000000..7ebd738c --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeoPolygonTest.php @@ -0,0 +1,65 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Document; +use Elastica\Filter\GeoPolygon; +use Elastica\Query; +use Elastica\Query\MatchAll; +use Elastica\Test\Base as BaseTest; + +class GeoPolygonTest extends BaseTest +{ + public function testGeoPoint() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + + $type = $index->getType('test'); + + // Set mapping + $type->setMapping(array('location' => array('type' => 'geo_point'))); + + // Add doc 1 + $doc1 = new Document(1, + array( + 'name' => 'ruflin', + ) + ); + + $doc1->addGeoPoint('location', 17, 19); + $type->addDocument($doc1); + + // Add doc 2 + $doc2 = new Document(2, + array( + 'name' => 'ruflin', + ) + ); + + $doc2->addGeoPoint('location', 30, 40); + $type->addDocument($doc2); + + $index->refresh(); + + // Only one point should be in polygon + $query = new Query(); + $points = array(array(16, 16), array(16, 20), array(20, 20), array(20, 16), array(16, 16)); + $geoFilter = new GeoPolygon('location', $points); + + $query = new Query(new MatchAll()); + $query->setFilter($geoFilter); + $this->assertEquals(1, $type->search($query)->count()); + + // Both points should be inside + $query = new Query(); + $points = array(array(16, 16), array(16, 40), array(40, 40), array(40, 16), array(16, 16)); + $geoFilter = new GeoPolygon('location', $points); + + $query = new Query(new MatchAll()); + $query->setFilter($geoFilter); + + $this->assertEquals(2, $type->search($query)->count()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeoShapePreIndexedTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeoShapePreIndexedTest.php new file mode 100644 index 00000000..21afec1a --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeoShapePreIndexedTest.php @@ -0,0 +1,90 @@ +<?php + + +namespace Elastica\Test\Filter; + +use Elastica\Filter\AbstractGeoShape; +use Elastica\Filter\GeoShapePreIndexed; +use Elastica\Query\MatchAll; +use Elastica\Query\Filtered; +use Elastica\Test\Base as BaseTest; + +class GeoShapePreIndexedTest extends BaseTest +{ + public function testGeoProvided() + { + $indexName = 'geo_shape_filter_test'; + $index = $this->_createIndex($indexName); + $type = $index->getType('type'); + $otherType = $index->getType('other_type'); + + // create mapping + $mapping = new \Elastica\Type\Mapping($type, array( + 'location' => array( + 'type' => 'geo_shape' + ) + )); + $type->setMapping($mapping); + + // create other type mapping + $otherMapping = new \Elastica\Type\Mapping($type, array( + 'location' => array( + 'type' => 'geo_shape' + ) + )); + $otherType->setMapping($otherMapping); + + // add type docs + $type->addDocument(new \Elastica\Document('1', array( + 'location' => array( + "type" => "envelope", + "coordinates" => array( + array(0.0, 50.0), + array(50.0, 0.0) + ) + ) + ))); + + // add other type docs + $otherType->addDocument(new \Elastica\Document('2', array( + 'location' => array( + "type" => "envelope", + "coordinates" => array( + array(25.0, 75.0), + array(75.0, 25.0) + ) + ) + ))); + + $index->optimize(); + $index->refresh(); + + $gsp = new GeoShapePreIndexed( + 'location', '1', 'type', 'elastica_'.$indexName, 'location' + ); + $gsp->setRelation(AbstractGeoShape::RELATION_INTERSECT); + + $expected = array( + 'geo_shape' => array( + 'location' => array( + 'indexed_shape' => array( + 'id' => '1', + 'type' => 'type', + 'index' => 'elastica_'.$indexName, + 'path' => 'location' + ), + 'relation' => $gsp->getRelation() + ) + ) + ); + + $this->assertEquals($expected, $gsp->toArray()); + + $query = new Filtered(new MatchAll(), $gsp); + $results = $index->getType('type')->search($query); + + $this->assertEquals(1, $results->count()); + + $index->delete(); + } +}
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeoShapeProvidedTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeoShapeProvidedTest.php new file mode 100644 index 00000000..146150a3 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeoShapeProvidedTest.php @@ -0,0 +1,88 @@ +<?php + + +namespace Elastica\Test\Filter; + +use Elastica\Filter\AbstractGeoShape; +use Elastica\Filter\GeoShapeProvided; +use Elastica\Query\Filtered; +use Elastica\Query\MatchAll; +use Elastica\Test\Base as BaseTest; + +class GeoShapeProvidedTest extends BaseTest +{ + public function testConstructEnvelope() + { + $index = $this->_createIndex('geo_shape_filter_test'); + $type = $index->getType('test'); + + // create mapping + $mapping = new \Elastica\Type\Mapping($type, array( + 'location' => array( + 'type' => 'geo_shape' + ) + )); + $type->setMapping($mapping); + + // add docs + $type->addDocument(new \Elastica\Document(1, array( + 'location' => array( + "type" => "envelope", + "coordinates" => array( + array(-50.0, 50.0), + array(50.0, -50.0) + ) + ) + ))); + + $index->optimize(); + $index->refresh(); + + $envelope = array( + array(25.0, 75.0), + array(75.0, 25.0) + ); + $gsp = new GeoShapeProvided('location', $envelope); + + $expected = array( + 'geo_shape' => array( + 'location' => array( + 'shape' => array( + 'type' => GeoShapeProvided::TYPE_ENVELOPE, + 'coordinates' => $envelope + ), + 'relation' => AbstractGeoShape::RELATION_INTERSECT + ), + ) + ); + + $this->assertEquals($expected, $gsp->toArray()); + + $query = new Filtered(new MatchAll(), $gsp); + $results = $type->search($query); + + $this->assertEquals(1, $results->count()); + + $index->delete(); + } + + public function testConstructPolygon() + { + $polygon = array(array(102.0, 2.0), array(103.0, 2.0), array(103.0, 3.0), array(103.0, 3.0), array(102.0, 2.0)); + $gsp = new GeoShapeProvided('location', $polygon, GeoShapeProvided::TYPE_POLYGON); + + $expected = array( + 'geo_shape' => array( + 'location' => array( + 'shape' => array( + 'type' => GeoShapeProvided::TYPE_POLYGON, + 'coordinates' => $polygon + ), + 'relation' => $gsp->getRelation() + ), + ) + ); + + $this->assertEquals($expected, $gsp->toArray()); + } +}
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeohashCellTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeohashCellTest.php new file mode 100644 index 00000000..7cb8aef6 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/GeohashCellTest.php @@ -0,0 +1,60 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Test\Base as BaseTest; +use Elastica\Filter\GeohashCell; + +class GeohashCellTest extends BaseTest +{ + public function testToArray() + { + $filter = new GeohashCell('pin', array('lat' => 37.789018, 'lon' => -122.391506), '50m'); + $expected = array( + 'geohash_cell' => array( + 'pin' => array( + 'lat' => 37.789018, + 'lon' => -122.391506 + ), + 'precision' => '50m', + 'neighbors' => false + ) + ); + $this->assertEquals($expected, $filter->toArray()); + } + + public function testFilter() + { + $index = $this->_createIndex('geohash_filter_test'); + $type = $index->getType('test'); + $mapping = new \Elastica\Type\Mapping($type, array( + 'pin' => array( + 'type' => 'geo_point', + 'geohash' => true, + 'geohash_prefix' => true + ) + )); + $type->setMapping($mapping); + + $type->addDocument(new \Elastica\Document(1, array('pin' => '9q8yyzm0zpw8'))); + $type->addDocument(new \Elastica\Document(2, array('pin' => '9mudgb0yued0'))); + $index->refresh(); + + $filter = new GeohashCell('pin', array('lat' => 32.828326, 'lon' => -117.255854)); + $query = new \Elastica\Query(); + $query->setFilter($filter); + $results = $type->search($query); + + $this->assertEquals(1, $results->count()); + + //test precision parameter + $filter = new GeohashCell('pin', '9', 1); + $query = new \Elastica\Query(); + $query->setFilter($filter); + $results = $type->search($query); + + $this->assertEquals(2, $results->count()); + + $index->delete(); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/HasChildTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/HasChildTest.php new file mode 100644 index 00000000..8bba8173 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/HasChildTest.php @@ -0,0 +1,166 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Document; +use Elastica\Filter\HasChild; +use Elastica\Query\MatchAll; +use Elastica\Test\Base as BaseTest; + +class HasChildTest extends BaseTest +{ + public function testToArray() + { + $q = new MatchAll(); + + $type = 'test'; + + $filter = new HasChild($q, $type); + + $expectedArray = array( + 'has_child' => array( + 'query' => $q->toArray(), + 'type' => $type + ) + ); + + $this->assertEquals($expectedArray, $filter->toArray()); + } + + public function testSetScope() + { + $q = new MatchAll(); + + $type = 'test'; + + $scope = 'foo'; + + $filter = new HasChild($q, $type); + $filter->setScope($scope); + + $expectedArray = array( + 'has_child' => array( + 'query' => $q->toArray(), + 'type' => $type, + '_scope' => $scope + ) + ); + + $this->assertEquals($expectedArray, $filter->toArray()); + } + + public function testFilterInsideHasChild() + { + $f = new \Elastica\Filter\MatchAll(); + + $type = 'test'; + + $filter = new HasChild($f, $type); + + $expectedArray = array( + 'has_child' => array( + 'filter' => $f->toArray(), + 'type' => $type + ) + ); + + $this->assertEquals($expectedArray, $filter->toArray()); + + } + + public function testFilterInsideHasChildSearch() + { + $index = $this->prepareSearchData(); + + $f = new \Elastica\Filter\Term(); + $f->setTerm('user', 'child1'); + $filter = new HasChild($f, 'child'); + + $searchQuery = new \Elastica\Query(); + $searchQuery->setFilter($filter); + $searchResults = $index->search($searchQuery); + + $this->assertEquals(1, $searchResults->count()); + + $result = $searchResults->current()->getData(); + $expected = array('id' => 'parent1', 'user' => 'parent1', 'email' => 'parent1@test.com'); + + $this->assertEquals($expected, $result); + } + + public function testQueryInsideHasChildSearch() + { + $index = $this->prepareSearchData(); + + $f = new \Elastica\Query\Term(); + $f->setTerm('user', 'child1'); + $filter = new HasChild($f, 'child'); + + $searchQuery = new \Elastica\Query(); + $searchQuery->setFilter($filter); + $searchResults = $index->search($searchQuery); + + $this->assertEquals(1, $searchResults->count()); + + $result = $searchResults->current()->getData(); + $expected = array('id' => 'parent1', 'user' => 'parent1', 'email' => 'parent1@test.com'); + + $this->assertEquals($expected, $result); + } + + public function testTypeInsideHasChildSearch() + { + $index = $this->prepareSearchData(); + + $f = new \Elastica\Query\Match(); + $f->setField('alt.name', 'testname'); + $filter = new HasChild($f, 'child'); + + $searchQuery = new \Elastica\Query(); + $searchQuery->setFilter($filter); + $searchResults = $index->search($searchQuery); + + $this->assertEquals(1, $searchResults->count()); + + $result = $searchResults->current()->getData(); + $expected = array('id' => 'parent2', 'user' => 'parent2', 'email' => 'parent2@test.com'); + + $this->assertEquals($expected, $result); + } + + private function prepareSearchData() + { + $client = $this->_getClient(); + $index = $client->getIndex('has_child_test'); + $index->create(array(), true); + + $parentType = $index->getType('parent'); + + $childType = $index->getType('child'); + $childMapping = new \Elastica\Type\Mapping($childType); + $childMapping->setParent('parent'); + $childMapping->send(); + + $altType = $index->getType('alt'); + $altDoc = new Document('alt1', array('name' => 'altname')); + $altType->addDocument($altDoc); + + $parent1 = new Document('parent1', array('id' => 'parent1', 'user' => 'parent1', 'email' => 'parent1@test.com')); + $parentType->addDocument($parent1); + $parent2 = new Document('parent2', array('id' => 'parent2', 'user' => 'parent2', 'email' => 'parent2@test.com')); + $parentType->addDocument($parent2); + + $child1 = new Document('child1', array('id' => 'child1', 'user' => 'child1', 'email' => 'child1@test.com')); + $child1->setParent('parent1'); + $childType->addDocument($child1); + $child2 = new Document('child2', array('id' => 'child2', 'user' => 'child2', 'email' => 'child2@test.com')); + $child2->setParent('parent2'); + $childType->addDocument($child2); + $child3 = new Document('child3', array('id' => 'child3', 'user' => 'child3', 'email' => 'child3@test.com', 'alt' => array(array('name' => 'testname')))); + $child3->setParent('parent2'); + $childType->addDocument($child3); + + $index->refresh(); + return $index; + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/HasParentTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/HasParentTest.php new file mode 100644 index 00000000..7998372b --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/HasParentTest.php @@ -0,0 +1,139 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Document; +use Elastica\Filter\HasParent; +use Elastica\Query\MatchAll; +use Elastica\Test\Base as BaseTest; + +class HasParentTest extends BaseTest +{ + public function testToArray() + { + $q = new MatchAll(); + + $type = 'test'; + + $filter = new HasParent($q, $type); + + $expectedArray = array( + 'has_parent' => array( + 'query' => $q->toArray(), + 'type' => $type + ) + ); + + $this->assertEquals($expectedArray, $filter->toArray()); + } + + public function testSetScope() + { + $q = new MatchAll(); + + $type = 'test'; + + $scope = 'foo'; + + $filter = new HasParent($q, $type); + $filter->setScope($scope); + + $expectedArray = array( + 'has_parent' => array( + 'query' => $q->toArray(), + 'type' => $type, + '_scope' => $scope + ) + ); + + $this->assertEquals($expectedArray, $filter->toArray()); + } + + public function testFilterInsideHasParent() + { + $f = new \Elastica\Filter\MatchAll(); + + $type = 'test'; + + $filter = new HasParent($f, $type); + + $expectedArray = array( + 'has_parent' => array( + 'filter' => $f->toArray(), + 'type' => $type + ) + ); + + $this->assertEquals($expectedArray, $filter->toArray()); + + } + + public function testFilterInsideHasParentSearch() + { + $index = $this->prepareSearchData(); + + $f = new \Elastica\Filter\Term(); + $f->setTerm('user', 'parent1'); + $filter = new HasParent($f, 'parent'); + + $searchQuery = new \Elastica\Query(); + $searchQuery->setFilter($filter); + $searchResults = $index->search($searchQuery); + + $this->assertEquals(1, $searchResults->count()); + + $result = $searchResults->current()->getData(); + $expected = array('id' => 'child1', 'user' => 'child1', 'email' => 'child1@test.com'); + + $this->assertEquals($expected, $result); + } + + public function testQueryInsideHasParentSearch() + { + $index = $this->prepareSearchData(); + + $f = new \Elastica\Query\Term(); + $f->setTerm('user', 'parent1'); + $filter = new HasParent($f, 'parent'); + + $searchQuery = new \Elastica\Query(); + $searchQuery->setFilter($filter); + $searchResults = $index->search($searchQuery); + + $this->assertEquals(1, $searchResults->count()); + + $result = $searchResults->current()->getData(); + $expected = array('id' => 'child1', 'user' => 'child1', 'email' => 'child1@test.com'); + + $this->assertEquals($expected, $result); + } + + private function prepareSearchData() + { + $client = $this->_getClient(); + $index = $client->getIndex('has_parent_test'); + $index->create(array(), true); + + $parentType = $index->getType('parent'); + + $childType = $index->getType('child'); + $childMapping = new \Elastica\Type\Mapping($childType); + $childMapping->setParent('parent'); + $childMapping->send(); + + $parent1 = new Document('parent1', array('id' => 'parent1', 'user' => 'parent1', 'email' => 'parent1@test.com')); + $parentType->addDocument($parent1); + $parent2 = new Document('parent2', array('id' => 'parent2', 'user' => 'parent2', 'email' => 'parent2@test.com')); + $parentType->addDocument($parent2); + + $child1 = new Document('child1', array('id' => 'child1', 'user' => 'child1', 'email' => 'child1@test.com')); + $child1->setParent('parent1'); + $childType->addDocument($child1); + $child2 = new Document('child2', array('id' => 'child2', 'user' => 'child2', 'email' => 'child2@test.com')); + $child2->setParent('parent2'); + $childType->addDocument($child2); + + $index->refresh(); + return $index; + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/IdsTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/IdsTest.php new file mode 100644 index 00000000..3d6af870 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/IdsTest.php @@ -0,0 +1,201 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Document; +use Elastica\Filter\Ids; +use Elastica\Filter\Type; +use Elastica\Query; +use Elastica\Test\Base as BaseTest; + +class IdsTest extends BaseTest +{ + protected $_index; + protected $_type; + + public function setUp() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + + $type1 = $index->getType('helloworld1'); + $type2 = $index->getType('helloworld2'); + + // Add documents to first type + for ($i = 1; $i < 100; $i++) { + $doc = new Document($i, array('name' => 'ruflin')); + $type1->addDocument($doc); + } + + // Add documents to second type + for ($i = 1; $i < 100; $i++) { + $doc = new Document($i, array('name' => 'ruflin')); + $type2->addDocument($doc); + } + + // This is a special id that will only be in the second type + $doc = new Document('101', array('name' => 'ruflin')); + $type2->addDocument($doc); + + $index->optimize(); + $index->refresh(); + + $this->_type = $type1; + $this->_index = $index; + } + + public function tearDown() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->delete(); + } + + public function testSetIdsSearchSingle() + { + $filter = new Ids(); + $filter->setIds('1'); + + $query = Query::create($filter); + $resultSet = $this->_type->search($query); + + $this->assertEquals(1, $resultSet->count()); + } + + public function testSetIdsSearchArray() + { + $filter = new Ids(); + $filter->setIds(array(1, 7, 13)); + + $query = Query::create($filter); + $resultSet = $this->_type->search($query); + + $this->assertEquals(3, $resultSet->count()); + } + + public function testAddIdsSearchSingle() + { + $filter = new Ids(); + $filter->addId('39'); + + $query = Query::create($filter); + $resultSet = $this->_type->search($query); + + $this->assertEquals(1, $resultSet->count()); + } + + public function testAddIdsSearchSingleNotInType() + { + $filter = new Ids(); + $filter->addId('39'); + + // Add an ID that is not in the index + $filter->addId(104); + + $query = Query::create($filter); + $resultSet = $this->_type->search($query); + + $this->assertEquals(1, $resultSet->count()); + } + + public function testComboIdsSearchArray() + { + $filter = new Ids(); + $filter->setIds(array(1, 7, 13)); + $filter->addId('39'); + + $query = Query::create($filter); + $resultSet = $this->_type->search($query); + + $this->assertEquals(4, $resultSet->count()); + } + + public function testSetTypeSingleSearchSingle() + { + $filter = new Ids(); + $filter->setIds('1'); + $filter->setType('helloworld1'); + + $query = Query::create($filter); + $resultSet = $this->_index->search($query); + + $this->assertEquals(1, $resultSet->count()); + } + + public function testSetTypeSingleSearchArray() + { + $filter = new Ids(); + $filter->setIds(array('1', '2')); + $filter->setType('helloworld1'); + + $query = Query::create($filter); + $resultSet = $this->_index->search($query); + + $this->assertEquals(2, $resultSet->count()); + } + + public function testSetTypeSingleSearchSingleDocInOtherType() + { + $filter = new Ids(); + + // Doc 4 is in the second type... + $filter->setIds('101'); + $filter->setType('helloworld1'); + + $query = Query::create($filter); + $resultSet = $this->_type->search($query); + + // ...therefore 0 results should be returned + $this->assertEquals(0, $resultSet->count()); + } + + public function testSetTypeSingleSearchArrayDocInOtherType() + { + $filter = new Ids(); + + // Doc 4 is in the second type... + $filter->setIds(array('1', '101')); + $filter->setType('helloworld1'); + + $query = Query::create($filter); + $resultSet = $this->_type->search($query); + + // ...therefore only 1 result should be returned + $this->assertEquals(1, $resultSet->count()); + } + + public function testSetTypeArraySearchArray() + { + $filter = new Ids(); + $filter->setIds(array('1', '4')); + $filter->setType(array('helloworld1', 'helloworld2')); + + $query = Query::create($filter); + $resultSet = $this->_index->search($query); + + $this->assertEquals(4, $resultSet->count()); + } + + public function testSetTypeArraySearchSingle() + { + $filter = new Ids(); + $filter->setIds('4'); + $filter->setType(array('helloworld1', 'helloworld2')); + + $query = Query::create($filter); + $resultSet = $this->_index->search($query); + + $this->assertEquals(2, $resultSet->count()); + } + + public function testFilterTypeAndTypeCollision() + { + // This test ensures that Elastica\Type and Elastica\Filter\Type + // do not collide when used together, which at one point + // happened because of a use statement in Elastica\Filter\Ids + // Test goal is to make sure a Fatal Error is not triggered + $filterType = new Type(); + $filter = new Ids(); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/IndicesTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/IndicesTest.php new file mode 100644 index 00000000..b682a5ce --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/IndicesTest.php @@ -0,0 +1,93 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Document; +use Elastica\Filter\BoolNot; +use Elastica\Filter\Indices; +use Elastica\Filter\Term; +use Elastica\Index; +use Elastica\Query; +use Elastica\Test\Base as BaseTest; + +class IndicesTest extends BaseTest +{ + /** + * @var Index + */ + protected $_index1; + + /** + * @var Index + */ + protected $_index2; + + protected function setUp() + { + parent::setUp(); + $this->_index1 = $this->_createIndex('indices_filter_1'); + $this->_index2 = $this->_createIndex('indices_filter_2'); + $this->_index1->addAlias("indices_filter"); + $this->_index2->addAlias("indices_filter"); + $docs = array( + new Document("1", array("color" => "blue")), + new Document("2", array("color" => "green")), + new Document("3", array("color" => "blue")), + new Document("4", array("color" => "yellow")), + ); + $this->_index1->getType("test")->addDocuments($docs); + $this->_index2->getType("test")->addDocuments($docs); + $this->_index1->refresh(); + $this->_index2->refresh(); + } + + protected function tearDown() + { + $this->_index1->delete(); + $this->_index2->delete(); + parent::tearDown(); + } + + public function testToArray() + { + $expected = array( + "indices" => array( + "indices" => array("index1", "index2"), + "filter" => array( + "term" => array("tag" => "wow") + ), + "no_match_filter" => array( + "term" => array("tag" => "such filter") + ) + ) + ); + $filter = new Indices(new Term(array("tag" => "wow")), array("index1", "index2")); + $filter->setNoMatchFilter(new Term(array("tag" => "such filter"))); + $this->assertEquals($expected, $filter->toArray()); + } + + public function testIndicesFilter() + { + $filter = new Indices(new BoolNot(new Term(array("color" => "blue"))), array($this->_index1->getName())); + $filter->setNoMatchFilter(new BoolNot(new Term(array("color" => "yellow")))); + $query = new Query(); + $query->setFilter($filter); + + // search over the alias + $index = $this->_getClient()->getIndex("indices_filter"); + $results = $index->search($query); + + // ensure that the proper docs have been filtered out for each index + $this->assertEquals(5, $results->count()); + foreach ($results->getResults() as $result) { + $data = $result->getData(); + $color = $data["color"]; + if ($result->getIndex() == $this->_index1->getName()) { + $this->assertNotEquals("blue", $color); + } else { + $this->assertNotEquals("yellow", $color); + } + } + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/MatchAllTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/MatchAllTest.php new file mode 100644 index 00000000..6696f11d --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/MatchAllTest.php @@ -0,0 +1,18 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Filter\MatchAll; +use Elastica\Test\Base as BaseTest; + +class MatchAllTest extends BaseTest +{ + public function testToArray() + { + $filter = new MatchAll(); + + $expectedArray = array('match_all' => new \stdClass()); + + $this->assertEquals($expectedArray, $filter->toArray()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/MultiTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/MultiTest.php new file mode 100644 index 00000000..f6513338 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/MultiTest.php @@ -0,0 +1,95 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Filter\AbstractMulti; +use Elastica\Filter\MatchAll; +use Elastica\Test\Base as BaseTest; + +class AbstractMultiTest extends BaseTest +{ + public function testConstruct() + { + $stub = $this->getStub(); + + $this->assertEmpty($stub->getFilters()); + } + + public function testAddFilter() + { + $stub = $this->getStub(); + + $filter = new MatchAll(); + $stub->addFilter($filter); + + $expected = array( + $filter->toArray() + ); + + $this->assertEquals($expected, $stub->getFilters()); + } + + public function testSetFilters() + { + $stub = $this->getStub(); + + $filter = new MatchAll(); + $stub->setFilters(array($filter)); + + $expected = array( + $filter->toArray() + ); + + $this->assertEquals($expected, $stub->getFilters()); + } + + public function testToArray() + { + $stub = $this->getStub(); + + $filter = new MatchAll(); + $stub->addFilter($filter); + + $expected = array( + $stub->getBaseName() => array( + $filter->toArray() + ) + ); + + $this->assertEquals($expected, $stub->toArray()); + } + + public function testToArrayWithParam() + { + $stub = $this->getStub(); + + $stub->setCached(true); + + $filter = new MatchAll(); + $stub->addFilter($filter); + + $expected = array( + $stub->getBaseName() => array( + '_cache' => true, + 'filters' => array( + $filter->toArray() + ) + ) + ); + + $this->assertEquals($expected, $stub->toArray()); + } + + private function getStub() + { + return $this->getMockForAbstractClass('Elastica\Test\Filter\AbstractMultiDebug'); + } +} + +class AbstractMultiDebug extends AbstractMulti +{ + public function getBaseName() + { + return parent::_getBaseName(); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/NestedFilterWithSetFilterTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/NestedFilterWithSetFilterTest.php new file mode 100644 index 00000000..12dbb598 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/NestedFilterWithSetFilterTest.php @@ -0,0 +1,121 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Document; +use Elastica\Filter\Nested; +use Elastica\Filter\Terms; +use Elastica\Search; +use Elastica\Type\Mapping; +use Elastica\Test\Base as BaseTest; + +class NestedFilterWithSetFilterTest extends BaseTest +{ + public function setUp() + { + $client = $this->_getClient(); + $index = $client->getIndex('elastica_test_filter_nested_abstract_filter'); + $index->create(array(), true); + $type = $index->getType('user'); + $mapping = new Mapping(); + $mapping->setProperties( + array( + 'firstname' => array('type' => 'string', 'store' => 'yes'), + // default is store => no expected + 'lastname' => array('type' => 'string'), + 'hobbies' => array( + 'type' => 'nested', + 'include_in_parent' => true, + 'properties' => array('hobby' => array('type' => 'string')) + ) + ) + ); + $type->setMapping($mapping); + + // Adds a list of documents with _bulk upload to the index + $docs = array(); + $docs[] = new Document(1, + array( + 'firstname' => 'Nicolas', + 'lastname' => 'Ruflin', + 'hobbies' => array( + array('hobby' => 'opensource') + ) + ) + ); + $docs[] = new Document(2, + array( + 'firstname' => 'Nicolas', + 'lastname' => 'Ippolito', + 'hobbies' => array( + array('hobby' => 'opensource'), + array('hobby' => 'guitar'), + ) + ) + ); + $response = $type->addDocuments($docs); + + // Refresh index + $index->refresh(); + } + + public function tearDown() + { + $client = $this->_getClient(); + $index = $client->getIndex('elastica_test_filter_nested_abstract_filter'); + $index->delete(); + } + + public function testToArray() + { + $f = new Nested(); + $this->assertEquals(array('nested' => array()), $f->toArray()); + $q = new Terms(); + $q->setTerms('hobby', array('guitar')); + $f->setPath('hobbies'); + $f->setFilter($q); + + $expectedArray = array( + 'nested' => array( + 'path' => 'hobbies', + 'filter' => array('terms' => array( + 'hobby' => array('guitar') + )) + ) + ); + + $this->assertEquals($expectedArray, $f->toArray()); + } + + public function testShouldReturnTheRightNumberOfResult() + { + $f = new Nested(); + $this->assertEquals(array('nested' => array()), $f->toArray()); + $q = new Terms(); + $q->setTerms('hobby', array('guitar')); + $f->setPath('hobbies'); + $f->setFilter($q); + + $c = $this->_getClient(); + $s = new Search($c); + $i = $c->getIndex('elastica_test_filter_nested_abstract_filter'); + $s->addIndex($i); + $r = $s->search($f); + + $this->assertEquals(1, $r->getTotalHits()); + + $f = new Nested(); + $this->assertEquals(array('nested' => array()), $f->toArray()); + $q = new Terms(); + $q->setTerms('hobby', array('opensource')); + $f->setPath('hobbies'); + $f->setFilter($q); + + $c = $this->_getClient(); + $s = new Search($c); + $i = $c->getIndex('elastica_test_filter_nested_abstract_filter'); + $s->addIndex($i); + $r = $s->search($f); + $this->assertEquals(2, $r->getTotalHits()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/NestedTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/NestedTest.php new file mode 100644 index 00000000..8d0d2004 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/NestedTest.php @@ -0,0 +1,121 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Document; +use Elastica\Filter\Nested; +use Elastica\Query\Terms; +use Elastica\Search; +use Elastica\Type\Mapping; +use Elastica\Test\Base as BaseTest; + +class NestedTest extends BaseTest +{ + public function setUp() + { + $client = $this->_getClient(); + $index = $client->getIndex('elastica_test_filter_nested'); + $index->create(array(), true); + $type = $index->getType('user'); + $mapping = new Mapping(); + $mapping->setProperties( + array( + 'firstname' => array('type' => 'string', 'store' => 'yes'), + // default is store => no expected + 'lastname' => array('type' => 'string'), + 'hobbies' => array( + 'type' => 'nested', + 'include_in_parent' => true, + 'properties' => array('hobby' => array('type' => 'string')) + ) + ) + ); + $type->setMapping($mapping); + + // Adds a list of documents with _bulk upload to the index + $docs = array(); + $docs[] = new Document(1, + array( + 'firstname' => 'Nicolas', + 'lastname' => 'Ruflin', + 'hobbies' => array( + array('hobby' => 'opensource') + ) + ) + ); + $docs[] = new Document(2, + array( + 'firstname' => 'Nicolas', + 'lastname' => 'Ippolito', + 'hobbies' => array( + array('hobby' => 'opensource'), + array('hobby' => 'guitar'), + ) + ) + ); + $response = $type->addDocuments($docs); + + // Refresh index + $index->refresh(); + } + + public function tearDown() + { + $client = $this->_getClient(); + $index = $client->getIndex('elastica_test_filter_nested'); + $index->delete(); + } + + public function testToArray() + { + $f = new Nested(); + $this->assertEquals(array('nested' => array()), $f->toArray()); + $q = new Terms(); + $q->setTerms('hobby', array('guitar')); + $f->setPath('hobbies'); + $f->setQuery($q); + + $expectedArray = array( + 'nested' => array( + 'path' => 'hobbies', + 'query' => array('terms' => array( + 'hobby' => array('guitar') + )) + ) + ); + + $this->assertEquals($expectedArray, $f->toArray()); + } + + public function testShouldReturnTheRightNumberOfResult() + { + $f = new Nested(); + $this->assertEquals(array('nested' => array()), $f->toArray()); + $q = new Terms(); + $q->setTerms('hobby', array('guitar')); + $f->setPath('hobbies'); + $f->setQuery($q); + + $c = $this->_getClient(); + $s = new Search($c); + $i = $c->getIndex('elastica_test_filter_nested'); + $s->addIndex($i); + $r = $s->search($f); + + $this->assertEquals(1, $r->getTotalHits()); + + $f = new Nested(); + $this->assertEquals(array('nested' => array()), $f->toArray()); + $q = new Terms(); + $q->setTerms('hobby', array('opensource')); + $f->setPath('hobbies'); + $f->setQuery($q); + + $c = $this->_getClient(); + $s = new Search($c); + $i = $c->getIndex('elastica_test_filter_nested'); + $s->addIndex($i); + $r = $s->search($f); + $this->assertEquals(2, $r->getTotalHits()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/NumericRangeTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/NumericRangeTest.php new file mode 100644 index 00000000..6cc2de06 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/NumericRangeTest.php @@ -0,0 +1,32 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Filter\NumericRange; +use Elastica\Test\Base as BaseTest; + +class NumericRangeTest extends BaseTest +{ + public function testAddField() + { + $rangeFilter = new NumericRange(); + $returnValue = $rangeFilter->addField('fieldName', array('to' => 'value')); + $this->assertInstanceOf('Elastica\Filter\NumericRange', $returnValue); + } + + public function testToArray() + { + $filter = new NumericRange(); + + $fromTo = array('from' => 'ra', 'to' => 'ru'); + $filter->addField('name', $fromTo); + + $expectedArray = array( + 'numeric_range' => array( + 'name' => $fromTo + ) + ); + + $this->assertEquals($expectedArray, $filter->toArray()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/PrefixTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/PrefixTest.php new file mode 100644 index 00000000..16362140 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/PrefixTest.php @@ -0,0 +1,149 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Document; +use Elastica\Filter\Prefix; +use Elastica\Type\Mapping; +use Elastica\Test\Base as BaseTest; + +class PrefixTest extends BaseTest +{ + public function testToArray() + { + $field = 'name'; + $prefix = 'ruf'; + + $filter = new Prefix($field, $prefix); + + $expectedArray = array( + 'prefix' => array( + $field => $prefix + ) + ); + + $this->assertequals($expectedArray, $filter->toArray()); + } + + public function testDifferentPrefixes() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + + /*$indexParams = array( + 'analysis' => array( + 'analyzer' => array( + 'lw' => array( + 'type' => 'custom', + 'tokenizer' => 'keyword', + 'filter' => array('lowercase') + ) + ), + ) + );*/ + + $index->create(array(), true); + $type = $index->getType('test'); + + $mapping = new Mapping($type, array( + 'name' => array('type' => 'string', 'store' => 'no', 'index' => 'not_analyzed'), + ) + ); + $type->setMapping($mapping); + + $doc = new Document(1, array('name' => 'Basel-Stadt')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'New York')); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'Baden')); + $type->addDocument($doc); + $doc = new Document(4, array('name' => 'Baden Baden')); + $type->addDocument($doc); + $doc = new Document(5, array('name' => 'New Orleans')); + $type->addDocument($doc); + + $index->refresh(); + + $query = new Prefix('name', 'Ba'); + $resultSet = $index->search($query); + $this->assertEquals(3, $resultSet->count()); + + // Lower case should not return a result + $query = new Prefix('name', 'ba'); + $resultSet = $index->search($query); + $this->assertEquals(0, $resultSet->count()); + + $query = new Prefix('name', 'Baden'); + $resultSet = $index->search($query); + $this->assertEquals(2, $resultSet->count()); + + $query = new Prefix('name', 'Baden B'); + $resultSet = $index->search($query); + $this->assertEquals(1, $resultSet->count()); + + $query = new Prefix('name', 'Baden Bas'); + $resultSet = $index->search($query); + $this->assertEquals(0, $resultSet->count()); + } + + public function testDifferentPrefixesLowercase() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + + $indexParams = array( + 'analysis' => array( + 'analyzer' => array( + 'lw' => array( + 'type' => 'custom', + 'tokenizer' => 'keyword', + 'filter' => array('lowercase') + ) + ), + ) + ); + + $index->create($indexParams, true); + $type = $index->getType('test'); + + $mapping = new Mapping($type, array( + 'name' => array('type' => 'string', 'store' => 'no', 'analyzer' => 'lw'), + ) + ); + $type->setMapping($mapping); + + $doc = new Document(1, array('name' => 'Basel-Stadt')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'New York')); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'Baden')); + $type->addDocument($doc); + $doc = new Document(4, array('name' => 'Baden Baden')); + $type->addDocument($doc); + $doc = new Document(5, array('name' => 'New Orleans')); + $type->addDocument($doc); + + $index->refresh(); + + $query = new Prefix('name', 'ba'); + $resultSet = $index->search($query); + $this->assertEquals(3, $resultSet->count()); + + // Upper case should not return a result + $query = new Prefix('name', 'Ba'); + $resultSet = $index->search($query); + $this->assertEquals(0, $resultSet->count()); + + $query = new Prefix('name', 'baden'); + $resultSet = $index->search($query); + $this->assertEquals(2, $resultSet->count()); + + $query = new Prefix('name', 'baden b'); + $resultSet = $index->search($query); + $this->assertEquals(1, $resultSet->count()); + + $query = new Prefix('name', 'baden bas'); + $resultSet = $index->search($query); + $this->assertEquals(0, $resultSet->count()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/QueryTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/QueryTest.php new file mode 100644 index 00000000..0a331098 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/QueryTest.php @@ -0,0 +1,46 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Query\QueryString; +use Elastica\Filter\Query; +use Elastica\Test\Base as BaseTest; + +class QueryTest extends BaseTest +{ + public function testSimple() + { + $query = new QueryString('foo bar'); + $filter = new Query($query); + + $expected = array( + 'query' => array( + 'query_string' => array( + 'query' => 'foo bar', + ) + ) + ); + + $this->assertEquals($expected, $filter->toArray()); + } + + public function testExtended() + { + $query = new QueryString('foo bar'); + $filter = new Query($query); + $filter->setCached(true); + + $expected = array( + 'fquery' => array( + 'query' => array( + 'query_string' => array( + 'query' => 'foo bar', + ), + ), + '_cache' => true + ) + ); + + $this->assertEquals($expected, $filter->toArray()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/RangeTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/RangeTest.php new file mode 100644 index 00000000..bf2cb260 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/RangeTest.php @@ -0,0 +1,32 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Filter\Range; +use Elastica\Test\Base as BaseTest; + +class RangeTest extends BaseTest +{ + public function testAddField() + { + $rangeFilter = new Range(); + $returnValue = $rangeFilter->addField('fieldName', array('to' => 'value')); + $this->assertInstanceOf('Elastica\Filter\Range', $returnValue); + } + + public function testToArray() + { + $filter = new Range(); + + $fromTo = array('from' => 'ra', 'to' => 'ru'); + $filter->addField('name', $fromTo); + + $expectedArray = array( + 'range' => array( + 'name' => $fromTo + ) + ); + + $this->assertEquals($expectedArray, $filter->toArray()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/RegexpTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/RegexpTest.php new file mode 100644 index 00000000..e06064dd --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/RegexpTest.php @@ -0,0 +1,137 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Document; +use Elastica\Filter\Regexp; +use Elastica\Type\Mapping; +use Elastica\Test\Base as BaseTest; + +class RegexpTest extends BaseTest +{ + public function testToArray() + { + $field = 'name'; + $regexp = 'ruf'; + + $filter = new Regexp($field, $regexp); + + $expectedArray = array( + 'regexp' => array( + $field => $regexp + ) + ); + + $this->assertequals($expectedArray, $filter->toArray()); + } + + public function testDifferentRegexp() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + + $index->create(array(), true); + $type = $index->getType('test'); + + $mapping = new Mapping($type, array( + 'name' => array('type' => 'string', 'store' => 'no', 'index' => 'not_analyzed'), + ) + ); + $type->setMapping($mapping); + + $doc = new Document(1, array('name' => 'Basel-Stadt')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'New York')); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'Baden')); + $type->addDocument($doc); + $doc = new Document(4, array('name' => 'Baden Baden')); + $type->addDocument($doc); + $doc = new Document(5, array('name' => 'New Orleans')); + $type->addDocument($doc); + + $index->refresh(); + + $query = new Regexp('name', 'Ba.*'); + $resultSet = $index->search($query); + $this->assertEquals(3, $resultSet->count()); + + // Lower case should not return a result + $query = new Regexp('name', 'ba.*'); + $resultSet = $index->search($query); + $this->assertEquals(0, $resultSet->count()); + + $query = new Regexp('name', 'Baden.*'); + $resultSet = $index->search($query); + $this->assertEquals(2, $resultSet->count()); + + $query = new Regexp('name', 'Baden B.*'); + $resultSet = $index->search($query); + $this->assertEquals(1, $resultSet->count()); + + $query = new Regexp('name', 'Baden Bas.*'); + $resultSet = $index->search($query); + $this->assertEquals(0, $resultSet->count()); + } + + public function testDifferentRegexpLowercase() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + + $indexParams = array( + 'analysis' => array( + 'analyzer' => array( + 'lw' => array( + 'type' => 'custom', + 'tokenizer' => 'keyword', + 'filter' => array('lowercase') + ) + ), + ) + ); + + $index->create($indexParams, true); + $type = $index->getType('test'); + + $mapping = new Mapping($type, array( + 'name' => array('type' => 'string', 'store' => 'no', 'analyzer' => 'lw'), + ) + ); + $type->setMapping($mapping); + + $doc = new Document(1, array('name' => 'Basel-Stadt')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'New York')); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'Baden')); + $type->addDocument($doc); + $doc = new Document(4, array('name' => 'Baden Baden')); + $type->addDocument($doc); + $doc = new Document(5, array('name' => 'New Orleans')); + $type->addDocument($doc); + + $index->refresh(); + + $query = new Regexp('name', 'ba.*'); + $resultSet = $index->search($query); + $this->assertEquals(3, $resultSet->count()); + + // Upper case should not return a result + $query = new Regexp('name', 'Ba.*'); + $resultSet = $index->search($query); + $this->assertEquals(0, $resultSet->count()); + + $query = new Regexp('name', 'baden.*'); + $resultSet = $index->search($query); + $this->assertEquals(2, $resultSet->count()); + + $query = new Regexp('name', 'baden b.*'); + $resultSet = $index->search($query); + $this->assertEquals(1, $resultSet->count()); + + $query = new Regexp('name', 'baden bas.*'); + $resultSet = $index->search($query); + $this->assertEquals(0, $resultSet->count()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/ScriptTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/ScriptTest.php new file mode 100644 index 00000000..65ea628e --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/ScriptTest.php @@ -0,0 +1,52 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Script; +use Elastica\Filter\Script as ScriptFilter; +use Elastica\Test\Base as BaseTest; + +class ScriptTest extends BaseTest +{ + public function testToArray() + { + $string = '_score * 2.0'; + + $filter = new ScriptFilter($string); + + $array = $filter->toArray(); + $this->assertInternalType('array', $array); + + $expected = array( + 'script' => array( + 'script' => $string, + ) + ); + $this->assertEquals($expected, $array); + } + + public function testSetScript() + { + $string = '_score * 2.0'; + $params = array( + 'param1' => 'one', + 'param2' => 1, + ); + $lang = 'mvel'; + $script = new Script($string, $params, $lang); + + $filter = new ScriptFilter(); + $filter->setScript($script); + + $array = $filter->toArray(); + + $expected = array( + 'script' => array( + 'script' => $string, + 'params' => $params, + 'lang' => $lang, + ) + ); + $this->assertEquals($expected, $array); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/TermTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/TermTest.php new file mode 100644 index 00000000..9a116851 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/TermTest.php @@ -0,0 +1,23 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Filter\Term; +use Elastica\Test\Base as BaseTest; + +class TermTest extends BaseTest +{ + + public function testToArray() + { + $query = new Term(); + $key = 'name'; + $value = 'ruflin'; + $query->setTerm($key, $value); + + $data = $query->toArray(); + + $this->assertInternalType('array', $data['term']); + $this->assertEquals(array($key => $value), $data['term']); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/TermsTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/TermsTest.php new file mode 100644 index 00000000..96994730 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/TermsTest.php @@ -0,0 +1,54 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Filter\Terms; +use Elastica\Test\Base as BaseTest; + +class TermsTest extends BaseTest +{ + + public function testLookup() + { + $index = $this->_createIndex('terms_filter_test'); + $type1 = $index->getType('musicians'); + $type2 = $index->getType('bands'); + + //index some test data + $type1->addDocument(new \Elastica\Document(1, array('name' => 'robert', 'lastName' => 'plant'))); + $type1->addDocument(new \Elastica\Document(2, array('name' => 'jimmy', 'lastName' => 'page'))); + $type1->addDocument(new \Elastica\Document(3, array('name' => 'john paul', 'lastName' => 'jones'))); + $type1->addDocument(new \Elastica\Document(4, array('name' => 'john', 'lastName' => 'bonham'))); + $type1->addDocument(new \Elastica\Document(5, array('name' => 'jimi', 'lastName' => 'hendrix'))); + + $type2->addDocument(new \Elastica\Document('led zeppelin', array('members' => array('plant', 'page', 'jones', 'bonham')))); + $index->refresh(); + + //use the terms lookup feature to query for some data + $termsFilter = new Terms(); + $termsFilter->setLookup('lastName', $type2, 'led zeppelin', 'members', NULL); + $query = new \Elastica\Query(); + $query->setFilter($termsFilter); + $results = $index->search($query); + $this->assertEquals($results->count(), 4, 'Terms lookup with null index'); + + $termsFilter->setLookup('lastName', $type2, 'led zeppelin', 'members', $index); + $query->setFilter($termsFilter); + $results = $index->search($query); + $this->assertEquals($results->count(), 4, 'Terms lookup with index as object'); + + //Query with index given as string + $termsFilter->setLookup('lastName', $type2, 'led zeppelin', 'members', $index->getName()); + $query->setFilter($termsFilter); + $results = $index->search($query); + $this->assertEquals($results->count(), 4, 'Terms lookup with index as string'); + + //Query with array of options + $termsFilter->setLookup('lastName', $type2, 'led zeppelin', 'members', array('index' => $index, 'cache' => false)); + $query->setFilter($termsFilter); + $results = $index->search($query); + $this->assertEquals($results->count(), 4, 'Terms lookup with options array'); + + $index->delete(); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/TypeTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/TypeTest.php new file mode 100644 index 00000000..fcada826 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Filter/TypeTest.php @@ -0,0 +1,27 @@ +<?php + +namespace Elastica\Test\Filter; + +use Elastica\Filter\Type; +use Elastica\Test\Base as BaseTest; + +class TypeTest extends BaseTest +{ + public function testSetType() + { + $typeFilter = new Type(); + $returnValue = $typeFilter->setType('type_name'); + $this->assertInstanceOf('Elastica\Filter\Type', $returnValue); + } + + public function testToArray() + { + $typeFilter = new Type('type_name'); + + $expectedArray = array( + 'type' => array('value' => 'type_name') + ); + + $this->assertEquals($expectedArray, $typeFilter->toArray()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Index/SettingsTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Index/SettingsTest.php new file mode 100644 index 00000000..4f74d22b --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Index/SettingsTest.php @@ -0,0 +1,300 @@ +<?php + +namespace Elastica\Test\Index; + +use Elastica\Document; +use Elastica\Exception\ResponseException; +use Elastica\Index; +use Elastica\Index\Settings as IndexSettings; +use Elastica\Test\Base as BaseTest; + +class SettingsTest extends BaseTest +{ + public function testGet() + { + $indexName = 'elasticatest'; + + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + $index->create(array(), true); + $index->refresh(); + $settings = $index->getSettings(); + + $this->assertInternalType('array', $settings->get()); + $this->assertNotNull($settings->get('number_of_replicas')); + $this->assertNotNull($settings->get('number_of_shards')); + $this->assertNull($settings->get('kjqwerjlqwer')); + + $index->delete(); + } + + public function testGetWithAlias() + { + $indexName = 'elasticatest'; + $aliasName = 'elasticatest_alias'; + + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + $index->create(array(), true); + $index->refresh(); + + $index->addAlias($aliasName); + $index = $client->getIndex($aliasName); + $settings = $index->getSettings(); + + $this->assertInternalType('array', $settings->get()); + $this->assertNotNull($settings->get('number_of_replicas')); + $this->assertNotNull($settings->get('number_of_shards')); + $this->assertNull($settings->get('kjqwerjlqwer')); + + $index->delete(); + } + + public function testSetNumberOfReplicas() + { + $indexName = 'test'; + + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + $index->create(array(), true); + $settings = $index->getSettings(); + + $settings->setNumberOfReplicas(2); + $index->refresh(); + $this->assertEquals(2, $settings->get('number_of_replicas')); + + $settings->setNumberOfReplicas(3); + $index->refresh(); + $this->assertEquals(3, $settings->get('number_of_replicas')); + + $index->delete(); + } + + public function testSetRefreshInterval() + { + $indexName = 'test'; + + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + $index->create(array(), true); + + $settings = $index->getSettings(); + + $settings->setRefreshInterval('2s'); + $index->refresh(); + $this->assertEquals('2s', $settings->get('refresh_interval')); + + $settings->setRefreshInterval('5s'); + $index->refresh(); + $this->assertEquals('5s', $settings->get('refresh_interval')); + + $index->delete(); + } + + public function testGetRefreshInterval() + { + $indexName = 'test'; + + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + $index->create(array(), true); + + $settings = $index->getSettings(); + + $this->assertEquals(IndexSettings::DEFAULT_REFRESH_INTERVAL, $settings->getRefreshInterval()); + + $interval = '2s'; + $settings->setRefreshInterval($interval); + $index->refresh(); + $this->assertEquals($interval, $settings->getRefreshInterval()); + $this->assertEquals($interval, $settings->get('refresh_interval')); + + $index->delete(); + } + + public function testSetMergePolicy() + { + $indexName = 'test'; + + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + $index->create(array(), true); + //wait for the shards to be allocated + $this->_waitForAllocation($index); + + $settings = $index->getSettings(); + + $settings->setMergePolicy('expunge_deletes_allowed', 15); + $this->assertEquals(15, $settings->getMergePolicy('expunge_deletes_allowed')); + + $settings->setMergePolicy('expunge_deletes_allowed', 10); + $this->assertEquals(10, $settings->getMergePolicy('expunge_deletes_allowed')); + + $index->delete(); + } + + public function testSetMergeFactor() + { + $indexName = 'test'; + + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + $index->create(array(), true); + + //wait for the shards to be allocated + $this->_waitForAllocation($index); + + $settings = $index->getSettings(); + + $response = $settings->setMergePolicy('merge_factor', 15); + $this->assertEquals(15, $settings->getMergePolicy('merge_factor')); + $this->assertInstanceOf('Elastica\Response', $response); + $this->assertTrue($response->isOk()); + + $settings->setMergePolicy('merge_factor', 10); + $this->assertEquals(10, $settings->getMergePolicy('merge_factor')); + + $index->delete(); + } + + public function testSetMergePolicyType() + { + $indexName = 'test'; + + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + $index->create(array(), true); + + //wait for the shards to be allocated + $this->_waitForAllocation($index); + + $settings = $index->getSettings(); + + $settings->setMergePolicyType('log_byte_size'); + $this->assertEquals('log_byte_size', $settings->getMergePolicyType()); + + $response = $settings->setMergePolicy('merge_factor', 15); + $this->assertEquals(15, $settings->getMergePolicy('merge_factor')); + $this->assertInstanceOf('Elastica\Response', $response); + $this->assertTrue($response->isOk()); + + $index->delete(); + } + + public function testSetReadOnly() + { + $index = $this->_createIndex('test'); + //wait for the shards to be allocated + $this->_waitForAllocation($index); + $index->getSettings()->setReadOnly(false); + + + // Add document to normal index + $doc1 = new Document(null, array('hello' => 'world')); + $doc2 = new Document(null, array('hello' => 'world')); + $doc3 = new Document(null, array('hello' => 'world')); + + $type = $index->getType('test'); + $type->addDocument($doc1); + $this->assertEquals('false', $index->getSettings()->get('blocks.read_only')); //ES returns a string for this setting + + // Try to add doc to read only index + $index->getSettings()->setReadOnly(true); + $this->assertEquals('true', $index->getSettings()->get('blocks.read_only')); + + try { + $type->addDocument($doc2); + $this->fail('Should throw exception because of read only'); + } catch (ResponseException $e) { + $message = $e->getMessage(); + $this->assertContains('ClusterBlockException', $message); + $this->assertContains('index read-only', $message); + } + + // Remove read only, add document + $response = $index->getSettings()->setReadOnly(false); + $this->assertTrue($response->isOk()); + + $type->addDocument($doc3); + $index->refresh(); + + $this->assertEquals(2, $type->count()); + + $index->delete(); + } + + + public function testGetSetBlocksRead() + { + $index = $this->_createIndex('elastica-test'); + $index->refresh(); + $settings = $index->getSettings(); + + $this->assertFalse($settings->getBlocksRead()); + + $settings->setBlocksRead(true); + $this->assertTrue($settings->getBlocksRead()); + + $settings->setBlocksRead(false); + $this->assertFalse($settings->getBlocksRead()); + + $settings->setBlocksRead(); + $this->assertTrue($settings->getBlocksRead()); + + $index->delete(); + } + + public function testGetSetBlocksWrite() + { + $index = $this->_createIndex('elastica-test'); + $index->refresh(); + $settings = $index->getSettings(); + + $this->assertFalse($settings->getBlocksWrite()); + + $settings->setBlocksWrite(true); + $this->assertTrue($settings->getBlocksWrite()); + + $settings->setBlocksWrite(false); + $this->assertFalse($settings->getBlocksWrite()); + + $settings->setBlocksWrite(); + $this->assertTrue($settings->getBlocksWrite()); + + $index->delete(); + } + + public function testGetSetBlocksMetadata() + { + $index = $this->_createIndex('elastica-test'); + $index->refresh(); + $settings = $index->getSettings(); + + $this->assertFalse($settings->getBlocksMetadata()); + + $settings->setBlocksMetadata(true); + $this->assertTrue($settings->getBlocksMetadata()); + + $settings->setBlocksMetadata(false); + $this->assertFalse($settings->getBlocksMetadata()); + + $settings->setBlocksMetadata(); + $this->assertTrue($settings->getBlocksMetadata()); + + $settings->setBlocksMetadata(false); // Cannot delete index otherwise + $index->delete(); + } + + protected function _waitForAllocation(Index $index) + { + do { + $settings = $index->getStatus()->get(); + $allocated = true; + foreach ($settings['shards'] as $shard) { + if ($shard[0]['routing']['state'] != 'STARTED') { + $allocated = false; + } + } + } while (!$allocated); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Index/StatsTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Index/StatsTest.php new file mode 100644 index 00000000..5e8e8d57 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Index/StatsTest.php @@ -0,0 +1,23 @@ +<?php + +namespace Elastica\Test\Index; + +use Elastica\Test\Base as BaseTest; + +class StatsTest extends BaseTest +{ + + public function testGetSettings() + { + $indexName = 'test'; + + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + $index->create(array(), true); + $stats = $index->getStats(); + $this->assertInstanceOf('Elastica\Index\Stats', $stats); + + $this->assertTrue($stats->getResponse()->isOk()); + $this->assertEquals(0, $stats->get('_all', 'indices', 'test', 'primaries', 'docs', 'count')); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Index/StatusTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Index/StatusTest.php new file mode 100644 index 00000000..8a056a53 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Index/StatusTest.php @@ -0,0 +1,66 @@ +<?php + +namespace Elastica\Test\Index; + +use Elastica\Index\Status as IndexStatus; +use Elastica\Test\Base as BaseTest; + +class StatusTest extends BaseTest +{ + public function testGetAliases() + { + $indexName = 'test'; + $aliasName = 'test-alias'; + + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + $index->create(array(), true); + + $status = new IndexStatus($index); + + $aliases = $status->getAliases(); + + $this->assertTrue(empty($aliases)); + $this->assertInternalType('array', $aliases); + + $index->addAlias($aliasName); + $status->refresh(); + + $aliases = $status->getAliases(); + + $this->assertTrue(in_array($aliasName, $aliases)); + } + + public function testHasAlias() + { + $indexName = 'test'; + $aliasName = 'test-alias'; + + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + $index->create(array(), true); + + $status = new IndexStatus($index); + + $this->assertFalse($status->hasAlias($aliasName)); + + $index->addAlias($aliasName); + $status->refresh(); + + $this->assertTrue($status->hasAlias($aliasName)); + } + + public function testGetSettings() + { + $indexName = 'test'; + + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + $index->create(array(), true); + $status = $index->getStatus(); + + $settings = $status->getSettings(); + $this->assertInternalType('array', $settings); + $this->assertTrue(isset($settings['index']['number_of_shards'])); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/IndexTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/IndexTest.php new file mode 100644 index 00000000..8e4ac306 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/IndexTest.php @@ -0,0 +1,696 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Client; +use Elastica\Document; +use Elastica\Exception\ResponseException; +use Elastica\Index; +use Elastica\Query\QueryString; +use Elastica\Query\Term; +use Elastica\Status; +use Elastica\Type; +use Elastica\Type\Mapping; +use Elastica\Query\HasChild; +use Elastica\Test\Base as BaseTest; + +class IndexTest extends BaseTest +{ + public function testMapping() + { + $index = $this->_createIndex(); + $doc = new Document(1, array('id' => 1, 'email' => 'test@test.com', 'username' => 'hanswurst', 'test' => array('2', '3', '5'))); + + $type = $index->getType('test'); + + $mapping = array('id' => array('type' => 'integer', 'store' => true), 'email' => array('type' => 'string', 'store' => 'no'), + 'username' => array('type' => 'string', 'store' => 'no'), 'test' => array('type' => 'integer', 'store' => 'no'),); + $type->setMapping($mapping); + + $type->addDocument($doc); + $index->optimize(); + + $storedMapping = $index->getMapping(); + + $this->assertEquals($storedMapping['test']['properties']['id']['type'], 'integer'); + $this->assertEquals($storedMapping['test']['properties']['id']['store'], true); + $this->assertEquals($storedMapping['test']['properties']['email']['type'], 'string'); + $this->assertEquals($storedMapping['test']['properties']['username']['type'], 'string'); + $this->assertEquals($storedMapping['test']['properties']['test']['type'], 'integer'); + + $result = $type->search('hanswurst'); + } + + public function testGetMappingAlias() { + + $indexName = 'test-mapping'; + $aliasName = 'test-mapping-alias'; + + $index = $this->_createIndex($indexName); + $indexName = $index->getName(); + $index->addAlias($aliasName); + + $type = new Type($index, 'test'); + $mapping = new Mapping($type, array( + 'id' => array('type' => 'integer', 'store' => 'yes'), + )); + $type->setMapping($mapping); + + $client = $index->getClient(); + + // Index mapping + $mapping1 = $client->getIndex($indexName)->getMapping(); + + // Alias mapping + $mapping2 = $client->getIndex($aliasName)->getMapping(); + + // Make sure, a mapping is set + $this->assertNotEmpty($mapping1); + + // Alias and index mapping should be identical + $this->assertEquals($mapping1, $mapping2); + } + + public function testParent() + { + $index = $this->_createIndex(); + + $typeBlog = new Type($index, 'blog'); + + $typeComment = new Type($index, 'comment'); + + $mapping = new Mapping(); + $mapping->setParam('_parent', array('type' => 'blog')); + $typeComment->setMapping($mapping); + + $entry1 = new Document(1); + $entry1->set('title', 'Hello world'); + $typeBlog->addDocument($entry1); + + $entry2 = new Document(2); + $entry2->set('title', 'Foo bar'); + $typeBlog->addDocument($entry2); + + $entry3 = new Document(3); + $entry3->set('title', 'Till dawn'); + $typeBlog->addDocument($entry3); + + $comment = new Document(1); + $comment->set('author', 'Max'); + $comment->setParent(2); // Entry Foo bar + $typeComment->addDocument($comment); + + $index->optimize(); + + $query = new HasChild('Max', 'comment'); + $resultSet = $typeBlog->search($query); + $this->assertEquals(1, $resultSet->count()); + $this->assertEquals(array('title' => 'Foo bar'), $resultSet->current()->getData()); + } + + public function testAddPdfFile() + { + $this->_checkAttachmentsPlugin(); + $indexMapping = array('file' => array('type' => 'attachment', 'store' => 'no'), 'text' => array('type' => 'string', 'store' => 'no'),); + + $indexParams = array('index' => array('number_of_shards' => 1, 'number_of_replicas' => 0),); + + $index = $this->_createIndex(); + $type = new Type($index, 'test'); + + $index->create($indexParams, true); + $type->setMapping($indexMapping); + + $doc1 = new Document(1); + $doc1->addFile('file', BASE_PATH . '/data/test.pdf', 'application/pdf'); + $doc1->set('text', 'basel world'); + $type->addDocument($doc1); + + $doc2 = new Document(2); + $doc2->set('text', 'running in basel'); + $type->addDocument($doc2); + + $index->optimize(); + + $resultSet = $type->search('xodoa'); + $this->assertEquals(1, $resultSet->count()); + + $resultSet = $type->search('basel'); + $this->assertEquals(2, $resultSet->count()); + + // Author is ruflin + $resultSet = $type->search('ruflin'); + $this->assertEquals(1, $resultSet->count()); + + // String does not exist in file + $resultSet = $type->search('guschti'); + $this->assertEquals(0, $resultSet->count()); + } + + public function testAddPdfFileContent() + { + $this->_checkAttachmentsPlugin(); + $indexMapping = array('file' => array('type' => 'attachment', 'store' => 'no'), 'text' => array('type' => 'string', 'store' => 'no'),); + + $indexParams = array('index' => array('number_of_shards' => 1, 'number_of_replicas' => 0),); + + $index = $this->_createIndex(); + $type = new Type($index, 'test'); + + $index->create($indexParams, true); + $type->setMapping($indexMapping); + + $doc1 = new Document(1); + $doc1->addFileContent('file', file_get_contents(BASE_PATH . '/data/test.pdf')); + $doc1->set('text', 'basel world'); + $type->addDocument($doc1); + + $doc2 = new Document(2); + $doc2->set('text', 'running in basel'); + $type->addDocument($doc2); + + $index->optimize(); + + $resultSet = $type->search('xodoa'); + $this->assertEquals(1, $resultSet->count()); + + $resultSet = $type->search('basel'); + $this->assertEquals(2, $resultSet->count()); + + // Author is ruflin + $resultSet = $type->search('ruflin'); + $this->assertEquals(1, $resultSet->count()); + + // String does not exist in file + $resultSet = $type->search('guschti'); + $this->assertEquals(0, $resultSet->count()); + } + + public function testAddWordxFile() + { + $this->_checkAttachmentsPlugin(); + $indexMapping = array('file' => array('type' => 'attachment'), 'text' => array('type' => 'string', 'store' => 'no'),); + + $indexParams = array('index' => array('number_of_shards' => 1, 'number_of_replicas' => 0),); + + $index = $this->_createIndex(); + $type = new Type($index, 'content'); + + $index->create($indexParams, true); + $type->setMapping($indexMapping); + + $doc1 = new Document(1); + $doc1->addFile('file', BASE_PATH . '/data/test.docx'); + $doc1->set('text', 'basel world'); + $type->addDocument($doc1); + + $doc2 = new Document(2); + $doc2->set('text', 'running in basel'); + $type->addDocument($doc2); + + $index->optimize(); + + $resultSet = $type->search('xodoa'); + $this->assertEquals(1, $resultSet->count()); + + $resultSet = $type->search('basel'); + $this->assertEquals(2, $resultSet->count()); + + $resultSet = $type->search('ruflin'); + $this->assertEquals(0, $resultSet->count()); + } + + public function testExcludeFileSource() + { + $this->_checkAttachmentsPlugin(); + $indexMapping = array('file' => array('type' => 'attachment', 'store' => 'yes'), 'text' => array('type' => 'string', 'store' => 'yes'), + 'title' => array('type' => 'string', 'store' => 'yes'),); + + $indexParams = array('index' => array('number_of_shards' => 1, 'number_of_replicas' => 0),); + + $index = $this->_createIndex(); + $type = new Type($index, 'content'); + + $mapping = Mapping::create($indexMapping); + $mapping->setSource(array('excludes' => array('file'))); + + $mapping->setType($type); + + $index->create($indexParams, true); + $type->setMapping($mapping); + + $docId = 1; + $text = 'Basel World'; + $title = 'No Title'; + + $doc1 = new Document($docId); + $doc1->addFile('file', BASE_PATH . '/data/test.docx'); + $doc1->set('text', $text); + $doc1->set('title', $title); + $type->addDocument($doc1); + + // Optimization necessary, as otherwise source still in realtime get + $index->optimize(); + + $data = $type->getDocument($docId)->getData(); + $this->assertEquals($data['title'], $title); + $this->assertEquals($data['text'], $text); + $this->assertFalse(isset($data['file'])); + } + + /** + * @expectedException \Elastica\Exception\ResponseException + */ + public function testAddRemoveAlias() + { + $client = $this->_getClient(); + + $indexName1 = 'test1'; + $aliasName = 'test-alias'; + $typeName = 'test'; + + $index = $client->getIndex($indexName1); + $index->create(array('index' => array('number_of_shards' => 1, 'number_of_replicas' => 0)), true); + + $doc = new Document(1, array('id' => 1, 'email' => 'test@test.com', 'username' => 'ruflin')); + + $type = $index->getType($typeName); + $type->addDocument($doc); + $index->refresh(); + + $resultSet = $type->search('ruflin'); + + $this->assertEquals(1, $resultSet->count()); + + $data = $index->addAlias($aliasName, true)->getData(); + $this->assertTrue($data['acknowledged']); + + $index2 = $client->getIndex($aliasName); + $type2 = $index2->getType($typeName); + + $resultSet2 = $type2->search('ruflin'); + $this->assertEquals(1, $resultSet2->count()); + + $response = $index->removeAlias($aliasName)->getData(); + $this->assertTrue($response['acknowledged']); + + $client->getIndex($aliasName)->getType($typeName)->search('ruflin'); + } + + public function testCount() + { + $index = $this->_createIndex(); + + // Add document to normal index + $doc1 = new Document(null, array('name' => 'ruflin')); + $doc2 = new Document(null, array('name' => 'nicolas')); + + $type = $index->getType('test'); + $type->addDocument($doc1); + $type->addDocument($doc2); + + + $index->refresh(); + + $this->assertEquals(2, $index->count()); + + $query = new Term(); + $key = 'name'; + $value = 'nicolas'; + $query->setTerm($key, $value); + + $this->assertEquals(1, $index->count($query)); + } + + public function testDeleteIndexDeleteAlias() + { + $indexName = 'test'; + $aliasName = 'test-aliase'; + + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + + $index->create(array(), true); + $index->addAlias($aliasName); + + $status = new Status($client); + $this->assertTrue($status->indexExists($indexName)); + $this->assertTrue($status->aliasExists($aliasName)); + + // Deleting index should also remove alias + $index->delete(); + + $status->refresh(); + $this->assertFalse($status->indexExists($indexName)); + $this->assertFalse($status->aliasExists($aliasName)); + } + + public function testAddAliasTwoIndices() + { + $indexName1 = 'test1'; + $indexName2 = 'test2'; + $aliasName = 'test-alias'; + + $client = $this->_getClient(); + $index1 = $client->getIndex($indexName1); + $index2 = $client->getIndex($indexName2); + + $index1->create(array(), true); + $index1->addAlias($aliasName); + $index2->create(array(), true); + + $index1->refresh(); + $index2->refresh(); + $index1->optimize(); + $index2->optimize(); + + $status = new Status($client); + + + $this->assertTrue($status->indexExists($indexName1)); + $this->assertTrue($status->indexExists($indexName2)); + + $this->assertTrue($status->aliasExists($aliasName)); + $this->assertTrue($index1->getStatus()->hasAlias($aliasName)); + $this->assertFalse($index2->getStatus()->hasAlias($aliasName)); + + $index2->addAlias($aliasName); + $this->assertTrue($index1->getStatus()->hasAlias($aliasName)); + $this->assertTrue($index2->getStatus()->hasAlias($aliasName)); + } + + public function testReplaceAlias() + { + $indexName1 = 'test1'; + $indexName2 = 'test2'; + $aliasName = 'test-alias'; + + $client = $this->_getClient(); + $index1 = $client->getIndex($indexName1); + $index2 = $client->getIndex($indexName2); + + $index1->create(array(), true); + $index1->addAlias($aliasName); + $index2->create(array(), true); + + $index1->refresh(); + $index2->refresh(); + + $status = new Status($client); + + $this->assertTrue($status->indexExists($indexName1)); + $this->assertTrue($status->indexExists($indexName2)); + $this->assertTrue($status->aliasExists($aliasName)); + $this->assertTrue($index1->getStatus()->hasAlias($aliasName)); + $this->assertFalse($index2->getStatus()->hasAlias($aliasName)); + + $index2->addAlias($aliasName, true); + $this->assertFalse($index1->getStatus()->hasAlias($aliasName)); + $this->assertTrue($index2->getStatus()->hasAlias($aliasName)); + } + + public function testAddDocumentVersion() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = new Type($index, 'test'); + + $doc1 = new Document(1); + $doc1->set('title', 'Hello world'); + + $return = $type->addDocument($doc1); + $data = $return->getData(); + $this->assertEquals(1, $data['_version']); + + $return = $type->addDocument($doc1); + $data = $return->getData(); + $this->assertEquals(2, $data['_version']); + } + + public function testClearCache() + { + $client = $this->_getClient(); + $index1 = $client->getIndex('test1'); + + $response = $index1->clearCache(); + $this->assertFalse($response->hasError()); + } + + public function testFlush() + { + $client = $this->_getClient(); + $index = $client->getIndex('test1'); + + $response = $index->flush(); + $this->assertFalse($response->hasError()); + } + + public function testExists() + { + $index = $this->_createIndex(); + + $this->assertTrue($index->exists()); + + $index->delete(); + + $this->assertFalse($index->exists()); + } + + /** + * Test $index->delete() return value for unknown index + * + * Tests if deleting an index that does not exist in Elasticsearch, + * correctly returns a boolean true from the hasError() method of + * the \Elastica\Response object + */ + public function testDeleteMissingIndexHasError() + { + $client = $this->_getClient(); + $index = $client->getIndex('index_does_not_exist'); + + try { + $index->delete(); + $this->fail('This should never be reached. Deleting an unknown index will throw an exception'); + } catch (ResponseException $error) { + $response = $error->getResponse(); + $this->assertTrue($response->hasError()); + $request = $error->getRequest(); + $this->assertInstanceOf('Elastica\Request', $request); + } + } + + /** + * Tests to see if the test type mapping exists when calling $index->getMapping() + */ + public function testIndexGetMapping() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + + $mapping = array('id' => array('type' => 'integer', 'store' => true), 'email' => array('type' => 'string', 'store' => 'no'), + 'username' => array('type' => 'string', 'store' => 'no'), 'test' => array('type' => 'integer', 'store' => 'no'),); + + $type->setMapping($mapping); + $index->refresh(); + $indexMappings = $index->getMapping(); + + $this->assertEquals($indexMappings['test']['properties']['id']['type'], 'integer'); + $this->assertEquals($indexMappings['test']['properties']['id']['store'], true); + $this->assertEquals($indexMappings['test']['properties']['email']['type'], 'string'); + $this->assertEquals($indexMappings['test']['properties']['username']['type'], 'string'); + $this->assertEquals($indexMappings['test']['properties']['test']['type'], 'integer'); + } + + /** + * Tests to see if the index is empty when there are no types set. + */ + public function testEmptyIndexGetMapping() + { + $index = $this->_createIndex(); + $indexMappings = $index->getMapping(); + + $this->assertTrue(empty($indexMappings['elastica_test'])); + } + + /** + * Test to see if search Default Limit works + */ + public function testLimitDefaultIndex() + { + $client = $this->_getClient(); + $index = $client->getIndex('zero'); + $index->create(array('index' => array('number_of_shards' => 1, 'number_of_replicas' => 0)), true); + + $docs = array(); + + $docs[] = new Document(1, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(2, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(3, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(4, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(5, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(6, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(7, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(8, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(9, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(10, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(11, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + + $type = $index->getType('zeroType'); + $type->addDocuments($docs); + $index->refresh(); + + // default limit results (default limit is 10) + $resultSet = $index->search('farrelley'); + $this->assertEquals(10, $resultSet->count()); + + // limit = 1 + $resultSet = $index->search('farrelley', 1); + $this->assertEquals(1, $resultSet->count()); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testCreateArray() + { + $client = $this->_getClient(); + $indexName = 'test'; + + //Testing recreate (backward compatibility) + $index = $client->getIndex($indexName); + $index->create(array(), true); + $status = new Status($client); + $this->assertTrue($status->indexExists($indexName)); + + //Testing create index with array options + $opts = array('recreate' => true, 'routing' => 'r1,r2'); + $index->create(array(), $opts); + $status = new Status($client); + $this->assertTrue($status->indexExists($indexName)); + + //Testing invalid options + $opts = array('recreate' => true, 'routing' => 'r1,r2', 'testing_invalid_option' => true); + $index->create(array(), $opts); + $status = new Status($client); + $this->assertTrue($status->indexExists($indexName)); + } + + public function testCreateSearch() + { + $client = $this->_getClient(); + $index = new Index($client, 'test'); + + $query = new QueryString('test'); + $options = 5; + + $search = $index->createSearch($query, $options); + + $expected = array( + 'query' => array( + 'query_string' => array( + 'query' => 'test' + ) + ), + 'size' => 5 + ); + $this->assertEquals($expected, $search->getQuery()->toArray()); + $this->assertEquals(array('test'), $search->getIndices()); + $this->assertTrue($search->hasIndices()); + $this->assertTrue($search->hasIndex('test')); + $this->assertTrue($search->hasIndex($index)); + $this->assertEquals(array(), $search->getTypes()); + $this->assertFalse($search->hasTypes()); + $this->assertFalse($search->hasType('test_type')); + + $type = new Type($index, 'test_type2'); + $this->assertFalse($search->hasType($type)); + } + + public function testSearch() + { + $index = $this->_createIndex(); + + $type = new Type($index, 'user'); + + $docs = array(); + $docs[] = new Document(1, array('username' => 'hans', 'test' => array('2', '3', '5'))); + $docs[] = new Document(2, array('username' => 'john', 'test' => array('1', '3', '6'))); + $docs[] = new Document(3, array('username' => 'rolf', 'test' => array('2', '3', '7'))); + $type->addDocuments($docs); + $index->refresh(); + + $resultSet = $index->search('rolf'); + $this->assertEquals(1, $resultSet->count()); + + $count = $index->count('rolf'); + $this->assertEquals(1, $count); + + // Test if source is returned + $result = $resultSet->current(); + $this->assertEquals(3, $result->getId()); + $data = $result->getData(); + $this->assertEquals('rolf', $data['username']); + + $count = $index->count(); + $this->assertEquals(3, $count); + } + + public function testOptimize() + { + $index = $this->_createIndex(); + + $type = new Type($index, 'optimize'); + + $docs = array(); + $docs[] = new Document(1, array('foo' => 'bar')); + $docs[] = new Document(2, array('foo' => 'bar')); + $type->addDocuments($docs); + $index->refresh(); + + $stats = $index->getStats()->getData(); + $this->assertEquals(0, $stats['_all']['primaries']['docs']['deleted']); + + $type->deleteById(1); + $index->refresh(); + + $stats = $index->getStats()->getData(); + $this->assertEquals(1, $stats['_all']['primaries']['docs']['deleted']); + + $index->optimize(array('max_num_segments' => 1)); + + $stats = $index->getStats()->getData(); + $this->assertEquals(0, $stats['_all']['primaries']['docs']['deleted']); + } + + public function testAnalyze() + { + $index = $this->_createIndex('analyze'); + $index->optimize(); + sleep(2); + $returnedTokens = $index->analyze('foo'); + + $tokens = array( + array( + 'token' => 'foo', + 'start_offset' => 0, + 'end_offset' => 3, + 'type' => '<ALPHANUM>', + 'position' => 1, + ) + ); + + $this->assertEquals($tokens, $returnedTokens); + } + + /** + * Check for the presence of the mapper-attachments plugin and skip the current test if it is not found. + */ + protected function _checkAttachmentsPlugin() + { + $nodes = $this->_getClient()->getCluster()->getNodes(); + if (!$nodes[0]->getInfo()->hasPlugin('mapper-attachments')) { + $this->markTestSkipped('mapper-attachments plugin not installed'); + } + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/LogTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/LogTest.php new file mode 100644 index 00000000..188be933 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/LogTest.php @@ -0,0 +1,153 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Client; +use Elastica\Log; +use Elastica\Test\Base as BaseTest; +use Psr\Log\LogLevel; + +class LogTest extends BaseTest +{ + private $_context = array(); + private $_message = 'hello world'; + + protected function setUp() + { + if (!class_exists('Psr\Log\AbstractLogger')) { + $this->markTestSkipped('The Psr extension is not available.'); + } + } + + public function testLogInterface() + { + $log = new Log(); + $this->assertInstanceOf('Psr\Log\LoggerInterface', $log); + } + + public function testSetLogConfigPath() + { + $logPath = '/tmp/php.log'; + $client = new Client(array('log' => $logPath)); + $this->assertEquals($logPath, $client->getConfig('log')); + } + + public function testSetLogConfigEnable() + { + $client = new Client(array('log' => true)); + $this->assertTrue($client->getConfig('log')); + } + + public function testSetLogConfigEnable1() + { + $client = new Client(); + $client->setLogger(new Log()); + $this->assertFalse($client->getConfig('log')); + } + + public function testEmptyLogConfig() + { + $client = $this->_getClient(); + $this->assertEmpty($client->getConfig('log')); + } + + public function testGetLastMessage() + { + $log = new Log('/tmp/php.log'); + + $log->log(LogLevel::DEBUG, $this->_message, $this->_context); + + $this->_context['error_message'] = $this->_message; + $message = json_encode($this->_context); + + $this->assertEquals($message, $log->getLastMessage()); + } + + public function testGetLastMessage2() + { + $client = new Client(array('log' => true)); + $log = new Log($client); + + // Set log path temp path as otherwise test fails with output + $errorLog = ini_get('error_log'); + ini_set('error_log', sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'php.log'); + + $this->_context['error_message'] = $this->_message; + $message = json_encode($this->_context); + + $log->log(LogLevel::DEBUG, $this->_message, $this->_context); + ini_set('error_log', $errorLog); + + $this->assertEquals($message, $log->getLastMessage()); + } + + public function testGetLastMessageInfo() + { + $log = $this->initLog(); + $log->info($this->_message, $this->_context); + $this->assertEquals($this->getMessage(), $log->getLastMessage()); + } + + public function testGetLastMessageCritical() + { + $log = $this->initLog(); + $log->critical($this->_message, $this->_context); + $this->assertEquals($this->getMessage(), $log->getLastMessage()); + } + + public function testGetLastMessageAlert() + { + $log = $this->initLog(); + $log->alert($this->_message, $this->_context); + $this->assertEquals($this->getMessage(), $log->getLastMessage()); + } + + public function testGetLastMessageDebug() + { + $log = $this->initLog(); + $log->debug($this->_message, $this->_context); + $this->assertEquals($this->getMessage(), $log->getLastMessage()); + } + + public function testGetLastMessageEmergency() + { + $log = $this->initLog(); + $log->emergency($this->_message, $this->_context); + $this->assertEquals($this->getMessage(), $log->getLastMessage()); + } + + public function testGetLastMessageError() + { + $log = $this->initLog(); + $log->error($this->_message, $this->_context); + $this->assertEquals($this->getMessage(), $log->getLastMessage()); + } + + public function testGetLastMessageNotice() + { + $log = $this->initLog(); + $log->notice($this->_message, $this->_context); + $this->assertEquals($this->getMessage(), $log->getLastMessage()); + } + + public function testGetLastMessageWarning() + { + $log = $this->initLog(); + $log->warning($this->_message, $this->_context); + $this->assertEquals($this->getMessage(), $log->getLastMessage()); + } + + private function initLog() + { + $log = new Log('/tmp/php.log'); + + return $log; + } + + private function getMessage() + { + $this->_context['error_message'] = $this->_message; + + return json_encode($this->_context); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Multi/SearchTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Multi/SearchTest.php new file mode 100644 index 00000000..a62aaaad --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Multi/SearchTest.php @@ -0,0 +1,549 @@ +<?php + +namespace Elastica\Test\Multi; + +use Elastica\Document; +use Elastica\Multi\Search as MultiSearch; +use Elastica\Query; +use Elastica\Query\Range; +use Elastica\Query\Term; +use Elastica\Search; +use Elastica\Test\Base as BaseTest; + +class SearchTest extends BaseTest +{ + /** + * @return \Elastica\Type + */ + protected function _createType() + { + $client = $this->_getClient(); + + $index = $client->getIndex('zero'); + $index->create(array('index' => array('number_of_shards' => 1, 'number_of_replicas' => 0)), true); + + $docs = array(); + $docs[] = new Document(1, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(2, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(3, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(4, array('id' => 1, 'email' => 'test@test.com', 'username' => 'kate')); + $docs[] = new Document(5, array('id' => 1, 'email' => 'test@test.com', 'username' => 'kate')); + $docs[] = new Document(6, array('id' => 1, 'email' => 'test@test.com', 'username' => 'bunny')); + $docs[] = new Document(7, array('id' => 1, 'email' => 'test@test.com', 'username' => 'bunny')); + $docs[] = new Document(8, array('id' => 1, 'email' => 'test@test.com', 'username' => 'bunny')); + $docs[] = new Document(9, array('id' => 1, 'email' => 'test@test.com', 'username' => 'bunny')); + $docs[] = new Document(10, array('id' => 1, 'email' => 'test@test.com', 'username' => 'bunny')); + $docs[] = new Document(11, array('id' => 1, 'email' => 'test@test.com', 'username' => 'bunny')); + $type = $index->getType('zeroType'); + $type->addDocuments($docs); + $index->refresh(); + + return $type; + } + + public function testConstruct() + { + $client = $this->_getClient(); + $multiSearch = new MultiSearch($client); + + $this->assertInstanceOf('Elastica\Multi\Search', $multiSearch); + $this->assertSame($client, $multiSearch->getClient()); + } + + public function testSetSearches() + { + $client = $this->_getClient(); + $multiSearch = new MultiSearch($client); + + $search1 = new Search($client); + $search2 = new Search($client); + $search3 = new Search($client); + + $multiSearch->setSearches(array($search1, $search2, $search3)); + + $searches = $multiSearch->getSearches(); + + $this->assertInternalType('array', $searches); + $this->assertCount(3, $searches); + $this->assertArrayHasKey(0, $searches); + $this->assertSame($search1, $searches[0]); + $this->assertArrayHasKey(1, $searches); + $this->assertSame($search2, $searches[1]); + $this->assertArrayHasKey(2, $searches); + $this->assertSame($search3, $searches[2]); + + $multiSearch->clearSearches(); + $searches = $multiSearch->getSearches(); + + $this->assertInternalType('array', $searches); + $this->assertCount(0, $searches); + } + + public function testSetSearchesByKeys() + { + $client = $this->_getClient(); + $multiSearch = new MultiSearch($client); + + $search1 = new Search($client); + $search2 = new Search($client); + $search3 = new Search($client); + + $multiSearch->setSearches(array('search1' => $search1, 'search2' => $search2, $search3)); + + $searches = $multiSearch->getSearches(); + + $this->assertInternalType('array', $searches); + $this->assertCount(3, $searches); + $this->assertArrayHasKey('search1', $searches); + $this->assertSame($search1, $searches['search1']); + $this->assertArrayHasKey('search2', $searches); + $this->assertSame($search2, $searches['search2']); + $this->assertArrayHasKey(0, $searches); + $this->assertSame($search3, $searches[0]); + + $multiSearch->clearSearches(); + $searches = $multiSearch->getSearches(); + + $this->assertInternalType('array', $searches); + $this->assertCount(0, $searches); + } + + public function testSearch() + { + $type = $this->_createType(); + $index = $type->getIndex(); + $client = $index->getClient(); + + $multiSearch = new MultiSearch($client); + + $search1 = new Search($client); + $search1->addIndex($index)->addType($type); + $query1 = new Query(); + $termQuery1 = new Term(); + $termQuery1->setTerm('username', 'farrelley'); + $query1->setQuery($termQuery1); + $query1->setSize(2); + $search1->setQuery($query1); + + $multiSearch->addSearch($search1); + + $this->assertCount(1, $multiSearch->getSearches()); + + $search2 = new Search($client); + $search2->addIndex($index)->addType($type); + $query2 = new Query(); + $termQuery2 = new Term(); + $termQuery2->setTerm('username', 'bunny'); + $query2->setQuery($termQuery2); + $query2->setSize(3); + $search2->setQuery($query2); + + $multiSearch->addSearch($search2); + + $this->assertCount(2, $multiSearch->getSearches()); + + $searches = $multiSearch->getSearches(); + $this->assertSame($search1, $searches[0]); + $this->assertSame($search2, $searches[1]); + + $multiResultSet = $multiSearch->search(); + + $this->assertInstanceOf('Elastica\Multi\ResultSet', $multiResultSet); + $this->assertCount(2, $multiResultSet); + $this->assertInstanceOf('Elastica\Response', $multiResultSet->getResponse()); + + foreach ($multiResultSet as $resultSet) { + $this->assertInstanceOf('Elastica\ResultSet', $resultSet); + } + + $resultSets = $multiResultSet->getResultSets(); + + $this->assertInternalType('array', $resultSets); + + $this->assertArrayHasKey(0, $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets[0]); + $this->assertCount(2, $resultSets[0]); + $this->assertSame($query1, $resultSets[0]->getQuery()); + $this->assertEquals(3, $resultSets[0]->getTotalHits()); + + $this->assertArrayHasKey(1, $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets[1]); + $this->assertCount(3, $resultSets[1]); + $this->assertSame($query2, $resultSets[1]->getQuery()); + $this->assertEquals(6, $resultSets[1]->getTotalHits()); + + $this->assertFalse($multiResultSet->hasError()); + + $search1->setOption(Search::OPTION_SEARCH_TYPE, Search::OPTION_SEARCH_TYPE_COUNT); + $search2->setOption(Search::OPTION_SEARCH_TYPE, Search::OPTION_SEARCH_TYPE_COUNT); + + $multiResultSet = $multiSearch->search(); + + $this->assertInstanceOf('Elastica\Multi\ResultSet', $multiResultSet); + $this->assertCount(2, $multiResultSet); + $this->assertInstanceOf('Elastica\Response', $multiResultSet->getResponse()); + + $resultSets = $multiResultSet->getResultSets(); + + $this->assertInternalType('array', $resultSets); + + $this->assertArrayHasKey(0, $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets[0]); + $this->assertCount(0, $resultSets[0]); + $this->assertSame($query1, $resultSets[0]->getQuery()); + $this->assertEquals(3, $resultSets[0]->getTotalHits()); + + $this->assertArrayHasKey(1, $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets[1]); + $this->assertCount(0, $resultSets[1]); + $this->assertSame($query2, $resultSets[1]->getQuery()); + $this->assertEquals(6, $resultSets[1]->getTotalHits()); + } + + public function testSearchWithKeys() + { + $type = $this->_createType(); + $index = $type->getIndex(); + $client = $index->getClient(); + + $multiSearch = new MultiSearch($client); + + $search1 = new Search($client); + $search1->addIndex($index)->addType($type); + $query1 = new Query(); + $termQuery1 = new Term(); + $termQuery1->setTerm('username', 'farrelley'); + $query1->setQuery($termQuery1); + $query1->setSize(2); + $search1->setQuery($query1); + + $multiSearch->addSearch($search1, "search1"); + + $this->assertCount(1, $multiSearch->getSearches()); + + $search2 = new Search($client); + $search2->addIndex($index)->addType($type); + $query2 = new Query(); + $termQuery2 = new Term(); + $termQuery2->setTerm('username', 'bunny'); + $query2->setQuery($termQuery2); + $query2->setSize(3); + $search2->setQuery($query2); + + $multiSearch->addSearch($search2, "search2"); + + $this->assertCount(2, $multiSearch->getSearches()); + + $searches = $multiSearch->getSearches(); + $this->assertSame($search1, $searches["search1"]); + $this->assertSame($search2, $searches["search2"]); + + $multiResultSet = $multiSearch->search(); + + $this->assertInstanceOf('Elastica\Multi\ResultSet', $multiResultSet); + $this->assertCount(2, $multiResultSet); + $this->assertInstanceOf('Elastica\Response', $multiResultSet->getResponse()); + + foreach ($multiResultSet as $resultSet) { + $this->assertInstanceOf('Elastica\ResultSet', $resultSet); + } + + $this->assertInstanceOf('Elastica\ResultSet', $multiResultSet["search1"]); + $this->assertInstanceOf('Elastica\ResultSet', $multiResultSet["search2"]); + + $resultSets = $multiResultSet->getResultSets(); + + $this->assertInternalType('array', $resultSets); + + $this->assertArrayHasKey("search1", $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets["search1"]); + $this->assertCount(2, $resultSets["search1"]); + $this->assertSame($query1, $resultSets["search1"]->getQuery()); + $this->assertEquals(3, $resultSets["search1"]->getTotalHits()); + + $this->assertArrayHasKey("search2", $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets["search2"]); + $this->assertCount(3, $resultSets["search2"]); + $this->assertSame($query2, $resultSets["search2"]->getQuery()); + $this->assertEquals(6, $resultSets["search2"]->getTotalHits()); + + $this->assertFalse($multiResultSet->hasError()); + + $search1->setOption(Search::OPTION_SEARCH_TYPE, Search::OPTION_SEARCH_TYPE_COUNT); + $search2->setOption(Search::OPTION_SEARCH_TYPE, Search::OPTION_SEARCH_TYPE_COUNT); + + $multiResultSet = $multiSearch->search(); + + $this->assertInstanceOf('Elastica\Multi\ResultSet', $multiResultSet); + $this->assertCount(2, $multiResultSet); + $this->assertInstanceOf('Elastica\Response', $multiResultSet->getResponse()); + + $resultSets = $multiResultSet->getResultSets(); + + $this->assertInternalType('array', $resultSets); + + $this->assertArrayHasKey("search1", $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets["search1"]); + $this->assertCount(0, $resultSets["search1"]); + $this->assertSame($query1, $resultSets["search1"]->getQuery()); + $this->assertEquals(3, $resultSets["search1"]->getTotalHits()); + + $this->assertArrayHasKey("search2", $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets["search2"]); + $this->assertCount(0, $resultSets["search2"]); + $this->assertSame($query2, $resultSets["search2"]->getQuery()); + $this->assertEquals(6, $resultSets["search2"]->getTotalHits()); + } + + public function testSearchWithError() + { + $type = $this->_createType(); + $index = $type->getIndex(); + $client = $index->getClient(); + + $multiSearch = new MultiSearch($client); + + $searchGood = new Search($client); + $searchGood->setQuery('bunny'); + $searchGood->addIndex($index)->addType($type); + + $multiSearch->addSearch($searchGood); + + $searchBad = new Search($client); + $searchBadQuery = new Range(); + $searchBadQuery->addField('bad', array('from' => 0)); + $searchBadQuery->setParam('_cache', true); + $searchBad->setQuery($searchBadQuery); + $searchBad->addIndex($index)->addType($type); + + $multiSearch->addSearch($searchBad); + + $multiResultSet = $multiSearch->search(); + + $this->assertInstanceOf('Elastica\Multi\ResultSet', $multiResultSet); + $resultSets = $multiResultSet->getResultSets(); + $this->assertInternalType('array', $resultSets); + + $this->assertArrayHasKey(0, $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets[0]); + $this->assertSame($searchGood->getQuery(), $resultSets[0]->getQuery()); + $this->assertSame(6, $resultSets[0]->getTotalHits()); + $this->assertCount(6, $resultSets[0]); + + $this->assertArrayHasKey(1, $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets[1]); + $this->assertSame($searchBad->getQuery(), $resultSets[1]->getQuery()); + $this->assertSame(0, $resultSets[1]->getTotalHits()); + $this->assertCount(0, $resultSets[1]); + $this->assertTrue($resultSets[1]->getResponse()->hasError()); + + $this->assertTrue($multiResultSet->hasError()); + } + + public function testSearchWithErrorWithKeys() + { + $type = $this->_createType(); + $index = $type->getIndex(); + $client = $index->getClient(); + + $multiSearch = new MultiSearch($client); + + $searchGood = new Search($client); + $searchGood->setQuery('bunny'); + $searchGood->addIndex($index)->addType($type); + + $multiSearch->addSearch($searchGood, "search1"); + + $searchBad = new Search($client); + $searchBadQuery = new Range(); + $searchBadQuery->addField('bad', array('from' => 0)); + $searchBadQuery->setParam('_cache', true); + $searchBad->setQuery($searchBadQuery); + $searchBad->addIndex($index)->addType($type); + + $multiSearch->addSearch($searchBad); + + $multiResultSet = $multiSearch->search(); + + $this->assertInstanceOf('Elastica\Multi\ResultSet', $multiResultSet); + $resultSets = $multiResultSet->getResultSets(); + $this->assertInternalType('array', $resultSets); + + $this->assertArrayHasKey("search1", $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets["search1"]); + $this->assertSame($searchGood->getQuery(), $resultSets["search1"]->getQuery()); + $this->assertSame(6, $resultSets["search1"]->getTotalHits()); + $this->assertCount(6, $resultSets["search1"]); + + $this->assertArrayHasKey(0, $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets[0]); + $this->assertSame($searchBad->getQuery(), $resultSets[0]->getQuery()); + $this->assertSame(0, $resultSets[0]->getTotalHits()); + $this->assertCount(0, $resultSets[0]); + $this->assertTrue($resultSets[0]->getResponse()->hasError()); + + $this->assertTrue($multiResultSet->hasError()); + } + + public function testGlobalSearchTypeSearch() + { + $type = $this->_createType(); + $index = $type->getIndex(); + $client = $index->getClient(); + + $multiSearch = new MultiSearch($client); + + $search1 = new Search($client); + $search1->addIndex($index)->addType($type); + $query1 = new Query(); + $termQuery1 = new Term(); + $termQuery1->setTerm('username', 'farrelley'); + $query1->setQuery($termQuery1); + $query1->setSize(2); + $search1->setQuery($query1); + + $multiSearch->addSearch($search1); + + $this->assertCount(1, $multiSearch->getSearches()); + + $search2 = new Search($client); + $search2->addIndex($index)->addType($type); + $query2 = new Query(); + $termQuery2 = new Term(); + $termQuery2->setTerm('username', 'bunny'); + $query2->setQuery($termQuery2); + $query2->setSize(3); + $search2->setQuery($query2); + + $multiSearch->addSearch($search2); + + $multiSearch->setSearchType(Search::OPTION_SEARCH_TYPE_COUNT); + + $multiResultSet = $multiSearch->search(); + + $this->assertInstanceOf('Elastica\Multi\ResultSet', $multiResultSet); + $this->assertCount(2, $multiResultSet); + $this->assertInstanceOf('Elastica\Response', $multiResultSet->getResponse()); + + $resultSets = $multiResultSet->getResultSets(); + + $this->assertInternalType('array', $resultSets); + + $this->assertArrayHasKey(0, $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets[0]); + $this->assertCount(0, $resultSets[0]); + $this->assertSame($query1, $resultSets[0]->getQuery()); + $this->assertEquals(3, $resultSets[0]->getTotalHits()); + + $this->assertArrayHasKey(1, $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets[1]); + $this->assertCount(0, $resultSets[1]); + $this->assertSame($query2, $resultSets[1]->getQuery()); + $this->assertEquals(6, $resultSets[1]->getTotalHits()); + + $search1->setOption(Search::OPTION_SEARCH_TYPE, Search::OPTION_SEARCH_TYPE_QUERY_AND_FETCH); + + $multiResultSet = $multiSearch->search(); + + $this->assertInstanceOf('Elastica\Multi\ResultSet', $multiResultSet); + $this->assertCount(2, $multiResultSet); + $this->assertInstanceOf('Elastica\Response', $multiResultSet->getResponse()); + + $resultSets = $multiResultSet->getResultSets(); + + $this->assertInternalType('array', $resultSets); + + $this->assertArrayHasKey(0, $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets[0]); + $this->assertCount(2, $resultSets[0]); + $this->assertSame($query1, $resultSets[0]->getQuery()); + $this->assertEquals(3, $resultSets[0]->getTotalHits()); + + $this->assertArrayHasKey(1, $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets[1]); + $this->assertCount(0, $resultSets[1]); + $this->assertSame($query2, $resultSets[1]->getQuery()); + $this->assertEquals(6, $resultSets[1]->getTotalHits()); + } + + public function testGlobalSearchTypeSearchWithKeys() + { + $type = $this->_createType(); + $index = $type->getIndex(); + $client = $index->getClient(); + + $multiSearch = new MultiSearch($client); + + $search1 = new Search($client); + $search1->addIndex($index)->addType($type); + $query1 = new Query(); + $termQuery1 = new Term(); + $termQuery1->setTerm('username', 'farrelley'); + $query1->setQuery($termQuery1); + $query1->setSize(2); + $search1->setQuery($query1); + + $multiSearch->addSearch($search1); + + $this->assertCount(1, $multiSearch->getSearches()); + + $search2 = new Search($client); + $search2->addIndex($index)->addType($type); + $query2 = new Query(); + $termQuery2 = new Term(); + $termQuery2->setTerm('username', 'bunny'); + $query2->setQuery($termQuery2); + $query2->setSize(3); + $search2->setQuery($query2); + + $multiSearch->addSearch($search2); + + $multiSearch->setSearchType(Search::OPTION_SEARCH_TYPE_COUNT); + + $multiResultSet = $multiSearch->search(); + + $this->assertInstanceOf('Elastica\Multi\ResultSet', $multiResultSet); + $this->assertCount(2, $multiResultSet); + $this->assertInstanceOf('Elastica\Response', $multiResultSet->getResponse()); + + $resultSets = $multiResultSet->getResultSets(); + + $this->assertInternalType('array', $resultSets); + + $this->assertArrayHasKey(0, $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets[0]); + $this->assertCount(0, $resultSets[0]); + $this->assertSame($query1, $resultSets[0]->getQuery()); + $this->assertEquals(3, $resultSets[0]->getTotalHits()); + + $this->assertArrayHasKey(1, $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets[1]); + $this->assertCount(0, $resultSets[1]); + $this->assertSame($query2, $resultSets[1]->getQuery()); + $this->assertEquals(6, $resultSets[1]->getTotalHits()); + + $search1->setOption(Search::OPTION_SEARCH_TYPE, Search::OPTION_SEARCH_TYPE_QUERY_AND_FETCH); + + $multiResultSet = $multiSearch->search(); + + $this->assertInstanceOf('Elastica\Multi\ResultSet', $multiResultSet); + $this->assertCount(2, $multiResultSet); + $this->assertInstanceOf('Elastica\Response', $multiResultSet->getResponse()); + + $resultSets = $multiResultSet->getResultSets(); + + $this->assertInternalType('array', $resultSets); + + $this->assertArrayHasKey(0, $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets[0]); + $this->assertCount(2, $resultSets[0]); + $this->assertSame($query1, $resultSets[0]->getQuery()); + $this->assertEquals(3, $resultSets[0]->getTotalHits()); + + $this->assertArrayHasKey(1, $resultSets); + $this->assertInstanceOf('Elastica\ResultSet', $resultSets[1]); + $this->assertCount(0, $resultSets[1]); + $this->assertSame($query2, $resultSets[1]->getQuery()); + $this->assertEquals(6, $resultSets[1]->getTotalHits()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Node/InfoTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Node/InfoTest.php new file mode 100644 index 00000000..10886b2d --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Node/InfoTest.php @@ -0,0 +1,42 @@ +<?php + +namespace Elastica\Test\Node; + +use Elastica\Node; +use Elastica\Node\Info as NodeInfo; +use Elastica\Test\Base as BaseTest; + +class InfoTest extends BaseTest +{ + public function testGet() + { + $client = $this->_getClient(); + $names = $client->getCluster()->getNodeNames(); + $name = reset($names); + + $node = new Node($name, $client); + $info = new NodeInfo($node); + + $this->assertNull($info->get('os', 'mem', 'total')); + + // Load os infos + $info = new NodeInfo($node, array('os')); + + $this->assertTrue(!is_null($info->get('os', 'mem', 'total_in_bytes'))); + $this->assertInternalType('array', $info->get('os', 'mem')); + $this->assertNull($info->get('test', 'notest', 'notexist')); + } + + public function testHasPlugin() + { + $client = $this->_getClient(); + $nodes = $client->getCluster()->getNodes(); + $node = $nodes[0]; + $info = $node->getInfo(); + + $pluginName = 'mapper-attachments'; + + $this->assertTrue($info->hasPlugin($pluginName)); + $this->assertFalse($info->hasPlugin('foo')); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/NodeTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/NodeTest.php new file mode 100644 index 00000000..d70825d1 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/NodeTest.php @@ -0,0 +1,84 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Client; +use Elastica\Node; +use Elastica\Test\Base as BaseTest; + +class NodeTest extends BaseTest +{ + + public function testCreateNode() + { + $client = $this->_getClient(); + $names = $client->getCluster()->getNodeNames(); + $name = reset($names); + + $node = new Node($name, $client); + $this->assertInstanceOf('Elastica\Node', $node); + } + + public function testGetInfo() + { + $client = $this->_getClient(); + $names = $client->getCluster()->getNodeNames(); + $name = reset($names); + + $node = new Node($name, $client); + + $info = $node->getInfo(); + + $this->assertInstanceOf('Elastica\Node\Info', $info); + } + + public function testGetStats() + { + $client = $this->_getClient(); + $names = $client->getCluster()->getNodeNames(); + $name = reset($names); + + $node = new Node($name, $client); + + $stats = $node->getStats(); + + $this->assertInstanceOf('Elastica\Node\Stats', $stats); + } + + /** + * Shuts one of two nodes down (if two available) + */ + public function testShutdown() + { + $this->markTestSkipped('At least two nodes have to be running, because 1 node is shutdown'); + $client = $this->_getClient(); + $nodes = $client->getCluster()->getNodes(); + + $count = count($nodes); + if ($count < 2) { + $this->markTestSkipped('At least two nodes have to be running, because 1 node is shutdown'); + } + + // Store node info of node with port 9200 for later + foreach ($nodes as $key => $node) { + if ($node->getInfo()->getPort() == 9200) { + $info = $node->getInfo(); + unset($nodes[$key]); + } + } + + // Select one of the not port 9200 nodes and shut it down + $node = array_shift($nodes); + $node->shutdown('2s'); + + // Wait until node is shutdown + sleep(5); + + // Use still existing node + $client = new Client(array('host' => $info->getIp(), 'port' => $info->getPort())); + $names = $client->getCluster()->getNodeNames(); + + // One node less ... + $this->assertEquals($count - 1, count($names)); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/ParamTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/ParamTest.php new file mode 100644 index 00000000..fab77600 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/ParamTest.php @@ -0,0 +1,97 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Param; +use Elastica\Util; +use Elastica\Test\Base as BaseTest; + +class ParamTest extends BaseTest +{ + public function testToArrayEmpty() + { + $param = new Param(); + $this->assertInstanceOf('Elastica\Param', $param); + $this->assertEquals(array($this->_getFilterName($param) => array()), $param->toArray()); + } + + public function testSetParams() + { + $param = new Param(); + $params = array('hello' => 'word', 'nicolas' => 'ruflin'); + $param->setParams($params); + + $this->assertInstanceOf('Elastica\Param', $param); + $this->assertEquals(array($this->_getFilterName($param) => $params), $param->toArray()); + } + + public function testSetGetParam() + { + $param = new Param(); + + $key = 'name'; + $value = 'nicolas ruflin'; + + $params = array($key => $value); + $param->setParam($key, $value); + + $this->assertEquals($params, $param->getParams()); + $this->assertEquals($value, $param->getParam($key)); + } + + public function testAddParam() + { + $param = new Param(); + + $key = 'name'; + $value = 'nicolas ruflin'; + + $param->addParam($key, $value); + + $this->assertEquals(array($key => array($value)), $param->getParams()); + $this->assertEquals(array($value), $param->getParam($key)); + } + + public function testAddParam2() + { + $param = new Param(); + + $key = 'name'; + $value1 = 'nicolas'; + $value2 = 'ruflin'; + + $param->addParam($key, $value1); + $param->addParam($key, $value2); + + $this->assertEquals(array($key => array($value1, $value2)), $param->getParams()); + $this->assertEquals(array($value1, $value2), $param->getParam($key)); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testGetParamInvalid() + { + $param = new Param(); + + $param->getParam('notest'); + } + + public function testHasParam() + { + $param = new Param(); + + $key = 'name'; + $value = 'nicolas ruflin'; + + $this->assertFalse($param->hasParam($key)); + + $param->setParam($key, $value); + $this->assertTrue($param->hasParam($key)); + } + + protected function _getFilterName($filter) + { + return Util::getParamName($filter); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/PercolatorTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/PercolatorTest.php new file mode 100644 index 00000000..f4cfae0c --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/PercolatorTest.php @@ -0,0 +1,224 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Client; +use Elastica\Document; +use Elastica\Index; +use Elastica\Percolator; +use Elastica\Query\Term; +use Elastica\Query; +use Elastica\Test\Base as BaseTest; + +class PercolatorTest extends BaseTest +{ + public function testConstruct() + { + $percolatorName = 'percotest'; + + $index = $this->_createIndex($percolatorName); + $percolator = new Percolator($index); + + $query = new Term(array('field1' => 'value1')); + $response = $percolator->registerQuery($percolatorName, $query); + + $data = $response->getData(); + + $expectedArray = array( + '_type' => '.percolator', + '_index' => $index->getName(), + '_id' => $percolatorName, + '_version' => 1, + 'created' => 1 + ); + + $this->assertEquals($expectedArray, $data); + + $index->delete(); + } + + public function testMatchDoc() + { + $index = $this->_createIndex(); + $percolator = new Percolator($index); + + $percolatorName = 'percotest'; + + $query = new Term(array('name' => 'ruflin')); + $response = $percolator->registerQuery($percolatorName, $query); + + $this->assertTrue($response->isOk()); + $this->assertFalse($response->hasError()); + + $doc1 = new Document(); + $doc1->set('name', 'ruflin'); + + $doc2 = new Document(); + $doc2->set('name', 'nicolas'); + + $index->refresh(); + + $matches1 = $percolator->matchDoc($doc1); + + $this->assertCount(1, $matches1); + $firstPercolatorFound = false; + foreach ($matches1 as $match) { + if ($match['_id'] == $percolatorName) { + $firstPercolatorFound = true; + } + } + $this->assertTrue($firstPercolatorFound); + + $matches2 = $percolator->matchDoc($doc2); + $this->assertEmpty($matches2); + + $index->delete(); + } + + /** + * Test case for using filtered percolator queries based on the Elasticsearch documentation examples. + */ + public function testFilteredMatchDoc() + { + // step one: register create index and setup the percolator query from the ES documentation. + $index = $this->_createIndex(); + $percolator = new Percolator($index); + $baseQuery = new Term(array('field1' => 'value1')); + $fields = array('color' => 'blue'); + + $response = $percolator->registerQuery('kuku', $baseQuery, $fields); + + $this->assertTrue($response->isOk()); + $this->assertFalse($response->hasError()); + + // refreshing is required in order to ensure the query is really ready for execution. + $index->refresh(); + + // step two: match a document which should match the kuku query when filtered on the blue color + $doc = new Document(); + $doc->set('field1', 'value1'); + + $matches = $percolator->matchDoc($doc, new Term(array('color' => 'blue'))); + $this->assertCount(1, $matches, 'No or too much registered query matched.'); + $this->assertEquals('kuku', $matches[0]['_id'], 'A wrong registered query has matched.'); + + // step three: validate that using a different color, no registered query matches. + $matches = $percolator->matchDoc($doc, new Term(array('color' => 'green'))); + $this->assertCount(0, $matches, 'A registered query matched, although nothing should match at all.'); + + $index->delete(); + } + + /** + * Test case for using filtered percolator queries based on the Elasticsearch documentation examples. + */ + public function testRegisterAndUnregisterPercolator() + { + // step one: register create index and setup the percolator query from the ES documentation. + $index = $this->_createIndex(); + $percolator = new Percolator($index); + $baseQuery = new Term(array('field1' => 'value1')); + $fields = array('color' => 'blue'); + + $response = $percolator->registerQuery('kuku', $baseQuery, $fields); + + $this->assertTrue($response->isOk()); + $this->assertFalse($response->hasError()); + + // refreshing is required in order to ensure the query is really ready for execution. + $index->refresh(); + + // step two: match a document which should match the kuku query when filtered on the blue color + $doc = new Document(); + $doc->set('field1', 'value1'); + + $matches = $percolator->matchDoc($doc, new Term(array('color' => 'blue'))); + $this->assertCount(1, $matches, 'No or too much registered query matched.'); + $this->assertEquals('kuku', $matches[0]['_id'], 'A wrong registered query has matched.'); + + // step three: validate that using a different color, no registered query matches. + $matches = $percolator->matchDoc($doc, new Term(array('color' => 'green'))); + $this->assertCount(0, $matches, 'A registered query matched, although nothing should match at all.'); + + + // unregister percolator query + $response = $percolator->unregisterQuery('kuku'); + + $this->assertTrue($response->isOk()); + $this->assertFalse($response->hasError()); + + // refreshing is required in order to ensure the query is really ready for execution. + $index->refresh(); + + $matches = $percolator->matchDoc($doc, new Term(array('color' => 'blue'))); + $this->assertCount(0, $matches, 'Percolator query did not get deleted.'); + + $index->delete(); + } + + protected function _getDefaultPercolator($percolatorName = 'existingDoc') + { + $index = $this->_createIndex(); + $percolator = new Percolator($index); + + $query = new Term(array('name' => 'foobar')); + $percolator->registerQuery($percolatorName, $query); + return $percolator; + } + + protected function _addDefaultDocuments($index, $type='testing') + { + $type = $index->getType('testing'); + $doc1 = new Document(1, array('name' => 'foobar')); + $doc2 = new Document(2, array('name' => 'barbaz')); + $type->addDocument($doc1); + $type->addDocument($doc2); + $index->refresh(); + return $type; + } + + public function testPercolateExistingDocWithoutAnyParameter() + { + $percolator = $this->_getDefaultPercolator(); + $index = $percolator->getIndex(); + $type = $this->_addDefaultDocuments($index); + + $matches = $percolator->matchExistingDoc(1, $type->getName()); + + $this->assertCount(1, $matches); + $this->assertEquals('existingDoc', $matches[0]['_id']); + $index->delete(); + } + + public function testPercolateExistingDocWithPercolateFormatIds() + { + $percolator = $this->_getDefaultPercolator(); + $index = $percolator->getIndex(); + $type = $this->_addDefaultDocuments($index); + + $parameter = array('percolate_format' => 'ids'); + $matches = $percolator->matchExistingDoc(1, $type->getName(), null, $parameter); + + $this->assertCount(1, $matches); + $this->assertEquals('existingDoc', $matches[0]); + $index->delete(); + } + + public function testPercolateExistingDocWithIdThatShouldBeUrlEncoded() + { + $percolator = $this->_getDefaultPercolator(); + $index = $percolator->getIndex(); + $type = $this->_addDefaultDocuments($index); + + // id with whitespace, should be urlencoded + $id = "foo bar 1"; + + $type->addDocument(new Document($id, array('name' => 'foobar'))); + $index->refresh(); + + $matches = $percolator->matchExistingDoc($id, $type->getName()); + + $this->assertCount(1, $matches); + $index->delete(); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/BoolTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/BoolTest.php new file mode 100644 index 00000000..d3bd90cd --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/BoolTest.php @@ -0,0 +1,114 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Index; +use Elastica\Query\Bool; +use Elastica\Query\Ids; +use Elastica\Query\Term; +use Elastica\Test\Base as BaseTest; +use Elastica\Type; + +class BoolTest extends BaseTest +{ + public function testToArray() + { + $query = new Bool(); + + $idsQuery1 = new Ids(); + $idsQuery1->setIds(1); + + $idsQuery2 = new Ids(); + $idsQuery2->setIds(2); + + $idsQuery3 = new Ids(); + $idsQuery3->setIds(3); + + $boost = 1.2; + $minMatch = 2; + + $query->setBoost($boost); + $query->setMinimumNumberShouldMatch($minMatch); + $query->addMust($idsQuery1); + $query->addMustNot($idsQuery2); + $query->addShould($idsQuery3->toArray()); + + $expectedArray = array( + 'bool' => array( + 'must' => array($idsQuery1->toArray()), + 'should' => array($idsQuery3->toArray()), + 'minimum_number_should_match' => $minMatch, + 'must_not' => array($idsQuery2->toArray()), + 'boost' => $boost, + ) + ); + + $this->assertEquals($expectedArray, $query->toArray()); + } + + /** + * Test to resolve the following issue + * + * https://groups.google.com/forum/?fromgroups#!topic/elastica-php-client/zK_W_hClfvU + */ + public function testToArrayStructure() + { + $boolQuery = new Bool(); + + $term1 = new Term(); + $term1->setParam('interests', 84); + + $term2 = new Term(); + $term2->setParam('interests', 92); + + $boolQuery->addShould($term1)->addShould($term2); + + $jsonString = '{"bool":{"should":[{"term":{"interests":84}},{"term":{"interests":92}}]}}'; + $this->assertEquals($jsonString, json_encode($boolQuery->toArray())); + } + + public function testSearch() + { + $client = $this->_getClient(); + $index = new Index($client, 'test'); + $index->create(array(), true); + + $type = new Type($index, 'helloworld'); + + $doc = new Document(1, array('id' => 1, 'email' => 'hans@test.com', 'username' => 'hans', 'test' => array('2', '3', '5'))); + $type->addDocument($doc); + $doc = new Document(2, array('id' => 2, 'email' => 'emil@test.com', 'username' => 'emil', 'test' => array('1', '3', '6'))); + $type->addDocument($doc); + $doc = new Document(3, array('id' => 3, 'email' => 'ruth@test.com', 'username' => 'ruth', 'test' => array('2', '3', '7'))); + $type->addDocument($doc); + + // Refresh index + $index->refresh(); + + $boolQuery = new Bool(); + $termQuery1 = new Term(array('test' => '2')); + $boolQuery->addMust($termQuery1); + $resultSet = $type->search($boolQuery); + + $this->assertEquals(2, $resultSet->count()); + + $termQuery2 = new Term(array('test' => '5')); + $boolQuery->addMust($termQuery2); + $resultSet = $type->search($boolQuery); + + $this->assertEquals(1, $resultSet->count()); + + $termQuery3 = new Term(array('username' => 'hans')); + $boolQuery->addMust($termQuery3); + $resultSet = $type->search($boolQuery); + + $this->assertEquals(1, $resultSet->count()); + + $termQuery4 = new Term(array('username' => 'emil')); + $boolQuery->addMust($termQuery4); + $resultSet = $type->search($boolQuery); + + $this->assertEquals(0, $resultSet->count()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/BoostingTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/BoostingTest.php new file mode 100644 index 00000000..f5af8740 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/BoostingTest.php @@ -0,0 +1,99 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Query\Boosting; +use Elastica\Test\Base as BaseTest; + +class BoostingTest extends BaseTest +{ + /** + * @var \Elastica\Index + */ + protected $index; + + /** + * @var \Elastica\Type + */ + protected $type; + + /* + * @var array + */ + protected $sampleData; + + protected function setUp() + { + parent::setUp(); + $this->index = $this->_createIndex('test_boostingquery'); + $this->type = $this->index->getType('test'); + $this->type->setMapping(array( + 'name' => array('type' => 'string', 'index' => 'analyzed'), + 'price' => array('type' => 'float') + )); + + $this->sampleData = array( + array("name" => "Vital Lama", "price" => 5.2), + array("name" => "Vital Match", "price" => 2.1), + array("name" => "Mercury Vital", "price" => 7.5), + array("name" => "Fist Mercury", "price" => 3.8), + array("name" => "Lama Vital 2nd", "price" => 3.2) + ); + + foreach($this->sampleData as $key => $value) { + $this->type->addDocument(new Document($key, $value)); + } + + $this->index->refresh(); + } + + protected function tearDown() + { + $this->index->delete(); + parent::tearDown(); + } + + public function testToArray() + { + $keyword = "vital"; + $negativeKeyword = "Mercury"; + + $query = new Boosting(); + $positiveQuery = new \Elastica\Query\Term(array('name' => $keyword)); + $negativeQuery = new \Elastica\Query\Term(array('name' => $negativeKeyword)); + $query->setPositiveQuery($positiveQuery); + $query->setNegativeQuery($negativeQuery); + $query->setNegativeBoost(0.3); + + $expected = array( + 'boosting' => array( + 'positive' => $positiveQuery->toArray(), + 'negative' => $negativeQuery->toArray(), + 'negative_boost' => 0.3 + ) + ); + $this->assertEquals($expected, $query->toArray()); + } + + public function testNegativeBoost() + { + $keyword = "vital"; + $negativeKeyword = "mercury"; + + $query = new Boosting(); + $positiveQuery = new \Elastica\Query\Term(array('name' => $keyword)); + $negativeQuery = new \Elastica\Query\Term(array('name' => $negativeKeyword)); + $query->setPositiveQuery($positiveQuery); + $query->setNegativeQuery($negativeQuery); + $query->setNegativeBoost(0.2); + + $response = $this->type->search($query); + $results = $response->getResults(); + + $this->assertEquals($response->getTotalHits(), 4); + + $lastResult = $results[3]->getData(); + $this->assertEquals($lastResult['name'], $this->sampleData[2]['name']); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/BuilderTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/BuilderTest.php new file mode 100644 index 00000000..5875c4ba --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/BuilderTest.php @@ -0,0 +1,270 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Query\Builder; +use Elastica\Test\Base as BaseTest; + +class BuilderTest extends BaseTest +{ + /** + * @var \Elastica\Query\Builder + */ + private $builder; + + public function setUp() + { + $this->builder = new Builder(); + } + + public function tearDown() + { + $this->builder = null; + } + + /** + * @covers \Elastica\Query\Builder::factory + * @covers \Elastica\Query\Builder::__construct + */ + public function testFactory() + { + $this->assertInstanceOf( + 'Elastica\Query\Builder', + Builder::factory('some string') + ); + } + + public function getQueryData() + { + return array( + array('allowLeadingWildcard', false, '{"allow_leading_wildcard":"false"}'), + array('allowLeadingWildcard', true, '{"allow_leading_wildcard":"true"}'), + array('analyzeWildcard', false, '{"analyze_wildcard":"false"}'), + array('analyzeWildcard', true, '{"analyze_wildcard":"true"}'), + array('analyzer', 'someAnalyzer', '{"analyzer":"someAnalyzer"}'), + array('autoGeneratePhraseQueries', true, '{"auto_generate_phrase_queries":"true"}'), + array('autoGeneratePhraseQueries', false, '{"auto_generate_phrase_queries":"false"}'), + array('boost', 2, '{"boost":"2"}'), + array('boost', 4.2, '{"boost":"4.2"}'), + array('defaultField', 'fieldName', '{"default_field":"fieldName"}'), + array('defaultOperator', 'OR', '{"default_operator":"OR"}'), + array('defaultOperator', 'AND', '{"default_operator":"AND"}'), + array('enablePositionIncrements', true, '{"enable_position_increments":"true"}'), + array('enablePositionIncrements', false, '{"enable_position_increments":"false"}'), + array('explain', true, '{"explain":"true"}'), + array('explain', false, '{"explain":"false"}'), + array('from', 42, '{"from":"42"}'), + array('fuzzyMinSim', 4.2, '{"fuzzy_min_sim":"4.2"}'), + array('fuzzyPrefixLength', 2, '{"fuzzy_prefix_length":"2"}'), + array('gt', 10, '{"gt":"10"}'), + array('gte', 11, '{"gte":"11"}'), + array('lowercaseExpandedTerms', true, '{"lowercase_expanded_terms":"true"}'), + array('lt', 10, '{"lt":"10"}'), + array('lte', 11, '{"lte":"11"}'), + array('minimumNumberShouldMatch', 21, '{"minimum_number_should_match":"21"}'), + array('phraseSlop', 6, '{"phrase_slop":"6"}'), + array('size', 7, '{"size":"7"}'), + array('tieBreakerMultiplier', 7, '{"tie_breaker_multiplier":"7"}'), + array('matchAll', 1.1, '{"match_all":{"boost":"1.1"}}'), + array('fields', array("age", "sex", "location"), '{"fields":["age","sex","location"]}'), + ); + } + + /** + * @dataProvider getQueryData + * @covers \Elastica\Query\Builder::__toString + * @covers \Elastica\Query\Builder::allowLeadingWildcard + * @covers \Elastica\Query\Builder::analyzeWildcard + * @covers \Elastica\Query\Builder::analyzer + * @covers \Elastica\Query\Builder::autoGeneratePhraseQueries + * @covers \Elastica\Query\Builder::boost + * @covers \Elastica\Query\Builder::defaultField + * @covers \Elastica\Query\Builder::defaultOperator + * @covers \Elastica\Query\Builder::enablePositionIncrements + * @covers \Elastica\Query\Builder::explain + * @covers \Elastica\Query\Builder::from + * @covers \Elastica\Query\Builder::fuzzyMinSim + * @covers \Elastica\Query\Builder::fuzzyPrefixLength + * @covers \Elastica\Query\Builder::gt + * @covers \Elastica\Query\Builder::gte + * @covers \Elastica\Query\Builder::lowercaseExpandedTerms + * @covers \Elastica\Query\Builder::lt + * @covers \Elastica\Query\Builder::lte + * @covers \Elastica\Query\Builder::minimumNumberShouldMatch + * @covers \Elastica\Query\Builder::phraseSlop + * @covers \Elastica\Query\Builder::size + * @covers \Elastica\Query\Builder::tieBreakerMultiplier + * @covers \Elastica\Query\Builder::matchAll + * @covers \Elastica\Query\Builder::fields + */ + public function testAllowLeadingWildcard($method, $argument, $result) + { + $this->assertSame($this->builder, $this->builder->$method($argument)); + $this->assertSame($result, (string) $this->builder); + } + + public function getQueryTypes() + { + return array( + array('bool', 'bool'), + array('constantScore', 'constant_score'), + array('disMax', 'dis_max'), + array('facets', 'facets'), + array('filter', 'filter'), + array('filteredQuery', 'filtered'), + array('must', 'must'), + array('mustNot', 'must_not'), + array('prefix', 'prefix'), + array('query', 'query'), + array('queryString', 'query_string'), + array('range', 'range'), + array('should', 'should'), + array('sort', 'sort'), + array('term', 'term'), + array('textPhrase', 'text_phrase'), + array('wildcard', 'wildcard'), + ); + } + + /** + * @dataProvider getQueryTypes + * + * @covers \Elastica\Query\Builder::fieldClose + * @covers \Elastica\Query\Builder::close + * + * @covers \Elastica\Query\Builder::bool + * @covers \Elastica\Query\Builder::boolClose + * @covers \Elastica\Query\Builder::constantScore + * @covers \Elastica\Query\Builder::constantScoreClose + * @covers \Elastica\Query\Builder::disMax + * @covers \Elastica\Query\Builder::disMaxClose + * @covers \Elastica\Query\Builder::facets + * @covers \Elastica\Query\Builder::facetsClose + * @covers \Elastica\Query\Builder::filter + * @covers \Elastica\Query\Builder::filterClose + * @covers \Elastica\Query\Builder::filteredQuery + * @covers \Elastica\Query\Builder::filteredQueryClose + * @covers \Elastica\Query\Builder::must + * @covers \Elastica\Query\Builder::mustClose + * @covers \Elastica\Query\Builder::mustNot + * @covers \Elastica\Query\Builder::mustNotClose + * @covers \Elastica\Query\Builder::prefix + * @covers \Elastica\Query\Builder::prefixClose + * @covers \Elastica\Query\Builder::query + * @covers \Elastica\Query\Builder::queryClose + * @covers \Elastica\Query\Builder::queryString + * @covers \Elastica\Query\Builder::queryStringClose + * @covers \Elastica\Query\Builder::range + * @covers \Elastica\Query\Builder::rangeClose + * @covers \Elastica\Query\Builder::should + * @covers \Elastica\Query\Builder::shouldClose + * @covers \Elastica\Query\Builder::sort + * @covers \Elastica\Query\Builder::sortClose + * @covers \Elastica\Query\Builder::term + * @covers \Elastica\Query\Builder::termClose + * @covers \Elastica\Query\Builder::textPhrase + * @covers \Elastica\Query\Builder::textPhraseClose + * @covers \Elastica\Query\Builder::wildcard + * @covers \Elastica\Query\Builder::wildcardClose + */ + public function testQueryTypes($method, $queryType) + { + $this->assertSame($this->builder, $this->builder->$method()); // open + $this->assertSame($this->builder, $this->builder->{$method."Close"}()); // close + $this->assertSame('{"' . $queryType . '":{}}', (string) $this->builder); + } + + /** + * @covers \Elastica\Query\Builder::fieldOpen + * @covers \Elastica\Query\Builder::fieldClose + * @covers \Elastica\Query\Builder::open + * @covers \Elastica\Query\Builder::close + */ + public function testFieldOpenAndClose() + { + $this->assertSame($this->builder, $this->builder->fieldOpen('someField')); + $this->assertSame($this->builder, $this->builder->fieldClose()); + $this->assertSame('{"someField":{}}', (string) $this->builder); + } + + /** + * @covers \Elastica\Query\Builder::sortField + */ + public function testSortField() + { + $this->assertSame($this->builder, $this->builder->sortField('name', true)); + $this->assertSame('{"sort":{"name":{"reverse":"true"}}}', (string) $this->builder); + } + + /** + * @covers \Elastica\Query\Builder::sortFields + */ + public function testSortFields() + { + $this->assertSame($this->builder, $this->builder->sortFields(array('field1' => 'asc', 'field2' => 'desc', 'field3' => 'asc'))); + $this->assertSame('{"sort":[{"field1":"asc"},{"field2":"desc"},{"field3":"asc"}]}', (string) $this->builder); + } + + /** + * @covers \Elastica\Query\Builder::queries + */ + public function testQueries() + { + $queries = array(); + + $b1 = clone $this->builder; + $b2 = clone $this->builder; + + $queries[] = $b1->term()->field('age', 34)->termClose(); + $queries[] = $b2->term()->field('name', 'christer')->termClose(); + + $this->assertSame($this->builder, $this->builder->queries($queries)); + $this->assertSame('{"queries":[{"term":{"age":"34"}},{"term":{"name":"christer"}}]}', (string) $this->builder); + } + + public function getFieldData() + { + return array( + array('name', 'value', '{"name":"value"}'), + array('name', true, '{"name":"true"}'), + array('name', false, '{"name":"false"}'), + array('name', array(1, 2, 3), '{"name":["1","2","3"]}'), + array('name', array('foo', 'bar', 'baz'), '{"name":["foo","bar","baz"]}'), + ); + } + + /** + * @dataProvider getFieldData + * @covers \Elastica\Query\Builder::field + */ + public function testField($name, $value, $result) + { + $this->assertSame($this->builder, $this->builder->field($name, $value)); + $this->assertSame($result, (string) $this->builder); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + * @covers \Elastica\Query\Builder::toArray + */ + public function testToArrayWithInvalidData() + { + $this->builder->open('foo'); + $this->builder->toArray(); + } + + /** + * @covers \Elastica\Query\Builder::toArray + */ + public function testToArray() + { + $this->builder->query()->term()->field('category.id', array(1, 2, 3))->termClose()->queryClose(); + $this->assertEquals(array( + 'query' => array( + 'term' => array( + 'category.id' => array(1, 2, 3) + ) + ) + ), $this->builder->toArray()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/CommonTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/CommonTest.php new file mode 100644 index 00000000..a84d6397 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/CommonTest.php @@ -0,0 +1,59 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Query\Common; +use Elastica\Test\Base as BaseTest; + +class CommonTest extends BaseTest +{ + public function testToArray() + { + $query = new Common('body', 'test query', .001); + $query->setLowFrequencyOperator(Common::OPERATOR_AND); + + $expected = array( + 'common' => array( + 'body' => array( + 'query' => 'test query', + 'cutoff_frequency' => .001, + 'low_freq_operator' => 'and' + ) + ) + ); + + $this->assertEquals($expected, $query->toArray()); + } + + public function testQuery() + { + $index = $this->_createIndex('common_test'); + $type = $index->getType('test'); + + //add documents to create common terms + $docs = array(); + for ($i = 0; $i < 20; $i++) { + $docs[] = new \Elastica\Document($i, array('body' => 'foo bar')); + } + $type->addDocuments($docs); + + $type->addDocument(new \Elastica\Document(20, array('body' => 'foo baz'))); + $type->addDocument(new \Elastica\Document(21, array('body' => 'foo bar baz'))); + $type->addDocument(new \Elastica\Document(22, array('body' => 'foo bar baz bat'))); + $index->refresh(); + + $query = new Common('body', 'foo bar baz bat', .5); + $results = $type->search($query)->getResults(); + + //documents containing only common words should not be returned + $this->assertEquals(3, sizeof($results)); + + $query->setMinimumShouldMatch(2); + $results = $type->search($query); + + //only the document containing both low frequency terms should match + $this->assertEquals(1, $results->count()); + + $index->delete(); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/ConstantScoreTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/ConstantScoreTest.php new file mode 100644 index 00000000..27143eb6 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/ConstantScoreTest.php @@ -0,0 +1,158 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Filter\Term; +use Elastica\Filter\Ids; +use Elastica\Query\ConstantScore; +use Elastica\Query\MatchAll; +use Elastica\Test\Base as BaseTest; +use Elastica\Index; +use Elastica\Document; +use Elastica\Type; + +class ConstantScoreTest extends BaseTest +{ + public function dataProviderSampleQueries() + { + return array( + array( + new Term(array('foo', 'bar')), + array( + 'constant_score' => array( + 'filter' => array( + 'term' => array( + 'foo', + 'bar', + ), + ), + ), + ), + ), + array( + array( + 'and' => array( + array( + 'query' => array( + 'query_string' => array( + 'query' => 'foo', + 'default_field' => 'something', + ), + ), + ), + array( + 'query' => array( + 'query_string' => array( + 'query' => 'bar', + 'default_field' => 'something', + ), + ), + ), + ), + ), + '{"constant_score":{"filter":{"and":[{"query":{"query_string":{"query":"foo","default_field":"something"}}},{"query":{"query_string":{"query":"bar","default_field":"something"}}}]}}}', + ), + ); + } + /** + * @dataProvider dataProviderSampleQueries + */ + public function testSimple($filter, $expected) + { + $query = new ConstantScore(); + $query->setFilter($filter); + if (is_string($expected)) { + $expected = json_decode($expected, true); + } + $this->assertEquals($expected, $query->toArray()); + } + + public function testToArray() + { + $query = new ConstantScore(); + + $boost = 1.2; + $filter = new Ids(); + $filter->setIds(array(1)); + + $query->setFilter($filter); + $query->setBoost($boost); + + $expectedArray = array( + 'constant_score' => array( + 'filter' => $filter->toArray(), + 'boost' => $boost + ) + ); + + $this->assertEquals($expectedArray, $query->toArray()); + } + + public function testConstruct() + { + $filter = new Ids(); + $filter->setIds(array(1)); + + $query = new ConstantScore($filter); + + $expectedArray = array( + 'constant_score' => array( + 'filter' => $filter->toArray(), + ) + ); + + $this->assertEquals($expectedArray, $query->toArray()); + + } + + public function testQuery() + { + + $client = $this->_getClient(); + $index = new Index($client, 'test'); + $index->create(array(), true); + + $type = new Type($index, 'constant_score'); + + $doc = new Document(1, array('id' => 1, 'email' => 'hans@test.com', 'username' => 'hans')); + $type->addDocument($doc); + $doc = new Document(2, array('id' => 2, 'email' => 'emil@test.com', 'username' => 'emil')); + $type->addDocument($doc); + $doc = new Document(3, array('id' => 3, 'email' => 'ruth@test.com', 'username' => 'ruth')); + $type->addDocument($doc); + + // Refresh index + $index->refresh(); + + $boost = 1.3; + $query_match = new MatchAll(); + + $query = new ConstantScore(); + $query->setQuery($query_match); + $query->setBoost($boost); + + $expectedArray = array( + 'constant_score' => array( + 'query' => $query_match->toArray(), + 'boost' => $boost + ) + ); + + $this->assertEquals($expectedArray, $query->toArray()); + $resultSet = $type->search($query); + + $results = $resultSet->getResults(); + + $this->assertEquals($resultSet->count(), 3); + $this->assertEquals($results[1]->getScore(), 1); + + } + + public function testConstructEmpty() + { + $query = new ConstantScore(); + $expectedArray = array('constant_score' => array()); + + $this->assertEquals($expectedArray, $query->toArray()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/DisMaxTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/DisMaxTest.php new file mode 100644 index 00000000..31c8437d --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/DisMaxTest.php @@ -0,0 +1,83 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Query\DisMax; +use Elastica\Query\Ids; +use Elastica\Query\QueryString; +use Elastica\Test\Base as BaseTest; + +class DisMaxTest extends BaseTest +{ + public function testToArray() + { + $query = new DisMax(); + + $idsQuery1 = new Ids(); + $idsQuery1->setIds(1); + + $idsQuery2 = new Ids(); + $idsQuery2->setIds(2); + + $idsQuery3 = new Ids(); + $idsQuery3->setIds(3); + + $boost = 1.2; + $tieBreaker = 2; + + $query->setBoost($boost); + $query->setTieBreaker($tieBreaker); + $query->addQuery($idsQuery1); + $query->addQuery($idsQuery2); + $query->addQuery($idsQuery3->toArray()); + + $expectedArray = array( + 'dis_max' => array( + 'tie_breaker' => $tieBreaker, + 'boost' => $boost, + 'queries' => array( + $idsQuery1->toArray(), + $idsQuery2->toArray(), + $idsQuery3->toArray() + ) + ) + ); + + $this->assertEquals($expectedArray, $query->toArray()); + } + + public function testQuery() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('test'); + + $doc = new Document(1, array('name' => 'Basel-Stadt')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'New York')); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'Baden')); + $type->addDocument($doc); + $doc = new Document(4, array('name' => 'Baden Baden')); + $type->addDocument($doc); + + $index->refresh(); + + $queryString1 = new QueryString('Bade*'); + $queryString2 = new QueryString('Base*'); + + $boost = 1.2; + $tieBreaker = 2; + + $query = new DisMax(); + $query->setBoost($boost); + $query->setTieBreaker($tieBreaker); + $query->addQuery($queryString1); + $query->addQuery($queryString2); + $resultSet = $type->search($query); + + $this->assertEquals(3, $resultSet->count()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/FilteredTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/FilteredTest.php new file mode 100644 index 00000000..c6bd9096 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/FilteredTest.php @@ -0,0 +1,112 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Filter\Term; +use Elastica\Query\Filtered; +use Elastica\Query\QueryString; +use Elastica\Test\Base as BaseTest; + +class FilteredTest extends BaseTest +{ + public function testFilteredSearch() + { + $index = $this->_createIndex(); + $type = $index->getType('helloworld'); + + $doc = new Document(1, array('id' => 1, 'email' => 'test@test.com', 'username' => 'hanswurst', 'test' => array('2', '3', '5'))); + $type->addDocument($doc); + $doc = new Document(2, array('id' => 2, 'email' => 'test@test.com', 'username' => 'peter', 'test' => array('2', '3', '5'))); + $type->addDocument($doc); + + $queryString = new QueryString('test*'); + + $filter1 = new Term(); + $filter1->setTerm('username', 'peter'); + + $filter2 = new Term(); + $filter2->setTerm('username', 'qwerqwer'); + + $query1 = new Filtered($queryString, $filter1); + $query2 = new Filtered($queryString, $filter2); + $index->refresh(); + + $resultSet = $type->search($queryString); + $this->assertEquals(2, $resultSet->count()); + + $resultSet = $type->search($query1); + $this->assertEquals(1, $resultSet->count()); + + $resultSet = $type->search($query2); + $this->assertEquals(0, $resultSet->count()); + } + + public function testFilteredGetter() + { + $queryString = new QueryString('test*'); + + $filter1 = new Term(); + $filter1->setTerm('username', 'peter'); + + $filter2 = new Term(); + $filter2->setTerm('username', 'qwerqwer'); + + $query1 = new Filtered($queryString, $filter1); + $query2 = new Filtered($queryString, $filter2); + + $this->assertEquals($query1->getQuery(), $queryString); + $this->assertEquals($query2->getQuery(), $queryString); + $this->assertEquals($query1->getFilter(), $filter1); + $this->assertEquals($query2->getFilter(), $filter2); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testFilteredWithoutArgumentsShouldRaiseException() + { + $query = new Filtered(); + $query->toArray(); + } + + public function testFilteredSearchNoQuery() + { + $index = $this->_createIndex(); + $type = $index->getType('helloworld'); + + $doc = new Document(1, array('id' => 1, 'email' => 'test@test.com', 'username' => 'hanswurst', 'test' => array('2', '3', '5'))); + $type->addDocument($doc); + $doc = new Document(2, array('id' => 2, 'email' => 'test@test.com', 'username' => 'peter', 'test' => array('2', '3', '5'))); + $type->addDocument($doc); + + $filter = new Term(); + $filter->setTerm('username', 'peter'); + + $query = new Filtered(null, $filter); + $index->refresh(); + + $resultSet = $type->search($query); + $this->assertEquals(1, $resultSet->count()); + } + + public function testFilteredSearchNoFilter() + { + $index = $this->_createIndex(); + $type = $index->getType('helloworld'); + + $doc = new Document(1, array('id' => 1, 'email' => 'test@test.com', 'username' => 'hanswurst', 'test' => array('2', '3', '5'))); + $type->addDocument($doc); + $doc = new Document(2, array('id' => 2, 'email' => 'test@test.com', 'username' => 'peter', 'test' => array('2', '3', '5'))); + $type->addDocument($doc); + + $queryString = new QueryString('hans*'); + + $query = new Filtered($queryString); + $index->refresh(); + + $resultSet = $type->search($query); + $this->assertEquals(1, $resultSet->count()); + } + +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/FunctionScoreTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/FunctionScoreTest.php new file mode 100644 index 00000000..47d9dd2c --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/FunctionScoreTest.php @@ -0,0 +1,210 @@ +<?php +/** + * User: Joe Linn + * Date: 9/16/13 + * Time: 5:05 PM + */ + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Filter\Term; +use Elastica\Query\FunctionScore; +use Elastica\Script; +use Elastica\Test\Base as BaseTest; + +class FunctionScoreTest extends BaseTest +{ + /** + * @var \Elastica\Index + */ + protected $index; + + /** + * @var \Elastica\Type + */ + protected $type; + + protected $locationOrigin = "32.804654, -117.242594"; + + protected function setUp() + { + parent::setUp(); + $this->index = $this->_createIndex('test_functionscore'); + $this->type = $this->index->getType('test'); + $this->type->setMapping(array( + 'name' => array('type' => 'string', 'index' => 'not_analyzed'), + 'location' => array('type' => 'geo_point'), + 'price' => array('type' => 'float') + )); + + $this->type->addDocument(new Document(1, array( + 'name' => "Mr. Frostie's", + 'location' => array('lat' => 32.799605, 'lon' => -117.243027), + 'price' => 4.5 + ))); + $this->type->addDocument(new Document(2, array( + 'name' => "Miller's Field", + 'location' => array('lat' => 32.795964, 'lon' => -117.255028), + 'price' => 9.5 + ))); + + $this->index->refresh(); + } + + protected function tearDown() + { + $this->index->delete(); + parent::tearDown(); + } + + public function testToArray() + { + $priceOrigin = 0; + $locationScale = '2mi'; + $priceScale = 9.25; + $query = new FunctionScore(); + $childQuery = new \Elastica\Query\MatchAll(); + $query->setQuery($childQuery); + $query->addDecayFunction(FunctionScore::DECAY_GAUSS, 'location', $this->locationOrigin, $locationScale); + $query->addDecayFunction(FunctionScore::DECAY_GAUSS, 'price', $priceOrigin, $priceScale); + $expected = array( + 'function_score' => array( + 'query' => $childQuery->toArray(), + 'functions' => array( + array( + 'gauss' => array( + 'location' => array( + 'origin' => $this->locationOrigin, + 'scale' => $locationScale + ) + ) + ), + array( + 'gauss' => array( + 'price' => array( + 'origin' => $priceOrigin, + 'scale' => $priceScale + ) + ) + ) + ) + ) + ); + $this->assertEquals($expected, $query->toArray()); + } + + public function testGauss() + { + $query = new FunctionScore(); + $query->addDecayFunction(FunctionScore::DECAY_GAUSS, 'location', $this->locationOrigin, "4mi"); + $query->addDecayFunction(FunctionScore::DECAY_GAUSS, 'price', 0, 10); + $response = $this->type->search($query); + $results = $response->getResults(); + + // the document with the closest location and lowest price should be scored highest + $result0 = $results[0]->getData(); + $this->assertEquals("Mr. Frostie's", $result0['name']); + } + + public function testBoostFactor() + { + $filter = new Term(array('price' => 4.5)); + $query = new FunctionScore(); + $query->addBoostFactorFunction(5.0, $filter); + $expected = array( + 'function_score' => array( + 'functions' => array( + array( + 'boost_factor' => 5.0, + 'filter' => array( + 'term' => array( + 'price' => 4.5 + ) + ) + ) + ) + ) + ); + + $this->assertEquals($expected, $query->toArray()); + + $response = $this->type->search($query); + $results = $response->getResults(); + + // the document with price = 4.5 should be scored highest + $result0 = $results[0]->getData(); + $this->assertEquals("Mr. Frostie's", $result0['name']); + } + + public function testRandomScore() + { + $filter = new Term(array('price' => 4.5)); + $query = new FunctionScore(); + $query->addRandomScoreFunction(2, $filter); + $expected = array( + 'function_score' => array( + 'functions' => array( + array( + 'random_score' => array( + 'seed' => 2 + ), + 'filter' => array( + 'term' => array( + 'price' => 4.5 + ) + ) + ) + ) + ) + ); + + $this->assertEquals($expected, $query->toArray()); + + $response = $this->type->search($query); + $results = $response->getResults(); + + // the document with the random score should have a score > 1, means it is the first result + $result0 = $results[1]->getData(); + + $this->assertEquals("Miller's Field", $result0['name']); + } + + public function testRandomScoreWithoutSeed() + { + $query = new FunctionScore(); + $query->setRandomScore(); + + $response = $this->type->search($query); + + $this->assertEquals(2, $response->count()); + } + + public function testScriptScore() + { + $scriptString = "_score * doc['price'].value"; + $script = new Script($scriptString); + $query = new FunctionScore(); + $query->addScriptScoreFunction($script); + $expected = array( + 'function_score' => array( + 'functions' => array( + array( + 'script_score' => array( + 'script' => $scriptString + ) + ) + ) + ) + ); + + $this->assertEquals($expected, $query->toArray()); + + $response = $this->type->search($query); + $results = $response->getResults(); + + // the document the highest price should be scored highest + $result0 = $results[0]->getData(); + $this->assertEquals("Miller's Field", $result0['name']); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/FuzzyLikeThisTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/FuzzyLikeThisTest.php new file mode 100644 index 00000000..c842c1a8 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/FuzzyLikeThisTest.php @@ -0,0 +1,228 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Index; +use Elastica\Query\FuzzyLikeThis; +use Elastica\Type; +use Elastica\Type\Mapping; +use Elastica\Test\Base as BaseTest; + +class FuzzyLikeThisTest extends BaseTest +{ + public function testSearch() + { + $client = $this->_getClient(); + $index = new Index($client, 'test'); + $index->create(array(), true); + $index->getSettings()->setNumberOfReplicas(0); + //$index->getSettings()->setNumberOfShards(1); + + $type = new Type($index, 'helloworldfuzzy'); + $mapping = new Mapping($type , array( + 'email' => array('store' => 'yes', 'type' => 'string', 'index' => 'analyzed'), + 'content' => array('store' => 'yes', 'type' => 'string', 'index' => 'analyzed'), + )); + + $mapping->setSource(array('enabled' => false)); + $type->setMapping($mapping); + + $doc = new Document(1000, array('email' => 'testemail@gmail.com', 'content' => 'This is a sample post. Hello World Fuzzy Like This!')); + $type->addDocument($doc); + + // Refresh index + $index->refresh(); + + $fltQuery = new FuzzyLikeThis(); + $fltQuery->setLikeText("sample gmail"); + $fltQuery->addFields(array("email","content")); + $fltQuery->setMinSimilarity(0.3); + $fltQuery->setMaxQueryTerms(3); + $resultSet = $type->search($fltQuery); + $this->assertEquals(1, $resultSet->count()); + } + + public function testSetPrefixLength() + { + $query = new FuzzyLikeThis(); + + $length = 3; + $query->setPrefixLength($length); + + $data = $query->toArray(); + + $this->assertEquals($length, $data['fuzzy_like_this']['prefix_length']); + } + + public function testAddFields() + { + $query = new FuzzyLikeThis(); + + $fields = array('test1', 'test2'); + $query->addFields($fields); + + $data = $query->toArray(); + + $this->assertEquals($fields, $data['fuzzy_like_this']['fields']); + } + + public function testSetLikeText() + { + $query = new FuzzyLikeThis(); + + $text = ' hello world'; + $query->setLikeText($text); + + $data = $query->toArray(); + + $this->assertEquals(trim($text), $data['fuzzy_like_this']['like_text']); + } + + public function testSetIgnoreTF() + { + $query = new FuzzyLikeThis(); + + $ignoreTF = false; + $query->setIgnoreTF($ignoreTF); + $data = $query->toArray(); + $this->assertEquals($ignoreTF, $data['fuzzy_like_this']['ignore_tf']); + + $ignoreTF = true; + $query->setIgnoreTF($ignoreTF); + $data = $query->toArray(); + $this->assertEquals($ignoreTF, $data['fuzzy_like_this']['ignore_tf']); + } + + public function testSetIgnoreTFDefault() + { + $query = new FuzzyLikeThis(); + + $data = $query->toArray(); + + $defaultIgnoreTF = false; + $this->assertEquals($defaultIgnoreTF, $data['fuzzy_like_this']['ignore_tf']); + } + + public function testSetMinSimilarity() + { + $query = new FuzzyLikeThis(); + + $similarity = 2; + $query->setMinSimilarity($similarity); + + $data = $query->toArray(); + + $this->assertEquals($similarity, $data['fuzzy_like_this']['min_similarity']); + } + + public function testSetBoost() + { + $query = new FuzzyLikeThis(); + + $boost = 2.2; + $query->setBoost($boost); + + $data = $query->toArray(); + + $this->assertEquals($boost, $data['fuzzy_like_this']['boost']); + } + + public function testAddAnalyzerViasetParam() + { + $analyzer = 'snowball'; + + $query = new FuzzyLikeThis(); + $query->setParam('analyzer', $analyzer); + + $data = $query->toArray(); + $this->assertEquals($analyzer, $data['fuzzy_like_this']['analyzer']); + } + + public function testSetAnalyzer() + { + $analyzer = 'snowball'; + + $query = new FuzzyLikeThis(); + $query->setAnalyzer($analyzer); + + $data = $query->toArray(); + $this->assertEquals($analyzer, $data['fuzzy_like_this']['analyzer']); + } + + public function testAnalyzerNotPresentInArrayToMaintainDefaultOfField() + { + $query = new FuzzyLikeThis(); + + $data = $query->toArray(); + $this->assertArrayNotHasKey('analyzer', $data); + } + + public function testArgArrayFieldsOverwrittenBySetParams() + { + $query = new FuzzyLikeThis(); + $query->setMaxQueryTerms(100); + $query->setParam('max_query_terms', 200); + + $data = $query->toArray(); + $this->assertEquals(200, $data['fuzzy_like_this']['max_query_terms']); + } + + public function testSearchSetAnalyzer() + { + $client = $this->_getClient(); + $index = new Index($client, 'test'); + $index->create(array('analysis' => array( + 'analyzer' => array( + 'searchAnalyzer' => array( + 'type' => 'custom', + 'tokenizer' => 'standard', + 'filter' => array('myStopWords') + ) + ), + 'filter' => array( + 'myStopWords' => array( + 'type' => 'stop', + 'stopwords' => array('The') + ) + ) + )), true); + + $index->getSettings()->setNumberOfReplicas(0); + //$index->getSettings()->setNumberOfShards(1); + + $type = new Type($index, 'helloworldfuzzy'); + $mapping = new Mapping($type , array( + 'email' => array('store' => 'yes', 'type' => 'string', 'index' => 'analyzed'), + 'content' => array('store' => 'yes', 'type' => 'string', 'index' => 'analyzed'), + )); + + $mapping->setSource(array('enabled' => false)); + $type->setMapping($mapping); + + $doc = new Document(1000, array('email' => 'testemail@gmail.com', 'content' => 'The Fuzzy Test!')); + $type->addDocument($doc); + + $doc = new Document(1001, array('email' => 'testemail@gmail.com', 'content' => 'Elastica Fuzzy Test')); + $type->addDocument($doc); + + // Refresh index + $index->refresh(); + + $fltQuery = new FuzzyLikeThis(); + $fltQuery->addFields(array("email","content")); + $fltQuery->setLikeText("The"); + + $fltQuery->setMinSimilarity(0.1); + $fltQuery->setMaxQueryTerms(3); + + // Test before analyzer applied, should return 1 result + $resultSet = $type->search($fltQuery); + $this->assertEquals(1, $resultSet->count()); + + $fltQuery->setParam('analyzer', 'searchAnalyzer'); + + $resultSet = $type->search($fltQuery); + $this->assertEquals(0, $resultSet->count()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/FuzzyTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/FuzzyTest.php new file mode 100644 index 00000000..57659293 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/FuzzyTest.php @@ -0,0 +1,129 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Query\Fuzzy; +use Elastica\Test\Base as BaseTest; + +class FuzzyTest extends BaseTest +{ + public function testToArray() + { + $fuzzy = new Fuzzy(); + $fuzzy->addField('user', array('value' => 'Nicolas', 'boost' => 1.0)); + $expectedArray = array( + 'fuzzy' => array( + 'user' => array( + 'value' => 'Nicolas', + 'boost' => 1.0 + ) + ) + ); + $this->assertEquals($expectedArray, $fuzzy->toArray(), 'Deprecated method failed'); + + $fuzzy = new Fuzzy('user', 'Nicolas'); + $expectedArray = array( + 'fuzzy' => array( + 'user' => array( + 'value' => 'Nicolas', + ) + ) + ); + $this->assertEquals($expectedArray, $fuzzy->toArray()); + + $fuzzy = new Fuzzy(); + $fuzzy->setField('user', 'Nicolas')->setFieldOption('boost', 1.0); + $expectedArray = array( + 'fuzzy' => array( + 'user' => array( + 'value' => 'Nicolas', + 'boost' => 1.0 + ) + ) + ); + $this->assertEquals($expectedArray, $fuzzy->toArray()); + } + + public function testQuery() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('test'); + + $doc = new Document(1, array('name' => 'Basel-Stadt')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'New York')); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'Baden')); + $type->addDocument($doc); + $doc = new Document(4, array('name' => 'Baden Baden')); + $type->addDocument($doc); + + $index->refresh(); + + $field = 'name'; + + $query = new Fuzzy(); + $query->setField($field, 'Baden'); + + $resultSet = $index->search($query); + + $this->assertEquals(2, $resultSet->count()); + } + + public function testBadArguments () + { + $this->setExpectedException('Elastica\Exception\InvalidException'); + $query = new Fuzzy(); + $query->addField('name', array(array('value' => 'Baden'))); + + $this->setExpectedException('Elastica\Exception\InvalidException'); + $query = new Fuzzy(); + $query->setField('name', array()); + + $this->setExpectedException('Elastica\Exception\InvalidException'); + $query = new Fuzzy(); + $query->setField('name', 'value'); + $query->setField('name1', 'value1'); + } + + public function testFuzzyWithFacets() { + + $index = $this->_createIndex(); + $type = $index->getType('test'); + + $doc = new Document(1, array('name' => 'Basel-Stadt')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'New York')); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'Baden')); + $type->addDocument($doc); + $doc = new Document(4, array('name' => 'Baden Baden')); + $type->addDocument($doc); + + $index->refresh(); + + $field = 'name'; + + $fuzzyQuery = new Fuzzy(); + $fuzzyQuery->setField($field, 'Baden'); + + $facet = new \Elastica\Facet\Terms('test'); + $facet->setField('name'); + + $query = new \Elastica\Query($fuzzyQuery); + $query->addFacet($facet); + + $resultSet = $index->search($query); + + // Assert query worked ok + $this->assertEquals(2, $resultSet->count()); + + // Check Facets + $this->assertTrue($resultSet->hasFacets()); + $facets = $resultSet->getFacets(); + $this->assertEquals(2, $facets['test']['total']); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/HasChildTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/HasChildTest.php new file mode 100644 index 00000000..bb1b5b96 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/HasChildTest.php @@ -0,0 +1,107 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Query\HasChild; +use Elastica\Query\MatchAll; +use Elastica\Test\Base as BaseTest; + +class HasChildTest extends BaseTest +{ + public function testToArray() + { + $q = new MatchAll(); + + $type = 'test'; + + $query = new HasChild($q, $type); + + $expectedArray = array( + 'has_child' => array( + 'query' => $q->toArray(), + 'type' => $type + ) + ); + + $this->assertEquals($expectedArray, $query->toArray()); + } + + public function testSetScope() + { + $q = new MatchAll(); + + $type = 'test'; + + $scope = 'foo'; + + $query = new HasChild($q, $type); + $query->setScope($scope); + + $expectedArray = array( + 'has_child' => array( + 'query' => $q->toArray(), + 'type' => $type, + '_scope' => $scope + ) + ); + + $this->assertEquals($expectedArray, $query->toArray()); + } + + public function testTypeInsideHasChildSearch() + { + $index = $this->prepareSearchData(); + + $f = new \Elastica\Query\Match(); + $f->setField('alt.name', 'testname'); + $query = new HasChild($f, 'child'); + + $searchQuery = new \Elastica\Query(); + $searchQuery->setQuery($query); + $searchResults = $index->search($searchQuery); + + $this->assertEquals(1, $searchResults->count()); + + $result = $searchResults->current()->getData(); + $expected = array('id' => 'parent2', 'user' => 'parent2', 'email' => 'parent2@test.com'); + + $this->assertEquals($expected, $result); + } + + private function prepareSearchData() + { + $client = $this->_getClient(); + $index = $client->getIndex('has_child_test'); + $index->create(array(), true); + + $parentType = $index->getType('parent'); + + $childType = $index->getType('child'); + $childMapping = new \Elastica\Type\Mapping($childType); + $childMapping->setParent('parent'); + $childMapping->send(); + + $altType = $index->getType('alt'); + $altDoc = new Document('alt1', array('name' => 'altname')); + $altType->addDocument($altDoc); + + $parent1 = new Document('parent1', array('id' => 'parent1', 'user' => 'parent1', 'email' => 'parent1@test.com')); + $parentType->addDocument($parent1); + $parent2 = new Document('parent2', array('id' => 'parent2', 'user' => 'parent2', 'email' => 'parent2@test.com')); + $parentType->addDocument($parent2); + + $child1 = new Document('child1', array('id' => 'child1', 'user' => 'child1', 'email' => 'child1@test.com')); + $child1->setParent('parent1'); + $childType->addDocument($child1); + $child2 = new Document('child2', array('id' => 'child2', 'user' => 'child2', 'email' => 'child2@test.com')); + $child2->setParent('parent2'); + $childType->addDocument($child2); + $child3 = new Document('child3', array('id' => 'child3', 'user' => 'child3', 'email' => 'child3@test.com', 'alt' => array(array('name' => 'testname')))); + $child3->setParent('parent2'); + $childType->addDocument($child3); + + $index->refresh(); + return $index; + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/HasParentTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/HasParentTest.php new file mode 100644 index 00000000..d417c887 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/HasParentTest.php @@ -0,0 +1,50 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Query\HasParent; +use Elastica\Query\MatchAll; +use Elastica\Test\Base as BaseTest; + +class HasParentTest extends BaseTest +{ + public function testToArray() + { + $q = new MatchAll(); + + $type = 'test'; + + $query = new HasParent($q, $type); + + $expectedArray = array( + 'has_parent' => array( + 'query' => $q->toArray(), + 'type' => $type + ) + ); + + $this->assertEquals($expectedArray, $query->toArray()); + } + + public function testSetScope() + { + $q = new MatchAll(); + + $type = 'test'; + + $scope = 'foo'; + + $query = new HasParent($q, $type); + $query->setScope($scope); + + $expectedArray = array( + 'has_parent' => array( + 'query' => $q->toArray(), + 'type' => $type, + '_scope' => $scope + ) + ); + + $this->assertEquals($expectedArray, $query->toArray()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/HighlightTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/HighlightTest.php new file mode 100644 index 00000000..4b1b6c5e --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/HighlightTest.php @@ -0,0 +1,49 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Query; +use Elastica\Query\QueryString; +use Elastica\Test\Base as BaseTest; + +class HighlightTest extends BaseTest +{ + public function testHightlightSearch() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('helloworld'); + + $phrase = 'My name is ruflin'; + + $doc = new Document(1, array('id' => 1, 'phrase' => $phrase, 'username' => 'hanswurst', 'test' => array('2', '3', '5'))); + $type->addDocument($doc); + $doc = new Document(2, array('id' => 2, 'phrase' => $phrase, 'username' => 'peter', 'test' => array('2', '3', '5'))); + $type->addDocument($doc); + + $queryString = new QueryString('rufl*'); + $query = new Query($queryString); + $query->setHighlight(array( + 'pre_tags' => array('<em class="highlight">'), + 'post_tags' => array('</em>'), + 'fields' => array( + 'phrase' => array( + 'fragment_size' => 200, + 'number_of_fragments' => 1, + ), + ), + )); + + $index->refresh(); + + $resultSet = $type->search($query); + foreach ($resultSet as $result) { + $highlight = $result->getHighlights(); + $this->assertEquals(array('phrase' => array(0 => 'My name is <em class="highlight">ruflin</em>')), $highlight); + } + $this->assertEquals(2, $resultSet->count()); + + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/IdsTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/IdsTest.php new file mode 100644 index 00000000..d1bf901e --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/IdsTest.php @@ -0,0 +1,165 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Query\Ids; +use Elastica\Test\Base as BaseTest; + +class IdsTest extends BaseTest +{ + protected $_index; + protected $_type; + + public function setUp() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + + $type1 = $index->getType('helloworld1'); + $type2 = $index->getType('helloworld2'); + + $doc = new Document(1, array('name' => 'hello world')); + $type1->addDocument($doc); + + $doc = new Document(2, array('name' => 'nicolas ruflin')); + $type1->addDocument($doc); + + $doc = new Document(3, array('name' => 'ruflin')); + $type1->addDocument($doc); + + $doc = new Document(4, array('name' => 'hello world again')); + $type2->addDocument($doc); + + $index->refresh(); + + $this->_type = $type1; + $this->_index = $index; + } + + public function tearDown() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->delete(); + } + + public function testSetIdsSearchSingle() + { + $query = new Ids(); + $query->setIds('1'); + + $resultSet = $this->_type->search($query); + + $this->assertEquals(1, $resultSet->count()); + } + + public function testSetIdsSearchArray() + { + $query = new Ids(); + $query->setIds(array('1', '2')); + + $resultSet = $this->_type->search($query); + + $this->assertEquals(2, $resultSet->count()); + } + + public function testAddIdsSearchSingle() + { + $query = new Ids(); + $query->addId('3'); + + $resultSet = $this->_type->search($query); + + $this->assertEquals(1, $resultSet->count()); + } + + public function testComboIdsSearchArray() + { + $query = new Ids(); + + $query->setIds(array('1', '2')); + $query->addId('3'); + + $resultSet = $this->_type->search($query); + + $this->assertEquals(3, $resultSet->count()); + } + + public function testSetTypeSingleSearchSingle() + { + $query = new Ids(); + + $query->setIds('1'); + $query->setType('helloworld1'); + + $resultSet = $this->_index->search($query); + + $this->assertEquals(1, $resultSet->count()); + } + + public function testSetTypeSingleSearchArray() + { + $query = new Ids(); + + $query->setIds(array('1', '2')); + $query->setType('helloworld1'); + + $resultSet = $this->_index->search($query); + + $this->assertEquals(2, $resultSet->count()); + } + + public function testSetTypeSingleSearchSingleDocInOtherType() + { + $query = new Ids(); + + // Doc 4 is in the second type... + $query->setIds('4'); + $query->setType('helloworld1'); + + $resultSet = $this->_index->search($query); + + // ...therefore 0 results should be returned + $this->assertEquals(0, $resultSet->count()); + } + + public function testSetTypeSingleSearchArrayDocInOtherType() + { + $query = new Ids(); + + // Doc 4 is in the second type... + $query->setIds(array('1', '4')); + $query->setType('helloworld1'); + + $resultSet = $this->_index->search($query); + + // ...therefore only 1 result should be returned + $this->assertEquals(1, $resultSet->count()); + } + + public function testSetTypeArraySearchArray() + { + $query = new Ids(); + + $query->setIds(array('1', '4')); + $query->setType(array('helloworld1', 'helloworld2')); + + $resultSet = $this->_index->search($query); + + $this->assertEquals(2, $resultSet->count()); + } + + public function testSetTypeArraySearchSingle() + { + $query = new Ids(); + + $query->setIds('4'); + $query->setType(array('helloworld1', 'helloworld2')); + + $resultSet = $this->_index->search($query); + + $this->assertEquals(1, $resultSet->count()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/MatchAllTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/MatchAllTest.php new file mode 100644 index 00000000..3731e659 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/MatchAllTest.php @@ -0,0 +1,44 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Query\MatchAll; +use Elastica\Search; +use Elastica\Test\Base as BaseTest; + +class MatchAllTest extends BaseTest +{ + public function testToArray() + { + $query = new MatchAll(); + + $expectedArray = array('match_all' => new \stdClass()); + + $this->assertEquals($expectedArray, $query->toArray()); + } + + public function testMatchAllIndicesTypes() + { + $index1 = $this->_createIndex('test1'); + $index2 = $this->_createIndex('test2'); + + $client = $index1->getClient(); + + $search1 = new Search($client); + $resultSet1 = $search1->search(new MatchAll()); + + $doc1 = new Document(1, array('name' => 'ruflin')); + $doc2 = new Document(1, array('name' => 'ruflin')); + $index1->getType('test')->addDocument($doc1); + $index2->getType('test')->addDocument($doc2); + + $index1->refresh(); + $index2->refresh(); + + $search2 = new Search($client); + $resultSet2 = $search2->search(new MatchAll()); + + $this->assertEquals($resultSet1->getTotalHits() + 2, $resultSet2->getTotalHits()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/MatchTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/MatchTest.php new file mode 100644 index 00000000..ed164663 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/MatchTest.php @@ -0,0 +1,187 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Query\Match; +use Elastica\Test\Base as BaseTest; + +class MatchTest extends BaseTest +{ + public function testToArray() + { + $field = 'test'; + $testQuery = 'Nicolas Ruflin'; + $type = 'phrase'; + $operator = 'and'; + $analyzer = 'myanalyzer'; + $boost = 2.0; + $minimumShouldMatch = 2; + $fuzziness = 0.3; + $fuzzyRewrite = 'constant_score_boolean'; + $prefixLength = 3; + $maxExpansions = 12; + + $query = new Match(); + $query->setFieldQuery($field, $testQuery); + $query->setFieldType($field, $type); + $query->setFieldOperator($field, $operator); + $query->setFieldAnalyzer($field, $analyzer); + $query->setFieldBoost($field, $boost); + $query->setFieldMinimumShouldMatch($field, $minimumShouldMatch); + $query->setFieldFuzziness($field, $fuzziness); + $query->setFieldFuzzyRewrite($field, $fuzzyRewrite); + $query->setFieldPrefixLength($field, $prefixLength); + $query->setFieldMaxExpansions($field, $maxExpansions); + + $expectedArray = array( + 'match' => array( + $field => array( + 'query' => $testQuery, + 'type' => $type, + 'operator' => $operator, + 'analyzer' => $analyzer, + 'boost' => $boost, + 'minimum_should_match' => $minimumShouldMatch, + 'fuzziness' => $fuzziness, + 'fuzzy_rewrite' => $fuzzyRewrite, + 'prefix_length' => $prefixLength, + 'max_expansions' => $maxExpansions + ) + ) + ); + + $this->assertEquals($expectedArray, $query->toArray()); + } + + public function testMatch() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('test'); + + $doc = new Document(1, array('name' => 'Basel-Stadt')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'New York')); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'New Hampshire')); + $type->addDocument($doc); + $doc = new Document(4, array('name' => 'Basel Land')); + $type->addDocument($doc); + + $index->refresh(); + + $field = 'name'; + $operator = 'or'; + + $query = new Match(); + $query->setFieldQuery($field, 'Basel New'); + $query->setFieldOperator($field, $operator); + + $resultSet = $index->search($query); + + $this->assertEquals(4, $resultSet->count()); + } + + public function testMatchZeroTerm() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('test'); + $doc = new Document(1, array('name' => 'Basel-Stadt')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'New York')); + $type->addDocument($doc); + $index->refresh(); + + $query = new Match(); + $query->setFieldQuery('name', ''); + $query->setFieldZeroTermsQuery('name', Match::ZERO_TERM_ALL); + + $resultSet = $index->search($query); + + $this->assertEquals(2, $resultSet->count()); + } + + public function testMatchPhrase() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('test'); + + $doc = new Document(1, array('name' => 'Basel-Stadt')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'New York')); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'New Hampshire')); + $type->addDocument($doc); + $doc = new Document(4, array('name' => 'Basel Land')); + $type->addDocument($doc); + + $index->refresh(); + + $field = 'name'; + $type = 'phrase'; + + $query = new Match(); + $query->setFieldQuery($field, 'New York'); + $query->setFieldType($field, $type); + + $resultSet = $index->search($query); + + $this->assertEquals(1, $resultSet->count()); + } + + public function testMatchPhrasePrefix() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('test'); + + $doc = new Document(1, array('name' => 'Basel-Stadt')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'New York')); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'New Hampshire')); + $type->addDocument($doc); + $doc = new Document(4, array('name' => 'Basel Land')); + $type->addDocument($doc); + + $index->refresh(); + + $field = 'name'; + $type = 'phrase_prefix'; + + $query = new Match(); + $query->setFieldQuery($field, 'New'); + $query->setFieldType($field, $type); + + $resultSet = $index->search($query); + + $this->assertEquals(2, $resultSet->count()); + } + + + public function testMatchFuzzinessType() + { + $field = 'test'; + $query = new Match(); + + $fuzziness = "AUTO"; + $query->setFieldFuzziness($field, $fuzziness); + + $parameters = $query->getParam($field); + $this->assertEquals($fuzziness, $parameters['fuzziness']); + + + $fuzziness = 0.3; + $query->setFieldFuzziness($field, $fuzziness); + + $parameters = $query->getParam($field); + $this->assertEquals($fuzziness, $parameters['fuzziness']); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/MoreLikeThisTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/MoreLikeThisTest.php new file mode 100644 index 00000000..b352e23a --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/MoreLikeThisTest.php @@ -0,0 +1,176 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Index; +use Elastica\Query; +use Elastica\Query\MoreLikeThis; +use Elastica\Type; +use Elastica\Type\Mapping; +use Elastica\Test\Base as BaseTest; + +class MoreLikeThisTest extends BaseTest +{ + public function testSearch() + { + $client = $this->_getClient(); + $index = new Index($client, 'test'); + $index->create(array(), true); + $index->getSettings()->setNumberOfReplicas(0); + //$index->getSettings()->setNumberOfShards(1); + + $type = new Type($index, 'helloworldmlt'); + $mapping = new Mapping($type , array( + 'email' => array('store' => 'yes', 'type' => 'string', 'index' => 'analyzed'), + 'content' => array('store' => 'yes', 'type' => 'string', 'index' => 'analyzed'), + )); + + $mapping->setSource(array('enabled' => false)); + $type->setMapping($mapping); + + $doc = new Document(1000, array('email' => 'testemail@gmail.com', 'content' => 'This is a sample post. Hello World Fuzzy Like This!')); + $type->addDocument($doc); + + $doc = new Document(1001, array('email' => 'nospam@gmail.com', 'content' => 'This is a fake nospam email address for gmail')); + $type->addDocument($doc); + + // Refresh index + $index->refresh(); + + $mltQuery = new MoreLikeThis(); + $mltQuery->setLikeText('fake gmail sample'); + $mltQuery->setFields(array('email','content')); + $mltQuery->setMaxQueryTerms(1); + $mltQuery->setMinDocFrequency(1); + $mltQuery->setMinTermFrequency(1); + + $query = new Query(); + $query->setFields(array('email', 'content')); + $query->setQuery($mltQuery); + + $resultSet = $type->search($query); + $resultSet->getResponse()->getData(); + $this->assertEquals(2, $resultSet->count()); + } + + public function testSetFields() + { + $query = new MoreLikeThis(); + + $fields = array('firstname', 'lastname'); + $query->setFields($fields); + + $data = $query->toArray(); + $this->assertEquals($fields, $data['more_like_this']['fields']); + } + + public function testSetLikeText() + { + $query = new MoreLikeThis(); + $query->setLikeText(' hello world'); + + $data = $query->toArray(); + $this->assertEquals('hello world', $data['more_like_this']['like_text']); + } + + public function testSetBoost() + { + $query = new MoreLikeThis(); + + $boost = 1.3; + $query->setBoost($boost); + + $this->assertEquals($boost, $query->getParam('boost')); + } + + public function testSetMaxQueryTerms() + { + $query = new MoreLikeThis(); + + $max = 3; + $query->setMaxQueryTerms($max); + + $this->assertEquals($max, $query->getParam('max_query_terms')); + } + + public function testSetPercentTermsToMatch() + { + $query = new MoreLikeThis(); + + $match = 0.8; + $query->setPercentTermsToMatch($match); + + $this->assertEquals($match, $query->getParam('percent_terms_to_match')); + } + + public function testSetMinDocFrequency() + { + $query = new MoreLikeThis(); + + $freq = 2; + $query->setMinDocFrequency($freq); + + $this->assertEquals($freq, $query->getParam('min_doc_freq')); + } + + public function testSetMaxDocFrequency() + { + $query = new MoreLikeThis(); + + $freq = 2; + $query->setMaxDocFrequency($freq); + + $this->assertEquals($freq, $query->getParam('max_doc_freq')); + } + + public function testSetMinWordLength() + { + $query = new MoreLikeThis(); + + $length = 4; + $query->setMinWordLength($length); + + $this->assertEquals($length, $query->getParam('min_word_length')); + } + + public function testSetMaxWordLength() + { + $query = new MoreLikeThis(); + + $length = 5; + $query->setMaxWordLength($length); + + $this->assertEquals($length, $query->getParam('max_word_length')); + } + + public function testSetBoostTerms() + { + $query = new MoreLikeThis(); + + $boost = false; + $query->setBoostTerms($boost); + + $this->assertEquals($boost, $query->getParam('boost_terms')); + } + + public function testSetAnalyzer() + { + $query = new MoreLikeThis(); + + $analyzer = 'UpperCase'; + $query->setAnalyzer($analyzer); + + $this->assertEquals($analyzer, $query->getParam('analyzer')); + } + + public function testSetStopWords() + { + $query = new MoreLikeThis(); + + $stopWords = array('no', 'yes', 'test'); + $query->setStopWords($stopWords); + + $this->assertEquals($stopWords, $query->getParam('stop_words')); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/MultiMatchTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/MultiMatchTest.php new file mode 100644 index 00000000..78a8a8fe --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/MultiMatchTest.php @@ -0,0 +1,187 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Index; +use Elastica\Query; +use Elastica\Query\MultiMatch; +use Elastica\Test\Base as BaseTest; +use Elastica\Type; +use Elastica\Type\Mapping; + +class MultiMatchTest extends BaseTest +{ + private $index; + private $multiMatch; + + private static $data = array( + array('id' => 1, 'name' => 'Rodolfo', 'last_name' => 'Moraes', 'full_name' => 'Rodolfo Moraes'), + array('id' => 2, 'name' => 'Tristan', 'last_name' => 'Maindron', 'full_name' => 'Tristan Maindron'), + array('id' => 3, 'name' => 'Monique', 'last_name' => 'Maindron', 'full_name' => 'Monique Maindron'), + array('id' => 4, 'name' => 'John', 'last_name' => 'not Doe', 'full_name' => 'John not Doe'), + ); + + protected function setUp() + { + $this->index = $this->_generateIndex(); + $this->multiMatch = new MultiMatch(); + } + + public function testMinimumShouldMatch() + { + $this->multiMatch->setQuery('Tristan Maindron'); + $this->multiMatch->setFields(array('full_name', 'name')); + $this->multiMatch->setMinimumShouldMatch(2); + $resultSet = $this->_getResults(); + + $this->assertEquals(1, $resultSet->count()); + } + + public function testAndOperator() + { + $this->multiMatch->setQuery('Monique Maindron'); + $this->multiMatch->setFields(array('full_name', 'name')); + $this->multiMatch->setOperator(MultiMatch::OPERATOR_AND); + $resultSet = $this->_getResults(); + + $this->assertEquals(1, $resultSet->count()); + } + + public function testType() + { + $this->multiMatch->setQuery('Trist'); + $this->multiMatch->setFields(array('full_name', 'name')); + $this->multiMatch->setType(MultiMatch::TYPE_PHRASE_PREFIX); + $resultSet = $this->_getResults(); + + $this->assertEquals(1, $resultSet->count()); + } + + public function testFuzzy() + { + $this->multiMatch->setQuery('Tritsan'); // Mispell on purpose + $this->multiMatch->setFields(array('full_name', 'name')); + $this->multiMatch->setFuzziness(2); + $resultSet = $this->_getResults(); + + $this->assertEquals(1, $resultSet->count()); + + $this->multiMatch->setQuery('Tritsan'); // Mispell on purpose + $this->multiMatch->setFields(array('full_name', 'name')); + $this->multiMatch->setFuzziness(0); + $resultSet = $this->_getResults(); + + $this->assertEquals(0, $resultSet->count()); + } + + public function testFuzzyWithOptions1() + { + // Here Elasticsearch will not accept mispells + // on the first 6 letters. + $this->multiMatch->setQuery('Tritsan'); // Mispell on purpose + $this->multiMatch->setFields(array('full_name', 'name')); + $this->multiMatch->setFuzziness(2); + $this->multiMatch->setPrefixLength(6); + $resultSet = $this->_getResults(); + + $this->assertEquals(0, $resultSet->count()); + } + + public function testFuzzyWithOptions2() { + + // Here with a 'M' search we should hit 'Moraes' first + // and then stop because MaxExpansion = 1. + // If MaxExpansion was set to 2, we could hit "Maindron" too. + $this->multiMatch->setQuery('M'); + $this->multiMatch->setFields(array('name')); + $this->multiMatch->setType(MultiMatch::TYPE_PHRASE_PREFIX); + $this->multiMatch->setPrefixLength(0); + $this->multiMatch->setMaxExpansions(1); + $resultSet = $this->_getResults(); + + $this->assertEquals(1, $resultSet->count()); + } + + public function testZeroTerm() + { + $this->multiMatch->setQuery('not'); // This is a stopword. + $this->multiMatch->setFields(array('full_name', 'last_name')); + $this->multiMatch->setZeroTermsQuery(MultiMatch::ZERO_TERM_NONE); + $this->multiMatch->setAnalyzer('stops'); + $resultSet = $this->_getResults(); + + $this->assertEquals(0, $resultSet->count()); + + $this->multiMatch->setZeroTermsQuery(MultiMatch::ZERO_TERM_ALL); + $resultSet = $this->_getResults(); + + $this->assertEquals(4, $resultSet->count()); + } + + public function testBaseMultiMatch() + { + $this->multiMatch->setQuery('Rodolfo'); + $this->multiMatch->setFields(array('name', 'last_name')); + $resultSet = $this->_getResults(); + + $this->assertEquals(1, $resultSet->count()); + + $this->multiMatch->setQuery('Moraes'); + $this->multiMatch->setFields(array('name', 'last_name')); + $resultSet = $this->_getResults(); + + $this->assertEquals(1, $resultSet->count()); + } + + /** + * Executes the query with the current multimatch. + */ + private function _getResults() + { + return $this->index->search(new Query($this->multiMatch)); + } + + /** + * Builds an index for testing. + */ + private function _generateIndex() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + + $index->create(array( + 'analysis' => array( + 'analyzer' => array( + 'noStops' => array( + 'type' => 'standard', + 'stopwords' => '_none_' + ), + 'stops' => array( + 'type' => 'standard', + 'stopwords' => array('not') + ), + ), + ) + ), true); + + $type = $index->getType('test'); + + $mapping = new Mapping($type, array( + 'name' => array('type' => 'string', 'store' => 'no', 'analyzer' => 'noStops'), + 'last_name' => array('type' => 'string', 'store' => 'no', 'analyzer' => 'noStops'), + 'full_name' => array('type' => 'string', 'store' => 'no', 'analyzer' => 'noStops'), + )); + + $type->setMapping($mapping); + + foreach (self::$data as $key => $docData) { + $type->addDocument(new Document($key, $docData)); + } + + // Refresh index + $index->refresh(); + + return $index; + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/NestedTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/NestedTest.php new file mode 100644 index 00000000..310a728b --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/NestedTest.php @@ -0,0 +1,28 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Query\Nested; +use Elastica\Query\QueryString; +use Elastica\Test\Base as BaseTest; + +class NestedTest extends BaseTest +{ + public function testSetQuery() + { + $nested = new Nested(); + $path = 'test1'; + + $queryString = new QueryString('test'); + $this->assertInstanceOf('Elastica\Query\Nested', $nested->setQuery($queryString)); + $this->assertInstanceOf('Elastica\Query\Nested', $nested->setPath($path)); + $expected = array( + 'nested' => array( + 'query' => $queryString->toArray(), + 'path' => $path, + ) + ); + + $this->assertEquals($expected, $nested->toArray()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/PostFilterTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/PostFilterTest.php new file mode 100644 index 00000000..16b7e07b --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/PostFilterTest.php @@ -0,0 +1,83 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Filter\Term; +use Elastica\Index; +use Elastica\Query\Match; +use Elastica\Query; +use Elastica\Test\Base as BaseTest; + +class PostFilterTest extends BaseTest +{ + /** + * @var Index + */ + protected $_index; + + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex("query"); + $docs = array( + new Document("1", array("color" => "green", "make" => "ford")), + new Document("2", array("color" => "blue", "make" => "volvo")), + new Document("3", array("color" => "red", "make" => "ford")), + new Document("4", array("color" => "green", "make" => "renault")), + ); + $this->_index->getType("test")->addDocuments($docs); + $this->_index->refresh(); + + } + + protected function tearDown() + { + parent::tearDown(); + if ($this->_index instanceof Index) { + $this->_index->delete(); + } + } + + public function testToArray() + { + $query = new Query(); + + $post_filter = new Term(array('color' => 'green')); + $query->setPostFilter($post_filter->toArray()); + + $data = $query->toArray(); + + $this->assertArrayHasKey('post_filter', $data); + $this->assertEquals(array('term' => array('color' => 'green')), $data['post_filter']); + + $query->setPostFilter(array()); + + $this->assertArrayNotHasKey('post_filter', $query->toArray()); + } + + public function testQuery() + { + $query = new Query(); + + $match = new Match(); + $match->setField('make', 'ford'); + + $query->setQuery($match); + + $filter = new Term(); + $filter->setTerm('color', 'green'); + + $query->setPostFilter($filter->toArray()); + + $results = $this->_index->search($query); + + $this->assertEquals(1, $results->getTotalHits()); + + } + + protected function _createIndex($name = 'test', $delete = true, $shards = 1) + { + return parent::_createIndex('test_postfilter_' . $name, $delete, $shards); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/PrefixTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/PrefixTest.php new file mode 100644 index 00000000..e6852c2e --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/PrefixTest.php @@ -0,0 +1,26 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Query\Prefix; +use Elastica\Test\Base as BaseTest; + +class PrefixTest extends BaseTest +{ + + public function testToArray() + { + $query = new Prefix(); + $key = 'name'; + $value = 'ni'; + $boost = 2; + $query->setPrefix($key, $value, $boost); + + $data = $query->toArray(); + + $this->assertInternalType('array', $data['prefix']); + $this->assertInternalType('array', $data['prefix'][$key]); + $this->assertEquals($data['prefix'][$key]['value'], $value); + $this->assertEquals($data['prefix'][$key]['boost'], $boost); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/QueryStringTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/QueryStringTest.php new file mode 100644 index 00000000..059bad2d --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/QueryStringTest.php @@ -0,0 +1,126 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Index; +use Elastica\Type; +use Elastica\Query\QueryString; +use Elastica\Test\Base as BaseTest; + +class QueryStringTest extends BaseTest +{ + public function testSearchMultipleFields() + { + $str = md5(rand()); + $query = new QueryString($str); + + $expected = array( + 'query' => $str + ); + + $this->assertEquals(array('query_string' => $expected), $query->toArray()); + + $fields = array(); + $max = rand() % 10 + 1; + for ($i = 0; $i < $max; $i++) { + $fields[] = md5(rand()); + } + + $query->setFields($fields); + $expected['fields'] = $fields; + $this->assertEquals(array('query_string' => $expected), $query->toArray()); + + foreach (array(false, true) as $val) { + $query->setUseDisMax($val); + $expected['use_dis_max'] = $val; + + $this->assertEquals(array('query_string' => $expected), $query->toArray()); + } + } + + public function testSearch() + { + $client = $this->_getClient(); + $index = new Index($client, 'test'); + $index->create(array(), true); + $index->getSettings()->setNumberOfReplicas(0); + //$index->getSettings()->setNumberOfShards(1); + + $type = new Type($index, 'helloworld'); + + $doc = new Document(1, array('email' => 'test@test.com', 'username' => 'hanswurst', 'test' => array('2', '3', '5'))); + $type->addDocument($doc); + + // Refresh index + $index->refresh(); + + $queryString = new QueryString('test*'); + $resultSet = $type->search($queryString); + + $this->assertEquals(1, $resultSet->count()); + } + + /** + * Tests if search in multiple fields is possible + */ + public function testSearchFields() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + + $doc = new Document(1, array('title' => 'hello world', 'firstname' => 'nicolas', 'lastname' => 'ruflin', 'price' => '102', 'year' => '2012')); + $type->addDocument($doc); + $index->refresh(); + + $query = new QueryString(); + $query = $query->setQuery('ruf*'); + $query = $query->setDefaultField('title'); + $query = $query->setFields(array('title', 'firstname', 'lastname', 'price', 'year')); + + $resultSet = $type->search($query); + $this->assertEquals(1, $resultSet->count()); + } + + public function testSetDefaultOperator() + { + $operator = 'AND'; + $query = new QueryString('test'); + $query->setDefaultOperator($operator); + + $data = $query->toArray(); + + $this->assertEquals($data['query_string']['default_operator'], $operator); + } + + public function testSetDefaultField() + { + $default = 'field1'; + $query = new QueryString('test'); + $query->setDefaultField($default); + + $data = $query->toArray(); + + $this->assertEquals($data['query_string']['default_field'], $default); + } + + public function testSetRewrite() + { + $rewrite = 'scoring_boolean'; + $query = new QueryString('test'); + $query->setRewrite($rewrite); + + $data = $query->toArray(); + + $this->assertEquals($data['query_string']['rewrite'], $rewrite); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testSetQueryInvalid() + { + $query = new QueryString(); + $query->setQuery(array()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/RangeTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/RangeTest.php new file mode 100644 index 00000000..4cd75bc8 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/RangeTest.php @@ -0,0 +1,73 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Query\Range; +use Elastica\Test\Base as BaseTest; + +class RangeTest extends BaseTest +{ + public function testQuery() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('test'); + + $doc = new Document(1, array('age' => 16, 'height' => 140)); + $type->addDocument($doc); + $doc = new Document(2, array('age' => 21, 'height' => 155)); + $type->addDocument($doc); + $doc = new Document(3, array('age' => 33, 'height' => 160)); + $type->addDocument($doc); + $doc = new Document(4, array('age' => 68, 'height' => 160)); + $type->addDocument($doc); + + $index->optimize(); + $index->refresh(); + + $query = new Range('age', array('from' => 10, 'to' => 20)); + $result = $type->search($query)->count(); + $this->assertEquals(1, $result); + + $query = new Range(); + $query->addField('height', array('gte' => 160)); + + $result = $type->search($query)->count(); + $this->assertEquals(2, $result); + } + + public function testToArray() + { + $range = new Range(); + + $field = array('from' => 20, 'to' => 40); + $range->addField('age', $field); + + $expectedArray = array( + 'range' => array( + 'age' => $field, + ) + ); + + $this->assertEquals($expectedArray, $range->toArray()); + } + + public function testConstruct() + { + $ranges = array('from' => 20, 'to' => 40); + $range = new Range( + 'age', + $ranges + ); + + $expectedArray = array( + 'range' => array( + 'age' => $ranges, + ) + ); + + $this->assertEquals($expectedArray, $range->toArray()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/RescoreTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/RescoreTest.php new file mode 100644 index 00000000..4396ceb4 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/RescoreTest.php @@ -0,0 +1,165 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Rescore\Query as QueryRescore; +use Elastica\Query\Term; +use Elastica\Query\Match; +use Elastica\Query; +use Elastica\Test\Base as BaseTest; + +class RescoreTest extends BaseTest +{ + /** + * @var Index + */ + protected $_index; + + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex("rescore_test"); + $this->_index->refresh(); + } + + public function testToArray() + { + $query = new Query(); + $mainQuery = new Match(); + $mainQuery = $mainQuery->setFieldQuery('test1', 'foo'); + $secQuery = new Term(); + $secQuery = $secQuery->setTerm('test2', 'bar', 2); + $queryRescore = new QueryRescore($secQuery); + $query->setQuery($mainQuery); + $query->setRescore($queryRescore); + $data = $query->toArray(); + + $expected = array( + 'query' => array( + 'match' => array( + 'test1' => array( + 'query' => 'foo', + ), + ), + ), + 'rescore' => array( + 'query' => array( + 'rescore_query' => array( + 'term' => array( + 'test2' => array( + 'value' => 'bar', + 'boost' => 2, + ), + ), + ), + ), + ), + ); + + $this->assertEquals($expected, $data); + } + + public function testSetSize() + { + $query = new Query(); + $mainQuery = new Match(); + $mainQuery = $mainQuery->setFieldQuery('test1', 'foo'); + $secQuery = new Term(); + $secQuery = $secQuery->setTerm('test2', 'bar', 2); + $queryRescore = new QueryRescore($secQuery); + $queryRescore->setWindowSize(50); + $query->setQuery($mainQuery); + $query->setRescore($queryRescore); + $data = $query->toArray(); + + $expected = array( + 'query' => array( + 'match' => array( + 'test1' => array( + 'query' => 'foo', + ), + ), + ), + 'rescore' => array( + 'window_size' => 50, + 'query' => array( + 'rescore_query' => array( + 'term' => array( + 'test2' => array( + 'value' => 'bar', + 'boost' => 2, + ), + ), + ), + ), + ), + ); + + $this->assertEquals($expected, $data); + } + + public function testSetWeights() + { + $query = new Query(); + $mainQuery = new Match(); + $mainQuery = $mainQuery->setFieldQuery('test1', 'foo'); + $secQuery = new Term(); + $secQuery = $secQuery->setTerm('test2', 'bar', 2); + $queryRescore = new QueryRescore($secQuery); + $queryRescore->setWindowSize(50); + $queryRescore->setQueryWeight(.7); + $queryRescore->setRescoreQueryWeight(1.2); + $query->setQuery($mainQuery); + $query->setRescore($queryRescore); + $data = $query->toArray(); + + $expected = array( + 'query' => array( + 'match' => array( + 'test1' => array( + 'query' => 'foo', + ), + ), + ), + 'rescore' => array( + 'window_size' => 50, + 'query' => array( + 'rescore_query' => array( + 'term' => array( + 'test2' => array( + 'value' => 'bar', + 'boost' => 2, + ), + ), + ), + 'query_weight' => 0.7, + 'rescore_query_weight' => 1.2 + ), + ), + ); + + $this->assertEquals($expected, $data); + } + + public function testQuery() + { + $query = new Query(); + $mainQuery = new Match(); + $mainQuery = $mainQuery->setFieldQuery('test1', 'foo'); + $secQuery = new Term(); + $secQuery = $secQuery->setTerm('test2', 'bar', 2); + $queryRescore = new QueryRescore($secQuery); + $queryRescore->setWindowSize(50); + $queryRescore->setQueryWeight(.7); + $queryRescore->setRescoreQueryWeight(1.2); + $query->setQuery($mainQuery); + $query->setRescore($queryRescore); + $data = $query->toArray(); + + $results = $this->_index->search($query); + $response = $results->getResponse(); + + $this->assertEquals(true, $response->isOk()); + $this->assertEquals(0, $results->getTotalHits()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/SimpleQueryStringTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/SimpleQueryStringTest.php new file mode 100644 index 00000000..eff9b8a1 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/SimpleQueryStringTest.php @@ -0,0 +1,73 @@ +<?php + +namespace Elastica\Test\Query; + + +use Elastica\Document; +use Elastica\Index; +use Elastica\Query\SimpleQueryString; +use Elastica\Test\Base; + +class SimpleQueryStringTest extends Base +{ + /** + * @var Index + */ + protected $_index; + + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex("simple_query_string_test"); + $docs = array( + new Document(1, array('make' => 'Gibson', 'model' => 'Les Paul')), + new Document(2, array('make' => 'Gibson', 'model' => 'SG Standard')), + new Document(3, array('make' => 'Gibson', 'model' => 'SG Supreme')), + new Document(4, array('make' => 'Gibson', 'model' => 'SG Faded')), + new Document(5, array('make' => 'Fender', 'model' => 'Stratocaster')) + ); + $this->_index->getType("guitars")->addDocuments($docs); + $this->_index->refresh(); + } + + protected function tearDown() + { + parent::tearDown(); + $this->_index->delete(); + } + + public function testToArray() + { + $string = "this is a test"; + $fields = array('field1', 'field2'); + $query = new SimpleQueryString($string, $fields); + $query->setDefaultOperator(SimpleQueryString::OPERATOR_OR); + $query->setAnalyzer("whitespace"); + + $expected = array( + "simple_query_string" => array( + "query" => $string, + "fields" => $fields, + "analyzer" => "whitespace", + "default_operator" => SimpleQueryString::OPERATOR_OR + ) + ); + + $this->assertEquals($expected, $query->toArray()); + } + + public function testQuery() + { + $query = new SimpleQueryString("gibson +sg +-faded", array("make", "model")); + $results = $this->_index->search($query); + + $this->assertEquals(2, $results->getTotalHits()); + + $query->setFields(array("model")); + $results = $this->_index->search($query); + + // We should not get any hits, since the "make" field was not included in the query. + $this->assertEquals(0, $results->getTotalHits()); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/SimpleTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/SimpleTest.php new file mode 100644 index 00000000..08a5f55d --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/SimpleTest.php @@ -0,0 +1,17 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Query\Simple; +use Elastica\Test\Base as BaseTest; + +class SimpleTest extends BaseTest +{ + public function testToArray() + { + $testQuery = array('hello' => array('world'), 'name' => 'ruflin'); + $query = new Simple($testQuery); + + $this->assertEquals($testQuery, $query->toArray()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/TermTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/TermTest.php new file mode 100644 index 00000000..887c3849 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/TermTest.php @@ -0,0 +1,26 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Query\Term; +use Elastica\Test\Base as BaseTest; + +class TermTest extends BaseTest +{ + + public function testToArray() + { + $query = new Term(); + $key = 'name'; + $value = 'nicolas'; + $boost = 2; + $query->setTerm($key, $value, $boost); + + $data = $query->toArray(); + + $this->assertInternalType('array', $data['term']); + $this->assertInternalType('array', $data['term'][$key]); + $this->assertEquals($data['term'][$key]['value'], $value); + $this->assertEquals($data['term'][$key]['boost'], $boost); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/TermsTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/TermsTest.php new file mode 100644 index 00000000..184f3ad6 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/TermsTest.php @@ -0,0 +1,62 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Query\Terms; +use Elastica\Test\Base as BaseTest; + +class TermsTest extends BaseTest +{ + public function testFilteredSearch() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + $index->create(array(), true); + $type = $index->getType('helloworld'); + + $doc = new Document(1, array('name' => 'hello world')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'nicolas ruflin')); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'ruflin')); + $type->addDocument($doc); + + $query = new Terms(); + $query->setTerms('name', array('nicolas', 'hello')); + + $index->refresh(); + + $resultSet = $type->search($query); + + $this->assertEquals(2, $resultSet->count()); + + $query->addTerm('ruflin'); + $resultSet = $type->search($query); + + $this->assertEquals(3, $resultSet->count()); + } + + public function testSetMinimum() + { + $key = 'name'; + $terms = array('nicolas', 'ruflin'); + $minimum = 2; + + $query = new Terms($key, $terms); + $query->setMinimumMatch($minimum); + + $data = $query->toArray(); + $this->assertEquals($minimum, $data['terms']['minimum_match']); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testInvalidParams() + { + $query = new Terms(); + + $query->toArray(); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/WildcardTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/WildcardTest.php new file mode 100644 index 00000000..077e6d4f --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Query/WildcardTest.php @@ -0,0 +1,101 @@ +<?php + +namespace Elastica\Test\Query; + +use Elastica\Document; +use Elastica\Query\Wildcard; +use Elastica\Test\Base as BaseTest; +use Elastica\Type\Mapping; + +class WildcardTest extends BaseTest +{ + public function testConstructEmpty() + { + $wildcard = new Wildcard(); + $this->assertEmpty($wildcard->getParams()); + } + + public function testToArray() + { + $key = 'name'; + $value = 'Ru*lin'; + $boost = 2.0; + + $wildcard = new Wildcard($key, $value, $boost); + + $expectedArray = array( + 'wildcard' => array( + $key => array( + 'value' => $value, + 'boost' => $boost + ) + ) + ); + + $this->assertEquals($expectedArray, $wildcard->toArray()); + } + + public function testSearchWithAnalyzer() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + + $indexParams = array( + 'analysis' => array( + 'analyzer' => array( + 'lw' => array( + 'type' => 'custom', + 'tokenizer' => 'keyword', + 'filter' => array('lowercase') + ) + ), + ) + ); + + $index->create($indexParams, true); + $type = $index->getType('test'); + + $mapping = new Mapping($type, array( + 'name' => array('type' => 'string', 'store' => 'no', 'analyzer' => 'lw'), + ) + ); + $type->setMapping($mapping); + + $doc = new Document(1, array('name' => 'Basel-Stadt')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'New York')); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'Baden')); + $type->addDocument($doc); + $doc = new Document(4, array('name' => 'Baden Baden')); + $type->addDocument($doc); + $doc = new Document(5, array('name' => 'New Orleans')); + $type->addDocument($doc); + + $index->refresh(); + + $query = new Wildcard(); + $query->setValue('name', 'ba*'); + $resultSet = $index->search($query); + + $this->assertEquals(3, $resultSet->count()); + + $query = new Wildcard(); + $query->setValue('name', 'baden*'); + $resultSet = $index->search($query); + + $this->assertEquals(2, $resultSet->count()); + + $query = new Wildcard(); + $query->setValue('name', 'baden b*'); + $resultSet = $index->search($query); + + $this->assertEquals(1, $resultSet->count()); + + $query = new Wildcard(); + $query->setValue('name', 'baden bas*'); + $resultSet = $index->search($query); + + $this->assertEquals(0, $resultSet->count()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/QueryTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/QueryTest.php new file mode 100644 index 00000000..ece9f4c2 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/QueryTest.php @@ -0,0 +1,194 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Document; +use Elastica\Exception\InvalidException; +use Elastica\Query\Builder; +use Elastica\Query\Term; +use Elastica\Query\Text; +use Elastica\Query; +use Elastica\Facet\Terms; +use Elastica\Test\Base as BaseTest; + +class QueryTest extends BaseTest +{ + public function testStringConversion() + { + $queryString = '{ + "query" : { + "filtered" : { + "filter" : { + "range" : { + "due" : { + "gte" : "2011-07-18 00:00:00", + "lt" : "2011-07-25 00:00:00" + } + } + }, + "query" : { + "text_phrase" : { + "title" : "Call back request" + } + } + } + }, + "sort" : { + "due" : { + "reverse" : true + } + }, + "fields" : [ + "created", "assigned_to" + ] + }'; + + $query = new Builder($queryString); + $queryArray = $query->toArray(); + + $this->assertInternalType('array', $queryArray); + + $this->assertEquals('2011-07-18 00:00:00', $queryArray['query']['filtered']['filter']['range']['due']['gte']); + } + + public function testRawQuery() + { + $textQuery = new Term(array('title' => 'test')); + + $query1 = Query::create($textQuery); + + $query2 = new Query(); + $query2->setRawQuery(array('query' => array('term' => array('title' => 'test')))); + + $this->assertEquals($query1->toArray(), $query2->toArray()); + } + + public function testArrayQuery() + { + $query = array( + 'query' => array( + 'text' => array( + 'title' => 'test' + ) + ) + ); + + $query1 = Query::create($query); + + $query2 = new Query(); + $query2->setRawQuery(array('query' => array('text' => array('title' => 'test')))); + + $this->assertEquals($query1->toArray(), $query2->toArray()); + } + + public function testSetSort() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + + $doc = new Document(1, array('name' => 'hello world')); + $type->addDocument($doc); + $doc = new Document(2, array('firstname' => 'guschti', 'lastname' => 'ruflin')); + $type->addDocument($doc); + $doc = new Document(3, array('firstname' => 'nicolas', 'lastname' => 'ruflin')); + $type->addDocument($doc); + + $queryTerm = new Term(); + $queryTerm->setTerm('lastname', 'ruflin'); + + $index->refresh(); + + $query = Query::create($queryTerm); + + // ASC order + $query->setSort(array(array('firstname' => array('order' => 'asc')))); + $resultSet = $type->search($query); + $this->assertEquals(2, $resultSet->count()); + + $first = $resultSet->current()->getData(); + $second = $resultSet->next()->getData(); + + $this->assertEquals('guschti', $first['firstname']); + $this->assertEquals('nicolas', $second['firstname']); + + // DESC order + $query->setSort(array('firstname' => array('order' => 'desc'))); + $resultSet = $type->search($query); + $this->assertEquals(2, $resultSet->count()); + + $first = $resultSet->current()->getData(); + $second = $resultSet->next()->getData(); + + $this->assertEquals('nicolas', $first['firstname']); + $this->assertEquals('guschti', $second['firstname']); + } + + public function testAddSort() + { + $query = new Query(); + $sortParam = array('firstname' => array('order' => 'asc')); + $query->addSort($sortParam); + + $this->assertEquals($query->getParam('sort'), array($sortParam)); + } + + public function testSetRawQuery() + { + $query = new Query(); + + $params = array('query' => 'test'); + $query->setRawQuery($params); + + $this->assertEquals($params, $query->toArray()); + } + + public function testSetFields() + { + $query = new Query(); + + $params = array('query' => 'test'); + + $query->setFields(array('firstname', 'lastname')); + + $data = $query->toArray(); + + $this->assertContains('firstname', $data['fields']); + $this->assertContains('lastname', $data['fields']); + $this->assertEquals(2, count($data['fields'])); + } + + public function testGetQuery() + { + $query = new Query(); + + try { + $query->getQuery(); + $this->fail('should throw exception because query does not exist'); + } catch (InvalidException $e) { + $this->assertTrue(true); + } + + $termQuery = new Term(); + $termQuery->setTerm('text', 'value'); + $query->setQuery($termQuery); + + $this->assertEquals($termQuery->toArray(), $query->getQuery()); + } + + public function testSetFacets() + { + $query = new Query(); + + $facet = new Terms('text'); + $query->setFacets(array($facet)); + + $data = $query->toArray(); + + $this->assertArrayHasKey('facets', $data); + $this->assertEquals(array('text' => array('terms' => array())), $data['facets']); + + $query->setFacets(array()); + + $this->assertArrayNotHasKey('facets', $query->toArray()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/RequestTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/RequestTest.php new file mode 100644 index 00000000..8896adeb --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/RequestTest.php @@ -0,0 +1,87 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Connection; +use Elastica\Request; +use Elastica\Test\Base as BaseTest; + +class RequestTest extends BaseTest +{ + + public function testConstructor() + { + $path = 'test'; + $method = Request::POST; + $query = array('no' => 'params'); + $data = array('key' => 'value'); + + $request = new Request($path, $method, $data, $query); + + $this->assertEquals($path, $request->getPath()); + $this->assertEquals($method, $request->getMethod()); + $this->assertEquals($query, $request->getQuery()); + $this->assertEquals($data, $request->getData()); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testInvalidConnection() + { + $request = new Request('', Request::GET); + $request->send(); + } + + public function testSend() + { + $connection = new Connection(); + $connection->setHost('localhost'); + $connection->setPort('9200'); + + $request = new Request('_status', Request::GET, array(), array(), $connection); + + $response = $request->send(); + + $this->assertInstanceOf('Elastica\Response', $response); + } + + public function testToString() + { + $path = 'test'; + $method = Request::POST; + $query = array('no' => 'params'); + $data = array('key' => 'value'); + + $connection = new Connection(); + $connection->setHost('localhost'); + $connection->setPort('9200'); + + $request = new Request($path, $method, $data, $query, $connection); + + $data = $request->toArray(); + + $this->assertInternalType('array', $data); + $this->assertArrayHasKey('method', $data); + $this->assertArrayHasKey('path', $data); + $this->assertArrayHasKey('query', $data); + $this->assertArrayHasKey('data', $data); + $this->assertArrayHasKey('connection', $data); + $this->assertEquals($request->getMethod(), $data['method']); + $this->assertEquals($request->getPath(), $data['path']); + $this->assertEquals($request->getQuery(), $data['query']); + $this->assertEquals($request->getData(), $data['data']); + $this->assertInternalType('array', $data['connection']); + $this->assertArrayHasKey('host', $data['connection']); + $this->assertArrayHasKey('port', $data['connection']); + $this->assertEquals($request->getConnection()->getHost(), $data['connection']['host']); + $this->assertEquals($request->getConnection()->getPort(), $data['connection']['port']); + + $string = $request->toString(); + + $this->assertInternalType('string', $string); + + $string = (string) $request; + $this->assertInternalType('string', $string); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/ResponseTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/ResponseTest.php new file mode 100644 index 00000000..1e026eae --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/ResponseTest.php @@ -0,0 +1,94 @@ +<?php + +namespace Elastica\Test; +use Elastica\Document; +use Elastica\Facet\DateHistogram; +use Elastica\Query; +use Elastica\Query\MatchAll; +use Elastica\Request; +use Elastica\Type\Mapping; +use Elastica\Test\Base as BaseTest; + +class ResponseTest extends BaseTest +{ + public function testClassHierarchy() + { + $facet = new DateHistogram('dateHist1'); + $this->assertInstanceOf('Elastica\Facet\Histogram', $facet); + $this->assertInstanceOf('Elastica\Facet\AbstractFacet', $facet); + unset($facet); + } + + public function testResponse() + { + $index = $this->_createIndex(); + $type = $index->getType('helloworld'); + + $mapping = new Mapping($type, array( + 'name' => array('type' => 'string', 'store' => 'no'), + 'dtmPosted' => array('type' => 'date', 'store' => 'no', 'format' => 'yyyy-MM-dd HH:mm:ss') + )); + $type->setMapping($mapping); + + $doc = new Document(1, array('name' => 'nicolas ruflin', 'dtmPosted' => "2011-06-23 21:53:00")); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'raul martinez jr', 'dtmPosted' => "2011-06-23 09:53:00")); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'rachelle clemente', 'dtmPosted' => "2011-07-08 08:53:00")); + $type->addDocument($doc); + $doc = new Document(4, array('name' => 'elastica search', 'dtmPosted' => "2011-07-08 01:53:00")); + $type->addDocument($doc); + + $query = new Query(); + $query->setQuery(new MatchAll()); + $index->refresh(); + + $resultSet = $type->search($query); + + $engineTime = $resultSet->getResponse()->getEngineTime(); + $shardsStats = $resultSet->getResponse()->getShardsStatistics(); + + $this->assertInternalType('int', $engineTime); + $this->assertTrue(is_array($shardsStats)); + $this->assertArrayHasKey('total', $shardsStats); + $this->assertArrayHasKey('successful', $shardsStats); + } + + public function testIsOk() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + + $doc = new Document(1, array('name' => 'ruflin')); + $response = $type->addDocument($doc); + + $this->assertTrue($response->isOk()); + } + + public function testIsOkMultiple() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + + $docs = array( + new Document(1, array('name' => 'ruflin')), + new Document(2, array('name' => 'ruflin')) + ); + $response = $type->addDocuments($docs); + + $this->assertTrue($response->isOk()); + } + + public function testGetDataEmpty() + { + $index = $this->_createIndex(); + + $response = $index->request( + 'non-existant-type/_mapping', + Request::GET + )->getData(); + + $this->assertEquals(0, count($response)); + } + +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/ResultSetTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/ResultSetTest.php new file mode 100644 index 00000000..2a62111d --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/ResultSetTest.php @@ -0,0 +1,93 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Client; +use Elastica\Document; +use Elastica\Query; +use Elastica\Query\Match; +use Elastica\Result; +use Elastica\Test\Base as BaseTest; + +class ResultSetTest extends BaseTest +{ + public function testGetters() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + + $doc = new Document(1, array('name' => 'elastica search')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'elastica library')); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'elastica test')); + $type->addDocument($doc); + $index->refresh(); + + $resultSet = $type->search('elastica search'); + + $this->assertInstanceOf('Elastica\ResultSet', $resultSet); + $this->assertEquals(3, $resultSet->getTotalHits()); + $this->assertGreaterThan(0, $resultSet->getMaxScore()); + $this->assertInternalType('array', $resultSet->getResults()); + $this->assertEquals(3, count($resultSet)); + } + + public function testArrayAccess() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + + $doc = new Document(1, array('name' => 'elastica search')); + $type->addDocument($doc); + $doc = new Document(2, array('name' => 'elastica library')); + $type->addDocument($doc); + $doc = new Document(3, array('name' => 'elastica test')); + $type->addDocument($doc); + $index->refresh(); + + $resultSet = $type->search('elastica search'); + + $this->assertInstanceOf('Elastica\ResultSet', $resultSet); + $this->assertInstanceOf('Elastica\Result', $resultSet[0]); + $this->assertInstanceOf('Elastica\Result', $resultSet[1]); + $this->assertInstanceOf('Elastica\Result', $resultSet[2]); + + $this->assertFalse(isset($resultSet[3])); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testInvalidOffsetCreation() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + + $doc = new Document(1, array('name' => 'elastica search')); + $type->addDocument($doc); + $index->refresh(); + + $resultSet = $type->search('elastica search'); + + $result = new Result(array('_id' => 'fakeresult')); + $resultSet[1] = $result; + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testInvalidOffsetGet() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + + $doc = new Document(1, array('name' => 'elastica search')); + $type->addDocument($doc); + $index->refresh(); + + $resultSet = $type->search('elastica search'); + + return $resultSet[3]; + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/ResultTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/ResultTest.php new file mode 100644 index 00000000..54d3ce55 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/ResultTest.php @@ -0,0 +1,121 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Client; +use Elastica\Document; +use Elastica\Result; +use Elastica\Type\Mapping; +use Elastica\Test\Base as BaseTest; + +class ResultTest extends BaseTest +{ + public function testGetters() + { + // Creates a new index 'xodoa' and a type 'user' inside this index + $typeName = 'user'; + + $index = $this->_createIndex(); + $type = $index->getType($typeName); + + // Adds 1 document to the index + $docId = 3; + $doc1 = new Document($docId, array('username' => 'hans')); + $type->addDocument($doc1); + + // Refreshes index + $index->refresh(); + + $resultSet = $type->search('hans'); + + $this->assertEquals(1, $resultSet->count()); + + $result = $resultSet->current(); + + $this->assertInstanceOf('Elastica\Result', $result); + $this->assertEquals($index->getName(), $result->getIndex()); + $this->assertEquals($typeName, $result->getType()); + $this->assertEquals($docId, $result->getId()); + $this->assertGreaterThan(0, $result->getScore()); + $this->assertInternalType('array', $result->getData()); + $this->assertTrue(isset($result->username)); + $this->assertEquals('hans', $result->username); + } + + public function testGetIdNoSource() + { + // Creates a new index 'xodoa' and a type 'user' inside this index + $indexName = 'xodoa'; + $typeName = 'user'; + + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + $index->create(array(), true); + $type = $index->getType($typeName); + + $mapping = new Mapping($type); + $mapping->disableSource(); + $mapping->send(); + + // Adds 1 document to the index + $docId = 3; + $doc1 = new Document($docId, array('username' => 'hans')); + $type->addDocument($doc1); + + // Refreshes index + $index->refresh(); + + $resultSet = $type->search('hans'); + + $this->assertEquals(1, $resultSet->count()); + + $result = $resultSet->current(); + + $this->assertEquals(array(), $result->getSource()); + $this->assertInstanceOf('Elastica\Result', $result); + $this->assertEquals($indexName, $result->getIndex()); + $this->assertEquals($typeName, $result->getType()); + $this->assertEquals($docId, $result->getId()); + $this->assertGreaterThan(0, $result->getScore()); + $this->assertInternalType('array', $result->getData()); + } + + public function testGetTotalTimeReturnsExpectedResults() + { + $typeName = 'user'; + $index = $this->_createIndex(); + $type = $index->getType($typeName); + + // Adds 1 document to the index + $docId = 3; + $doc1 = new Document($docId, array('username' => 'hans')); + $type->addDocument($doc1); + + // Refreshes index + $index->refresh(); + + $resultSet = $type->search('hans'); + + $this->assertNotNull($resultSet->getTotalTime(), 'Get Total Time should never be a null value'); + $this->assertEquals( + 'integer', + getType($resultSet->getTotalTime()), + 'Total Time should be an integer' + ); + } + + public function testHasFields() + { + $data = array('value set'); + + $result = new Result(array()); + $this->assertFalse($result->hasFields()); + + $result = new Result(array('_source' => $data)); + $this->assertFalse($result->hasFields()); + + $result = new Result(array('fields' => $data)); + $this->assertTrue($result->hasFields()); + $this->assertEquals($data, $result->getFields()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/ScanAndScrollTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/ScanAndScrollTest.php new file mode 100644 index 00000000..a64670bb --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/ScanAndScrollTest.php @@ -0,0 +1,115 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Document; +use Elastica\Query; +use Elastica\ResultSet; +use Elastica\ScanAndScroll; +use Elastica\Search; +use Elastica\Test\Base as BaseTest; + +class ScanAndScrollTest extends BaseTest { + + public function testConstruct() { + $scanAndScroll = $this->_prepareScanAndScroll(); + + $this->assertInstanceOf('Elastica\ScanAndScroll', $scanAndScroll); + } + + public function testDefaultProperties() { + $scanAndScroll = $this->_prepareScanAndScroll(); + + $this->assertEquals('1m', $scanAndScroll->expiryTime); + $this->assertEquals(1000, $scanAndScroll->sizePerShard); + } + + public function testQuerySizeOverride() { + $query = new Query(); + $query->setSize(100); + + $index = $this->_createIndex('test_1'); + $index->refresh(); // Waits for the index to be fully created. + $type = $index->getType('scanAndScrollTest'); + + $search = new Search($this->_getClient()); + $search->addIndex($index)->addType($type); + $search->setQuery($query); + + $scanAndScroll = new ScanAndScroll($search); + $scanAndScroll->sizePerShard = 10; + $scanAndScroll->rewind(); + + $this->assertEquals(10, $query->getParam('size')); + } + + public function testSizePerShard() { + $search = $this->_prepareSearch('test_2', 2, 20); + + $scanAndScroll = new ScanAndScroll($search); + $scanAndScroll->sizePerShard = 5; + $scanAndScroll->rewind(); + + $this->assertEquals(10, $scanAndScroll->current()->count()); + } + + public function testScrollId() { + $search = $this->_prepareSearch('test_3', 1, 2); + + $scanAndScroll = new ScanAndScroll($search); + $scanAndScroll->sizePerShard = 1; + + $scanAndScroll->rewind(); + $this->assertEquals( + $scanAndScroll->current()->getResponse()->getScrollId(), + $scanAndScroll->key() + ); + } + + public function testForeach() { + $search = $this->_prepareSearch('test_4', 2, 11); + + $scanAndScroll = new ScanAndScroll($search); + $scanAndScroll->sizePerShard = 5; + + // We expect 2 scrolls: + // 1. with 10 hits, + // 2. with 1 hit + // Note: there is a 3. scroll with 0 hits + + $count = 0; + foreach($scanAndScroll as $resultSet) { + /** @var ResultSet $resultSet */ + $count++; + + switch(true) { + case $count == 1: $this->assertEquals(10, $resultSet->count()); break; + case $count == 2: $this->assertEquals(1, $resultSet->count()); break; + } + } + + $this->assertEquals(2, $count); + } + + private function _prepareScanAndScroll() { + return new ScanAndScroll(new Search($this->_getClient())); + } + + private function _prepareSearch($indexName, $indexShards, $docs) { + $index = $this->_createIndex($indexName, true, $indexShards); + $type = $index->getType('scanAndScrollTest'); + + $insert = array(); + for ($x = 1; $x <= $docs; $x++) { + $insert[] = new Document($x, array('id' => $x, 'key' => 'value')); + } + + $type->addDocuments($insert); + $index->refresh(); + + $search = new Search($this->_getClient()); + $search->addIndex($index)->addType($type); + + return $search; + } +}
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/ScriptFieldsTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/ScriptFieldsTest.php new file mode 100644 index 00000000..a3dd0d51 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/ScriptFieldsTest.php @@ -0,0 +1,95 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Document; +use Elastica\Query; +use Elastica\Script; +use Elastica\ScriptFields; +use Elastica\Test\Base as BaseTest; + +class ScriptFieldsTest extends BaseTest +{ + protected $index; + + public function setUp() + { + $this->index = $this->_createIndex(); + } + + public function tearDown() + { + $this->index->delete(); + } + + public function testNewScriptFields() + { + $script = new Script('1 + 2'); + + // addScript + $scriptFields = new ScriptFields; + $scriptFields->addScript('test', $script); + $this->assertEquals($scriptFields->getParam('test'), $script->toArray()); + + // setScripts + $scriptFields = new ScriptFields; + $scriptFields->setScripts(array( + 'test' => $script + )); + $this->assertEquals($scriptFields->getParam('test'), $script->toArray()); + + // Constructor + $scriptFields = new ScriptFields(array( + 'test' => $script + )); + $this->assertEquals($scriptFields->getParam('test'), $script->toArray()); + } + + public function testSetScriptFields() + { + $query = new Query; + $script = new Script('1 + 2'); + + $scriptFields = new ScriptFields(array( + 'test' => $script + )); + $query->setScriptFields($scriptFields); + $this->assertEquals($query->getParam('script_fields'), $scriptFields->toArray()); + + $query->setScriptFields(array( + 'test' => $script + )); + $this->assertEquals($query->getParam('script_fields'), $scriptFields->toArray()); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testNameException() + { + $script = new Script('1 + 2'); + $scriptFields = new ScriptFields(array($script)); + } + + public function testQuery() + { + $type = $this->index->getType('test'); + + $doc = new Document(1, array('firstname' => 'guschti', 'lastname' => 'ruflin')); + $type->addDocument($doc); + $this->index->refresh(); + + $query = new Query(); + $script = new Script('1 + 2'); + $scriptFields = new ScriptFields(array( + 'test' => $script + )); + $query->setScriptFields($scriptFields); + + $resultSet = $type->search($query); + $first = $resultSet->current()->getData(); + + // 1 + 2 + $this->assertEquals(3, $first['test'][0]); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/ScriptTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/ScriptTest.php new file mode 100644 index 00000000..0a11d118 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/ScriptTest.php @@ -0,0 +1,129 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Script; +use Elastica\Test\Base as BaseTest; + +class ScriptTest extends BaseTest +{ + public function testConstructor() + { + $value = "_score * doc['my_numeric_field'].value"; + $script = new Script($value); + + $expected = array( + 'script' => $value, + ); + $this->assertEquals($value, $script->getScript()); + $this->assertEquals($expected, $script->toArray()); + + $params = array( + 'param1' => 'one', + 'param2' => 10, + ); + + $script = new Script($value, $params); + + $expected = array( + 'script' => $value, + 'params' => $params, + ); + + $this->assertEquals($value, $script->getScript()); + $this->assertEquals($params, $script->getParams()); + $this->assertEquals($expected, $script->toArray()); + + $lang = 'mvel'; + + $script = new Script($value, $params, $lang); + + $expected = array( + 'script' => $value, + 'params' => $params, + 'lang' => $lang, + ); + + $this->assertEquals($value, $script->getScript()); + $this->assertEquals($params, $script->getParams()); + $this->assertEquals($lang, $script->getLang()); + $this->assertEquals($expected, $script->toArray()); + } + + public function testCreateString() + { + $string = '_score * 2.0'; + $script = Script::create($string); + + $this->assertInstanceOf('Elastica\Script', $script); + + $this->assertEquals($string, $script->getScript()); + + $expected = array( + 'script' => $string, + ); + $this->assertEquals($expected, $script->toArray()); + } + + public function testCreateScript() + { + $data = new Script('_score * 2.0'); + + $script = Script::create($data); + + $this->assertInstanceOf('Elastica\Script', $script); + $this->assertSame($data, $script); + } + + public function testCreateArray() + { + $string = '_score * 2.0'; + $lang = 'mvel'; + $params = array( + 'param1' => 'one', + 'param2' => 1, + ); + $array = array( + 'script' => $string, + 'lang' => $lang, + 'params' => $params, + ); + + $script = Script::create($array); + + $this->assertInstanceOf('Elastica\Script', $script); + + $this->assertEquals($string, $script->getScript()); + $this->assertEquals($params, $script->getParams()); + $this->assertEquals($lang, $script->getLang()); + + $this->assertEquals($array, $script->toArray()); + } + + /** + * @dataProvider dataProviderCreateInvalid + * @expectedException \Elastica\Exception\InvalidException + */ + public function testCreateInvalid($data) + { + Script::create($data); + } + + /** + * @return array + */ + public function dataProviderCreateInvalid() + { + return array( + array( + new \stdClass + ), + array( + array('params' => array('param1' => 'one')), + ), + array( + array('script' => '_score * 2.0', 'params' => 'param'), + ) + ); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/SearchTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/SearchTest.php new file mode 100644 index 00000000..e08d2d60 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/SearchTest.php @@ -0,0 +1,500 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Client; +use Elastica\Document; +use Elastica\Index; +use Elastica\Query\Builder; +use Elastica\Query\MatchAll; +use Elastica\Query\QueryString; +use Elastica\Query\FunctionScore; +use Elastica\Query; +use Elastica\Script; +use Elastica\Search; +use Elastica\Test\Base as BaseTest; +use Elastica\Type; + +class SearchTest extends BaseTest +{ + public function testConstruct() + { + $client = $this->_getClient(); + $search = new Search($client); + + $this->assertInstanceOf('Elastica\Search', $search); + $this->assertSame($client, $search->getClient()); + } + + public function testAddIndex() + { + $client = $this->_getClient(); + $search = new Search($client); + + $index1 = $this->_createIndex('test1'); + $index2 = $this->_createIndex('test2'); + + $search->addIndex($index1); + $indices = $search->getIndices(); + + $this->assertEquals(1, count($indices)); + + $search->addIndex($index2); + $indices = $search->getIndices(); + + $this->assertEquals(2, count($indices)); + + $this->assertTrue(in_array($index1->getName(), $indices)); + $this->assertTrue(in_array($index2->getName(), $indices)); + + // Add string + $search->addIndex('test3'); + $indices = $search->getIndices(); + + $this->assertEquals(3, count($indices)); + $this->assertTrue(in_array('test3', $indices)); + } + + public function testAddIndices() + { + $client = $this->_getClient(); + $search = new Search($client); + + $indices = array(); + $indices[] = $client->getIndex('elastica_test1'); + $indices[] = $client->getIndex('elastica_test2'); + + $search->addIndices($indices); + + $this->assertEquals(2, count($search->getIndices())); + } + + public function testAddType() + { + $client = $this->_getClient(); + $search = new Search($client); + + $index = $this->_createIndex(); + + $type1 = $index->getType('type1'); + $type2 = $index->getType('type2'); + + $this->assertEquals(array(), $search->getTypes()); + + $search->addType($type1); + $types = $search->getTypes(); + + $this->assertEquals(1, count($types)); + + $search->addType($type2); + $types = $search->getTypes(); + + $this->assertEquals(2, count($types)); + + $this->assertTrue(in_array($type1->getName(), $types)); + $this->assertTrue(in_array($type2->getName(), $types)); + + // Add string + $search->addType('test3'); + $types = $search->getTypes(); + + $this->assertEquals(3, count($types)); + $this->assertTrue(in_array('test3', $types)); + } + + public function testAddTypes() + { + $client = $this->_getClient(); + $search = new Search($client); + + $index = $this->_createIndex(); + + $types = array(); + $types[] = $index->getType('type1'); + $types[] = $index->getType('type2'); + + $search->addTypes($types); + + $this->assertEquals(2, count($search->getTypes())); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testAddTypeInvalid() + { + $client = $this->_getClient(); + $search = new Search($client); + + $search->addType(new \stdClass()); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testAddIndexInvalid() + { + $client = $this->_getClient(); + $search = new Search($client); + + $search->addIndex(new \stdClass()); + } + + public function testGetPath() + { + $client = $this->_getClient(); + $search1 = new Search($client); + $search2 = new Search($client); + + $index1 = $this->_createIndex('test1'); + $index2 = $this->_createIndex('test2'); + + $type1 = $index1->getType('type1'); + $type2 = $index1->getType('type2'); + + // No index + $this->assertEquals('/_search', $search1->getPath()); + + // Only index + $search1->addIndex($index1); + $this->assertEquals($index1->getName() . '/_search', $search1->getPath()); + + // MUltiple index, no types + $search1->addIndex($index2); + $this->assertEquals($index1->getName() . ',' . $index2->getName() . '/_search', $search1->getPath()); + + // Single type, no index + $search2->addType($type1); + $this->assertEquals('_all/' . $type1->getName() . '/_search', $search2->getPath()); + + // Multiple types + $search2->addType($type2); + $this->assertEquals('_all/' . $type1->getName() . ',' . $type2->getName() . '/_search', $search2->getPath()); + + // Combine index and types + $search2->addIndex($index1); + $this->assertEquals($index1->getName() . '/' . $type1->getName() . ',' . $type2->getName() . '/_search', $search2->getPath()); + } + + public function testSearchRequest() + { + $client = $this->_getClient(); + $search1 = new Search($client); + + $index1 = $this->_createIndex('test1'); + $index2 = $this->_createIndex('test2'); + + $type1 = $index1->getType('hello1'); + + $result = $search1->search(array()); + $this->assertFalse($result->getResponse()->hasError()); + + $search1->addIndex($index1); + + $result = $search1->search(array()); + $this->assertFalse($result->getResponse()->hasError()); + + $search1->addIndex($index2); + + $result = $search1->search(array()); + $this->assertFalse($result->getResponse()->hasError()); + + $search1->addType($type1); + + $result = $search1->search(array()); + $this->assertFalse($result->getResponse()->hasError()); + } + + public function testSearchScrollRequest() + { + $client = $this->_getClient(); + + $index = $this->_createIndex('test'); + $type = $index->getType('scrolltest'); + + $docs = array(); + for ($x = 1; $x <= 10; $x++) { + $docs[] = new Document($x, array('id' => $x, 'testscroll' => 'jbafford')); + } + + $type->addDocuments($docs); + $index->refresh(); + + $search = new Search($client); + $search->addIndex($index)->addType($type); + $result = $search->search(array(), array( + Search::OPTION_SEARCH_TYPE => Search::OPTION_SEARCH_TYPE_SCAN, + Search::OPTION_SCROLL => '5m', + Search::OPTION_SIZE => 5, + )); + $this->assertFalse($result->getResponse()->hasError()); + + $scrollId = $result->getResponse()->getScrollId(); + $this->assertNotEmpty($scrollId); + + //There are 10 items, and we're scrolling with a size of 5 + //So we should get two results of 5 items, and then no items + //We should also have sent the raw scroll_id as the HTTP request body + $search = new Search($client); + $result = $search->search(array(), array( + Search::OPTION_SCROLL => '5m', + Search::OPTION_SCROLL_ID => $scrollId, + )); + $this->assertFalse($result->getResponse()->hasError()); + $this->assertEquals(5, count($result->getResults())); + $this->assertArrayNotHasKey(Search::OPTION_SCROLL_ID, $search->getClient()->getLastRequest()->getQuery()); + $this->assertEquals($scrollId, $search->getClient()->getLastRequest()->getData()); + + $result = $search->search(array(), array( + Search::OPTION_SCROLL => '5m', + Search::OPTION_SCROLL_ID => $scrollId, + )); + $this->assertFalse($result->getResponse()->hasError()); + $this->assertEquals(5, count($result->getResults())); + $this->assertArrayNotHasKey(Search::OPTION_SCROLL_ID, $search->getClient()->getLastRequest()->getQuery()); + $this->assertEquals($scrollId, $search->getClient()->getLastRequest()->getData()); + + $result = $search->search(array(), array( + Search::OPTION_SCROLL => '5m', + Search::OPTION_SCROLL_ID => $scrollId, + )); + $this->assertFalse($result->getResponse()->hasError()); + $this->assertEquals(0, count($result->getResults())); + $this->assertArrayNotHasKey(Search::OPTION_SCROLL_ID, $search->getClient()->getLastRequest()->getQuery()); + $this->assertEquals($scrollId, $search->getClient()->getLastRequest()->getData()); + } + + /** + * Default Limit tests for \Elastica\Search + */ + public function testLimitDefaultSearch() + { + $client = $this->_getClient(); + $search = new Search($client); + + $index = $client->getIndex('zero'); + $index->create(array('index' => array('number_of_shards' => 1, 'number_of_replicas' => 0)), true); + + $docs = array(); + $docs[] = new Document(1, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(2, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(3, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(4, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(5, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(6, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(7, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(8, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(9, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(10, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(11, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $type = $index->getType('zeroType'); + $type->addDocuments($docs); + $index->refresh(); + + $search->addIndex($index)->addType($type); + + // default limit results (default limit is 10) + $resultSet = $search->search('farrelley'); + $this->assertEquals(10, $resultSet->count()); + + // limit = 1 + $resultSet = $search->search('farrelley', 1); + $this->assertEquals(1, $resultSet->count()); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testArrayConfigSearch() + { + $client = $this->_getClient(); + $search = new Search($client); + + $index = $client->getIndex('zero'); + $index->create(array('index' => array('number_of_shards' => 1, 'number_of_replicas' => 0)), true); + + $docs = array(); + for ($i = 0; $i < 11; $i++) { + $docs[] = new Document($i, array('id' => 1, 'email' => 'test@test.com', 'username' => 'test')); + } + + $type = $index->getType('zeroType'); + $type->addDocuments($docs); + $index->refresh(); + + $search->addIndex($index)->addType($type); + //Backward compatibility, integer => limit + // default limit results (default limit is 10) + $resultSet = $search->search('test'); + $this->assertEquals(10, $resultSet->count()); + + // limit = 1 + $resultSet = $search->search('test', 1); + $this->assertEquals(1, $resultSet->count()); + + //Array with limit + $resultSet = $search->search('test', array('limit' => 2)); + $this->assertEquals(2, $resultSet->count()); + + //Array with size + $resultSet = $search->search('test', array('size' => 2)); + $this->assertEquals(2, $resultSet->count()); + + //Array with from + $resultSet = $search->search('test', array('from' => 10)); + $this->assertEquals(10, $resultSet->current()->getId()); + + //Array with routing + $resultSet = $search->search('test', array('routing' => 'r1,r2')); + $this->assertEquals(10, $resultSet->count()); + + //Array with limit and routing + $resultSet = $search->search('test', array('limit' => 5, 'routing' => 'r1,r2')); + $this->assertEquals(5, $resultSet->count()); + + //Search types + $resultSet = $search->search('test', array('limit' => 5, 'search_type' => 'count')); + $this->assertTrue(($resultSet->count() === 0) && $resultSet->getTotalHits() === 11); + + //Timeout - this one is a bit more tricky to test + $script = new Script('Thread.sleep(100); return _score;'); + $query = new FunctionScore(); + $query->addScriptScoreFunction($script); + $resultSet = $search->search($query, array('timeout' => 50)); + $this->assertTrue($resultSet->hasTimedOut()); + + // Throws InvalidException + $resultSet = $search->search('test', array('invalid_option' => 'invalid_option_value')); + } + + public function testSearchWithVersionOption() + { + $index = $this->_createIndex('test1'); + $doc = new Document(1, array('id' => 1, 'email' => 'test@test.com', 'username' => 'ruflin')); + $index->getType('test')->addDocument($doc); + $index->refresh(); + + $search = new Search($index->getClient()); + $search->addIndex($index); + + // Version param should not be inside by default + $results = $search->search(new MatchAll()); + $hit = $results->current(); + $this->assertEquals(array(), $hit->getParam('_version')); + + // Added version param to result + $results = $search->search(new MatchAll(), array('version' => true)); + $hit = $results->current(); + $this->assertEquals(1, $hit->getParam('_version')); + } + + public function testCountRequest() + { + $client = $this->_getClient(); + $search = new Search($client); + + $index = $client->getIndex('zero'); + $index->create(array('index' => array('number_of_shards' => 1, 'number_of_replicas' => 0)), true); + + $docs = array(); + $docs[] = new Document(1, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(2, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(3, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(4, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(5, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(6, array('id' => 1, 'email' => 'test@test.com', 'username' => 'marley')); + $docs[] = new Document(7, array('id' => 1, 'email' => 'test@test.com', 'username' => 'marley')); + $docs[] = new Document(8, array('id' => 1, 'email' => 'test@test.com', 'username' => 'marley')); + $docs[] = new Document(9, array('id' => 1, 'email' => 'test@test.com', 'username' => 'marley')); + $docs[] = new Document(10, array('id' => 1, 'email' => 'test@test.com', 'username' => 'marley')); + $docs[] = new Document(11, array('id' => 1, 'email' => 'test@test.com', 'username' => 'marley')); + + $type = $index->getType('zeroType'); + $type->addDocuments($docs); + $index->refresh(); + + $search->addIndex($index)->addType($type); + + $count = $search->count('farrelley'); + $this->assertEquals(5, $count); + + $count = $search->count('marley'); + $this->assertEquals(6, $count); + + $count = $search->count(); + $this->assertEquals(6, $count, 'Uses previous query set'); + + $count = $search->count(new MatchAll()); + $this->assertEquals(11, $count); + + $count = $search->count('bunny'); + $this->assertEquals(0, $count); + } + + public function testEmptySearch() + { + $client = $this->_getClient(); + $search = new Search($client); + + $index = $client->getIndex('zero'); + $index->create(array('index' => array('number_of_shards' => 1, 'number_of_replicas' => 0)), true); + $docs = array(); + $docs[] = new Document(1, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(2, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(3, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(4, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(5, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(6, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(7, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(8, array('id' => 1, 'email' => 'test@test.com', 'username' => 'bunny')); + $docs[] = new Document(9, array('id' => 1, 'email' => 'test@test.com', 'username' => 'bunny')); + $docs[] = new Document(10, array('id' => 1, 'email' => 'test@test.com', 'username' => 'bunny')); + $docs[] = new Document(11, array('id' => 1, 'email' => 'test@test.com', 'username' => 'bunny')); + $type = $index->getType('zeroType'); + $type->addDocuments($docs); + $index->refresh(); + + $search->addIndex($index)->addType($type); + $resultSet = $search->search(); + $this->assertInstanceOf('Elastica\ResultSet', $resultSet); + $this->assertCount(10, $resultSet); + $this->assertEquals(11, $resultSet->getTotalHits()); + + $query = new QueryString('bunny'); + $search->setQuery($query); + + $resultSet = $search->search(); + + $this->assertCount(4, $resultSet); + $this->assertEquals(4, $resultSet->getTotalHits()); + $source = $resultSet->current()->getSource(); + $this->assertEquals('bunny', $source['username']); + } + + public function testCount() { + $index = $this->_createIndex('eeee'); + $search = new Search($index->getClient()); + $type = $index->getType('test'); + + $doc = new Document(1, array('id' => 1, 'username' => 'ruflin')); + + $type->addDocument($doc); + $index->refresh(); + + $search->addIndex($index); + $search->addType($type); + + $result1 = $search->count(new \Elastica\Query\MatchAll()); + $this->assertEquals(1, $result1); + + + $result2 = $search->count(new \Elastica\Query\MatchAll(), true); + $this->assertInstanceOf('\Elastica\ResultSet', $result2); + $this->assertEquals(1, $result2->getTotalHits()); + } + + public function testScanAndScroll() { + $search = new Search($this->_getClient()); + $this->assertInstanceOf('Elastica\ScanAndScroll', $search->scanAndScroll()); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/SnapshotTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/SnapshotTest.php new file mode 100644 index 00000000..3ac5bfe2 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/SnapshotTest.php @@ -0,0 +1,112 @@ +<?php + +namespace Elastica\Test; + + +use Elastica\Document; +use Elastica\Index; +use Elastica\Snapshot; + +class SnapshotTest extends Base +{ + /** + * @var Snapshot + */ + protected $_snapshot; + + /** + * @var Index + */ + protected $_index; + + /** + * @var Document[] + */ + protected $_docs; + + protected function setUp() + { + parent::setUp(); + $this->_snapshot = new Snapshot($this->_getClient()); + + $this->_index = $this->_createIndex("test_snapshot"); + $this->_docs = array( + new Document("1", array("city" => "San Diego")), + new Document("2", array("city" => "San Luis Obispo")), + new Document("3", array("city" => "San Francisco")), + ); + $this->_index->getType("test")->addDocuments($this->_docs); + $this->_index->refresh(); + } + + protected function tearDown() + { + parent::tearDown(); + $this->_index->delete(); + } + + public function testRegisterRepository() + { + $name = "test_register"; + $location = "/tmp/test_register"; + + $response = $this->_snapshot->registerRepository($name, "fs", array("location" => $location)); + $this->assertTrue($response->isOk()); + + $response = $this->_snapshot->getRepository($name); + $this->assertEquals($location, $response["settings"]["location"]); + + // attempt to retrieve a repository which does not exist + $this->setExpectedException('Elastica\Exception\NotFoundException'); + $this->_snapshot->getRepository("foobar"); + } + + public function testSnapshotAndRestore() + { + $repositoryName = "test_repository"; + $location = "/tmp/{$repositoryName}"; + + // register the repository + $response = $this->_snapshot->registerRepository($repositoryName, "fs", array("location" => $location)); + $this->assertTrue($response->isOk()); + + // create a snapshot of our test index + $snapshotName = "test_snapshot_1"; + $response = $this->_snapshot->createSnapshot($repositoryName, $snapshotName, array("indices" => $this->_index->getName()), true); + + // ensure that the snapshot was created properly + $this->assertTrue($response->isOk()); + $this->assertArrayHasKey("snapshot", $response->getData()); + $data = $response->getData(); + $this->assertContains($this->_index->getName(), $data["snapshot"]["indices"]); + $this->assertEquals(1, sizeof($data["snapshot"]["indices"])); // only the specified index should be present + $this->assertEquals($snapshotName, $data["snapshot"]["snapshot"]); + + // retrieve data regarding the snapshot + $response = $this->_snapshot->getSnapshot($repositoryName, $snapshotName); + $this->assertContains($this->_index->getName(), $response["indices"]); + + // delete our test index + $this->_index->delete(); + + // restore the index from our snapshot + $response = $this->_snapshot->restoreSnapshot($repositoryName, $snapshotName, array(), true); + $this->assertTrue($response->isOk()); + + $this->_index->refresh(); + $this->_index->optimize(); + + // ensure that the index has been restored + $count = $this->_index->getType("test")->count(); + $this->assertEquals(sizeof($this->_docs), $count); + + // delete the snapshot + $response = $this->_snapshot->deleteSnapshot($repositoryName, $snapshotName); + $this->assertTrue($response->isOk()); + + // ensure that the snapshot has been deleted + $this->setExpectedException('Elastica\Exception\NotFoundException'); + $this->_snapshot->getSnapshot($repositoryName, $snapshotName); + } +} +
\ No newline at end of file diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/StatusTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/StatusTest.php new file mode 100644 index 00000000..14d7950a --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/StatusTest.php @@ -0,0 +1,116 @@ +<?php + +namespace Elastica\Test; +use Elastica\Client; +use Elastica\Exception\ResponseException; +use Elastica\Status; +use Elastica\Test\Base as BaseTest; + +class StatusTest extends BaseTest +{ + public function testGetResponse() + { + $index = $this->_createIndex(); + $status = new Status($index->getClient()); + $this->assertInstanceOf('Elastica\Response', $status->getResponse()); + } + + public function testGetIndexStatuses() + { + $index = $this->_createIndex(); + + $status = new Status($index->getClient()); + $statuses = $status->getIndexStatuses(); + + $this->assertInternalType('array', $statuses); + + foreach ($statuses as $indexStatus) { + $this->assertInstanceOf('Elastica\Index\Status', $indexStatus); + } + } + + public function testGetIndexNames() + { + $indexName = 'test'; + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + $index->create(array(), true); + $index = $this->_createIndex(); + $index->refresh(); + $index->optimize(); + + $status = new Status($index->getClient()); + $names = $status->getIndexNames(); + + $this->assertInternalType('array', $names); + $this->assertContains($index->getName(), $names); + + foreach ($names as $name) { + $this->assertInternalType('string', $name); + } + } + + public function testIndexExists() + { + $indexName = 'elastica_test'; + $aliasName = 'elastica_test-alias'; + + $client = $this->_getClient(); + $index = $client->getIndex($indexName); + + try { + // Make sure index is deleted first + $index->delete(); + } catch (ResponseException $e) { + } + + $status = new Status($client); + $this->assertFalse($status->indexExists($indexName)); + $index->create(); + + $status->refresh(); + $this->assertTrue($status->indexExists($indexName)); + } + + public function testAliasExists() + { + $indexName = 'test'; + $aliasName = 'elastica_test-alias'; + + $index1 = $this->_createIndex(); + + $status = new Status($index1->getClient()); + + foreach ($status->getIndicesWithAlias($aliasName) as $tmpIndex) { + $tmpIndex->removeAlias($aliasName); + } + + $this->assertFalse($status->aliasExists($aliasName)); + + $index1->addAlias($aliasName); + $status->refresh(); + $this->assertTrue($status->aliasExists($aliasName)); + + $indicesWithAlias = $status->getIndicesWithAlias($aliasName); + $this->assertEquals(array("elastica_$indexName"), array_map( + function($index) { + return $index->getName(); + }, $indicesWithAlias)); + } + + public function testServerStatus() + { + $client = $this->_getClient(); + $status = $client->getStatus(); + $serverStatus = $status->getServerStatus(); + + $this->assertTrue(!empty($serverStatus) ); + $this->assertTrue('array' == gettype($serverStatus)); + $this->assertArrayHasKey('status', $serverStatus); + $this->assertTrue($serverStatus['status'] == 200); + $this->assertArrayHasKey('version', $serverStatus); + + $versionInfo = $serverStatus['version']; + $this->assertArrayHasKey('number', $versionInfo); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Suggest/PhraseTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Suggest/PhraseTest.php new file mode 100644 index 00000000..eda08ba0 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Suggest/PhraseTest.php @@ -0,0 +1,85 @@ +<?php + +namespace Elastica\Test\Suggest; + +use Elastica\Suggest; +use Elastica\Suggest\CandidateGenerator\DirectGenerator; +use Elastica\Suggest\Phrase; +use Elastica\Test\Base as BaseTest; +use Elastica\Query; +use Elastica\Document; +use Elastica\Index; + +class PhraseTest extends BaseTest +{ + const TEST_TYPE = 'testSuggestType'; + + /** + * @var Index + */ + protected $_index; + + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex('test_suggest_phrase'); + $docs = array(); + $docs[] = new Document(1, array('text' => 'Github is pretty cool')); + $docs[] = new Document(2, array('text' => 'Elasticsearch is bonsai cool')); + $docs[] = new Document(3, array('text' => 'This is a test phrase')); + $docs[] = new Document(4, array('text' => 'Another sentence for testing')); + $docs[] = new Document(5, array('text' => 'Some more words here')); + $type = $this->_index->getType(self::TEST_TYPE); + $type->addDocuments($docs); + $this->_index->refresh(); + } + + protected function tearDown() + { + $this->_index->delete(); + } + + public function testToArray() + { + $suggest = new Suggest(); + $phraseSuggest = new Phrase('suggest1', 'text'); + $phraseSuggest->setText('elasticsearch is bansai coor'); + $phraseSuggest->setAnalyzer('simple'); + $suggest->addSuggestion($phraseSuggest); + $suggest->setGlobalText('global!'); + + $expected = array( + 'suggest' => array( + 'text' => 'global!', + 'suggest1' => array( + 'text' => 'elasticsearch is bansai coor', + 'phrase' => array( + 'field' => 'text', + 'analyzer' => 'simple' + ) + ) + ) + ); + + $this->assertEquals($expected, $suggest->toArray()); + } + + public function testPhraseSuggest() + { + $suggest = new Suggest(); + $phraseSuggest = new Phrase('suggest1', 'text'); + $phraseSuggest->setText("elasticsearch is bansai coor"); + $phraseSuggest->setAnalyzer("simple")->setHighlight("<suggest>", "</suggest>")->setStupidBackoffSmoothing(0.4); + $phraseSuggest->addCandidateGenerator(new DirectGenerator("text")); + $suggest->addSuggestion($phraseSuggest); + + $result = $this->_index->search($suggest); + $suggests = $result->getSuggests(); + + // 3 suggestions should be returned: One in which both misspellings are corrected, and two in which only one misspelling is corrected. + $this->assertEquals(3, sizeof($suggests['suggest1'][0]['options'])); + + $this->assertEquals("elasticsearch is <suggest>bonsai cool</suggest>", $suggests['suggest1'][0]['options'][0]['highlighted']); + $this->assertEquals("elasticsearch is bonsai cool", $suggests['suggest1'][0]['options'][0]['text']); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Suggest/TermTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Suggest/TermTest.php new file mode 100644 index 00000000..7765f1bb --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Suggest/TermTest.php @@ -0,0 +1,104 @@ +<?php + +namespace Elastica\Test\Suggest; + +use Elastica\Suggest; +use Elastica\Suggest\Term; +use Elastica\Test\Base as BaseTest; +use Elastica\Query; +use Elastica\Document; +use Elastica\Index; + +class TermTest extends BaseTest +{ + const TEST_TYPE = 'testSuggestType'; + + /** + * @var Index + */ + protected $_index; + + protected function setUp() + { + parent::setUp(); + $this->_index = $this->_createIndex('test_suggest'); + $docs = array(); + $docs[] = new Document(1, array('id' => 1, 'text' => 'GitHub')); + $docs[] = new Document(2, array('id' => 1, 'text' => 'Elastic')); + $docs[] = new Document(3, array('id' => 1, 'text' => 'Search')); + $docs[] = new Document(4, array('id' => 1, 'text' => 'Food')); + $docs[] = new Document(5, array('id' => 1, 'text' => 'Flood')); + $docs[] = new Document(6, array('id' => 1, 'text' => 'Folks')); + $type = $this->_index->getType(self::TEST_TYPE); + $type->addDocuments($docs); + $this->_index->refresh(); + } + + protected function tearDown() + { + $this->_index->delete(); + } + + public function testToArray() + { + $suggest = new Suggest(); + $suggest1 = new Term('suggest1', '_all'); + $suggest->addSuggestion($suggest1->setText('Foor')); + $suggest2 = new Term('suggest2', '_all'); + $suggest->addSuggestion($suggest2->setText('Girhub')); + + $expected = array( + 'suggest' => array( + 'suggest1' => array( + 'term' => array( + 'field' => '_all' + ), + 'text' => 'Foor' + ), + 'suggest2' => array( + 'term' => array( + 'field' => '_all' + ), + 'text' => 'Girhub' + ) + ) + ); + + $this->assertEquals($expected, $suggest->toArray()); + } + + public function testSuggestResults() + { + $suggest = new Suggest(); + $suggest1 = new Term('suggest1', '_all'); + $suggest->addSuggestion($suggest1->setText('Foor seach')); + $suggest2 = new Term('suggest2', '_all'); + $suggest->addSuggestion($suggest2->setText('Girhub')); + + $result = $this->_index->search($suggest); + + $this->assertEquals(2, $result->countSuggests()); + + $suggests = $result->getSuggests(); + + // Ensure that two suggestion results are returned for suggest1 + $this->assertEquals(2, sizeof($suggests['suggest1'])); + + $this->assertEquals('github', $suggests['suggest2'][0]['options'][0]['text']); + $this->assertEquals('food', $suggests['suggest1'][0]['options'][0]['text']); + } + + public function testSuggestNoResults() + { + $termSuggest = new Term('suggest1', '_all'); + $termSuggest->setText('Foobar')->setSize(4); + + $result = $this->_index->search($termSuggest); + + $this->assertEquals(1, $result->countSuggests()); + + // Assert that no suggestions were returned + $suggests = $result->getSuggests(); + $this->assertEquals(0, sizeof($suggests['suggest1'][0]['options'])); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/AbstractTransportTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/AbstractTransportTest.php new file mode 100644 index 00000000..4f1c7114 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/AbstractTransportTest.php @@ -0,0 +1,77 @@ +<?php + +namespace Elastica\Test\Transport; + +use Elastica\Transport\AbstractTransport; +use Elastica\Transport\Http; +use Elastica\Connection; +use Elastica\Exception\InvalidException; + +class AbstractTransportTest extends \PHPUnit_Framework_TestCase +{ + /** + * Return transport configuration and the expected HTTP method + * + * @return array[] + */ + public function getValidDefinitions() + { + $connection = new Connection(); + + return array( + array('Http'), + array(array('type' => 'Http')), + array(array('type' => new Http())), + array(new Http()), + ); + } + + /** + * @dataProvider getValidDefinitions + */ + public function testCanCreateTransportInstances($transport) + { + $connection = new Connection(); + $params = array(); + $transport = AbstractTransport::create($transport, $connection, $params); + $this->assertInstanceOf('Elastica\Transport\AbstractTransport', $transport); + $this->assertSame($connection, $transport->getConnection()); + } + + public function getInvalidDefinitions() + { + return array( + array(array('transport' => 'Http')), + array('InvalidTransport'), + ); + } + + /** + * @dataProvider getInvalidDefinitions + * @expectedException Elastica\Exception\InvalidException + * @expectedExceptionMessage Invalid transport + */ + public function testThrowsExecptionOnInvalidTransportDefinition($transport) + { + AbstractTransport::create($transport, new Connection()); + } + + public function testCanInjectParamsWhenUsingArray() + { + $connection = new Connection(); + $params = array( + 'param1' => 'some value', + 'param3' => 'value3', + ); + + $transport = AbstractTransport::create(array( + 'type' => 'Http', + 'param1' => 'value1', + 'param2' => 'value2', + ), $connection, $params); + + $this->assertSame('value1', $transport->getParam('param1')); + $this->assertSame('value2', $transport->getParam('param2')); + $this->assertSame('value3', $transport->getParam('param3')); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/GuzzleTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/GuzzleTest.php new file mode 100644 index 00000000..b2e385bb --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/GuzzleTest.php @@ -0,0 +1,163 @@ +<?php + +namespace Elastica\Test\Transport; + +use Elastica\Client; +use Elastica\Document; +use Elastica\Query; +use Elastica\ResultSet; +use Elastica\Test\Base as BaseTest; +use Elastica\Exception\ResponseException; + +class GuzzleTest extends BaseTest +{ + public static function setUpBeforeClass() + { + if (!class_exists('GuzzleHttp\\Client')) { + self::markTestSkipped('guzzlehttp/guzzle package should be installed to run guzzle transport tests'); + } + } + + public function setUp() + { + if (defined('DEBUG') && !DEBUG) { + $this->markTestSkipped('The DEBUG constant must be set to true for this test to run'); + } + + if (!defined('DEBUG')) { + define('DEBUG', true); + } + } + + /** + * Return transport configuration and the expected HTTP method + * + * @return array[] + */ + public function getConfig() + { + return array( + array( + array('transport' => 'Guzzle'), + 'GET' + ), + array( + array('transport' => array('type' => 'Guzzle', 'postWithRequestBody' => false)), + 'GET' + ), + array( + array('transport' => array('type' => 'Guzzle', 'postWithRequestBody' => true)), + 'POST' + ), + ); + } + + /** + * @dataProvider getConfig + */ + public function testDynamicHttpMethodBasedOnConfigParameter(array $config, $httpMethod) + { + $client = new Client($config); + + $index = $client->getIndex('dynamic_http_method_test'); + $index->create(array(), true); + $type = $index->getType('test'); + $type->addDocument(new Document(1, array('test' => 'test'))); + $index->refresh(); + $resultSet = $index->search('test'); + $info = $resultSet->getResponse()->getTransferInfo(); + $this->assertStringStartsWith($httpMethod, $info['request_header']); + } + + /** + * @dataProvider getConfig + */ + public function testDynamicHttpMethodOnlyAffectsRequestsWithBody(array $config, $httpMethod) + { + $client = new Client($config); + + $status = $client->getStatus(); + $info = $status->getResponse()->getTransferInfo(); + $this->assertStringStartsWith('GET', $info['request_header']); + } + + public function testWithEnvironmentalProxy() + { + putenv('http_proxy=http://127.0.0.1:12345/'); + + $client = new \Elastica\Client(array('transport' => 'Guzzle')); + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(200, $transferInfo['http_code']); + + $client->getConnection()->setProxy(null); // will not change anything + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(200, $transferInfo['http_code']); + + putenv('http_proxy='); + } + + public function testWithEnabledEnvironmentalProxy() + { + putenv('http_proxy=http://127.0.0.1:12346/'); + + $client = new \Elastica\Client(array('transport' => 'Guzzle')); + + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(403, $transferInfo['http_code']); + + $client = new \Elastica\Client(); + $client->getConnection()->setProxy(''); + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(200, $transferInfo['http_code']); + + putenv('http_proxy='); + } + + public function testWithProxy() + { + $client = new \Elastica\Client(array('transport' => 'Guzzle')); + $client->getConnection()->setProxy('http://127.0.0.1:12345'); + + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(200, $transferInfo['http_code']); + } + + public function testWithoutProxy() + { + $client = new \Elastica\Client(array('transport' => 'Guzzle')); + $client->getConnection()->setProxy(''); + + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(200, $transferInfo['http_code']); + } + + public function testBodyReuse() + { + $client = new Client(array('transport' => 'Guzzle')); + + $index = $client->getIndex('elastica_body_reuse_test'); + + $index->create(array(), true); + + $type = $index->getType('test'); + $type->addDocument(new Document(1, array('test' => 'test'))); + + $index->refresh(); + + $resultSet = $index->search(array( + 'query' => array( + 'query_string' => array( + 'query' => 'pew pew pew', + ), + ), + )); + + $this->assertEquals(0, $resultSet->getTotalHits()); + + $response = $index->request('/_search', 'POST'); + $resultSet = new ResultSet($response, Query::create(array())); + + $this->assertEquals(1, $resultSet->getTotalHits()); + } + +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/HttpTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/HttpTest.php new file mode 100644 index 00000000..88c93bea --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/HttpTest.php @@ -0,0 +1,227 @@ +<?php + +namespace Elastica\Test\Transport; + +use Elastica\Client; +use Elastica\Document; +use Elastica\Query; +use Elastica\ResultSet; +use Elastica\Test\Base as BaseTest; +use Elastica\Exception\ResponseException; + +class HttpTest extends BaseTest +{ + public function setUp() + { + if (defined('DEBUG') && !DEBUG) { + $this->markTestSkipped('The DEBUG constant must be set to true for this test to run'); + } + + if (!defined('DEBUG')) { + define('DEBUG', true); + } + } + + /** + * Return transport configuration and the expected HTTP method + * + * @return array[] + */ + public function getConfig() + { + return array( + array( + array('transport' => 'Http'), + 'GET' + ), + array( + array('transport' => array('type' => 'Http', 'postWithRequestBody' => false)), + 'GET' + ), + array( + array('transport' => array('type' => 'Http', 'postWithRequestBody' => true)), + 'POST' + ), + ); + } + + /** + * @dataProvider getConfig + */ + public function testDynamicHttpMethodBasedOnConfigParameter(array $config, $httpMethod) + { + $client = new Client($config); + + $index = $client->getIndex('dynamic_http_method_test'); + + $index->create(array(), true); + + $type = $index->getType('test'); + $type->addDocument(new Document(1, array('test' => 'test'))); + + $index->refresh(); + + $resultSet = $index->search('test'); + + $info = $resultSet->getResponse()->getTransferInfo(); + $this->assertStringStartsWith($httpMethod, $info['request_header']); + } + + /** + * @dataProvider getConfig + */ + public function testDynamicHttpMethodOnlyAffectsRequestsWithBody(array $config, $httpMethod) + { + $client = new Client($config); + + $status = $client->getStatus(); + $info = $status->getResponse()->getTransferInfo(); + $this->assertStringStartsWith('GET', $info['request_header']); + } + + public function testCurlNobodyOptionIsResetAfterHeadRequest() + { + $client = new \Elastica\Client(); + $index = $client->getIndex('curl_test'); + $type = $index->getType('item'); + + // Force HEAD request to set CURLOPT_NOBODY = true + $index->exists(); + + $id = 1; + $data = array('id' => $id, 'name' => 'Item 1'); + $doc = new \Elastica\Document($id, $data); + + $type->addDocument($doc); + + $index->refresh(); + + $doc = $type->getDocument($id); + + // Document should be retrieved correctly + $this->assertSame($data, $doc->getData()); + $this->assertEquals($id, $doc->getId()); + } + + public function testUnicodeData() + { + $client = new \Elastica\Client(); + $index = $client->getIndex('curl_test'); + $type = $index->getType('item'); + + // Force HEAD request to set CURLOPT_NOBODY = true + $index->exists(); + + $id = 22; + $data = array('id' => $id, 'name' => ' + Сегодня, я вижу, особенно грустен твой взгляд, / + И руки особенно тонки, колени обняв. / + Послушай: далеко, далеко, на озере Чад / + Изысканный бродит жираф.'); + + $doc = new \Elastica\Document($id, $data); + + $type->addDocument($doc); + + $index->refresh(); + + $doc = $type->getDocument($id); + + // Document should be retrieved correctly + $this->assertSame($data, $doc->getData()); + $this->assertEquals($id, $doc->getId()); + } + + public function testWithEnvironmentalProxy() + { + putenv('http_proxy=http://127.0.0.1:12345/'); + + $client = new \Elastica\Client(); + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(200, $transferInfo['http_code']); + + $client->getConnection()->setProxy(null); // will not change anything + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(200, $transferInfo['http_code']); + + putenv('http_proxy='); + } + + public function testWithEnabledEnvironmentalProxy() + { + putenv('http_proxy=http://127.0.0.1:12346/'); + + $client = new \Elastica\Client(); + + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(403, $transferInfo['http_code']); + + $client = new \Elastica\Client(); + $client->getConnection()->setProxy(''); + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(200, $transferInfo['http_code']); + + putenv('http_proxy='); + } + + public function testWithProxy() + { + $client = new \Elastica\Client(); + $client->getConnection()->setProxy('http://127.0.0.1:12345'); + + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(200, $transferInfo['http_code']); + } + + public function testWithoutProxy() + { + $client = new \Elastica\Client(); + $client->getConnection()->setProxy(''); + + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(200, $transferInfo['http_code']); + } + + public function testBodyReuse() + { + $client = new Client(); + + $index = $client->getIndex('elastica_body_reuse_test'); + + $index->create(array(), true); + + $type = $index->getType('test'); + $type->addDocument(new Document(1, array('test' => 'test'))); + + $index->refresh(); + + $resultSet = $index->search(array( + 'query' => array( + 'query_string' => array( + 'query' => 'pew pew pew', + ), + ), + )); + + $this->assertEquals(0, $resultSet->getTotalHits()); + + $response = $index->request('/_search', 'POST'); + $resultSet = new ResultSet($response, Query::create(array())); + + $this->assertEquals(1, $resultSet->getTotalHits()); + } + + public function testPostWith0Body() + { + $client = new Client(); + + $index = $client->getIndex('elastica_0_body'); + $index->create(array(), true); + $index->refresh(); + + $tokens = $index->analyze('0'); + + $this->assertNotEmpty($tokens); + } + +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/MemcacheTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/MemcacheTest.php new file mode 100644 index 00000000..17d46d88 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/MemcacheTest.php @@ -0,0 +1,51 @@ +<?php + +namespace Elastica\Test\Transport; + +use Elastica\Client; +use Elastica\Document; +use Elastica\Test\Base as BaseTest; + +class MemcacheTest extends BaseTest +{ + public function setUp() + { + if (!extension_loaded('Memcache')) { + $this->markTestSkipped('pecl/memcache must be installed to run this test case'); + } + } + + public function testExample() + { + // Creates a new index 'xodoa' and a type 'user' inside this index + $host = 'localhost'; + $port = 11211; + $client = new Client(array('host' => $host, 'port' => $port, 'transport' => 'Memcache')); + + $index = $client->getIndex('elastica_test1'); + $index->create(array(), true); + + $type = $index->getType('user'); + + // Adds 1 document to the index + $doc1 = new Document(1, + array('username' => 'hans', 'test' => array('2', '3', '5')) + ); + $type->addDocument($doc1); + + // Adds a list of documents with _bulk upload to the index + $docs = array(); + $docs[] = new Document(2, + array('username' => 'john', 'test' => array('1', '3', '6')) + ); + $docs[] = new Document(3, + array('username' => 'rolf', 'test' => array('2', '3', '7')) + ); + $type->addDocuments($docs); + + // Refresh index + $index->refresh(); + $this->markTestIncomplete('Memcache implementation is not finished yet'); + $resultSet = $type->search('rolf'); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/NullTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/NullTest.php new file mode 100644 index 00000000..c07f5da1 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/NullTest.php @@ -0,0 +1,59 @@ +<?php + +namespace Elastica\Test\Transport; + +use Elastica\Client; +use Elastica\Connection; +use Elastica\Query; +use Elastica\Test\Base as BaseTest; + +/** + * Elastica Null Transport Test + * + * @package Elastica + * @author James Boehmer <james.boehmer@jamesboehmer.com> + */ +class NullTest extends BaseTest +{ + + public function testEmptyResult() + { + // Creates a client with any destination, and verify it returns a response object when executed + $client = $this->_getClient(); + $connection = new Connection(array('transport' => 'Null')); + $client->setConnections(array($connection)); + + $index = $client->getIndex('elasticaNullTransportTest1'); + + $resultSet = $index->search(new Query()); + $this->assertNotNull($resultSet); + + $response = $resultSet->getResponse(); + $this->assertNotNull($response); + + // Validate most of the expected fields in the response data. Consumers of the response + // object have a reasonable expectation of finding "hits", "took", etc + $responseData = $response->getData(); + $this->assertContains("took", $responseData); + $this->assertEquals(0, $responseData["took"]); + $this->assertContains("_shards", $responseData); + $this->assertContains("hits", $responseData); + $this->assertContains("total", $responseData["hits"]); + $this->assertEquals(0, $responseData["hits"]["total"]); + $this->assertContains("params", $responseData); + + $took = $response->getEngineTime(); + $this->assertEquals(0, $took); + + $errorString = $response->getError(); + $this->assertEmpty($errorString); + + $shards = $response->getShardsStatistics(); + $this->assertContains("total", $shards); + $this->assertEquals(0, $shards["total"]); + $this->assertContains("successful", $shards); + $this->assertEquals(0, $shards["successful"]); + $this->assertContains("failed", $shards); + $this->assertEquals(0, $shards["failed"]); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/ThriftTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/ThriftTest.php new file mode 100644 index 00000000..f1698ff6 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Transport/ThriftTest.php @@ -0,0 +1,132 @@ +<?php + +namespace Elastica\Test\Transport; + +use Elastica\Client; +use Elastica\Connection; +use Elastica\Document; +use Elastica\Index; +use Elastica\Query; +use Elastica\Test\Base as BaseTest; + +class ThriftTest extends BaseTest +{ + public static function setUpBeforeClass() + { + if (!class_exists('Elasticsearch\\RestClient')) { + self::markTestSkipped('munkie/elasticsearch-thrift-php package should be installed to run thrift transport tests'); + } + } + + public function testConstruct() + { + $host = 'localhost'; + $port = 9500; + $client = new Client(array('host' => $host, 'port' => $port, 'transport' => 'Thrift')); + + $this->assertEquals($host, $client->getConnection()->getHost()); + $this->assertEquals($port, $client->getConnection()->getPort()); + } + + /** + * @dataProvider configProvider + */ + public function testSearchRequest($config) + { + $this->_checkPlugin(); + + // Creates a new index 'xodoa' and a type 'user' inside this index + $client = new Client($config); + + $index = $client->getIndex('elastica_test1'); + $index->create(array(), true); + + $type = $index->getType('user'); + + // Adds 1 document to the index + $doc1 = new Document(1, + array('username' => 'hans', 'test' => array('2', '3', '5')) + ); + $doc1->setVersion(0); + $type->addDocument($doc1); + + // Adds a list of documents with _bulk upload to the index + $docs = array(); + $docs[] = new Document(2, + array('username' => 'john', 'test' => array('1', '3', '6')) + ); + $docs[] = new Document(3, + array('username' => 'rolf', 'test' => array('2', '3', '7')) + ); + $type->addDocuments($docs); + + // Refresh index + $index->refresh(); + $resultSet = $type->search('rolf'); + + $this->assertEquals(1, $resultSet->getTotalHits()); + } + + /** + * @expectedException \Elastica\Exception\ConnectionException + */ + public function testInvalidHostRequest() + { + $this->_checkPlugin(); + + $client = new Client(array('host' => 'unknown', 'port' => 9555, 'transport' => 'Thrift')); + $client->getStatus(); + } + + /** + * @expectedException \Elastica\Exception\ResponseException + */ + public function testInvalidElasticRequest() + { + $this->_checkPlugin(); + + $connection = new Connection(); + $connection->setHost('localhost'); + $connection->setPort(9500); + $connection->setTransport('Thrift'); + + $client = new Client(); + $client->addConnection($connection); + + $index = new Index($client, 'missing_index'); + $index->getStatus(); + } + + public function configProvider() + { + return array( + array( + array( + 'host' => 'localhost', + 'port' => 9500, + 'transport' => 'Thrift' + ) + ), + array( + array( + 'host' => 'localhost', + 'port' => 9500, + 'transport' => 'Thrift', + 'config' => array( + 'framedTransport' => false, + 'sendTimeout' => 10000, + 'recvTimeout' => 20000, + ) + ) + ) + ); + } + + protected function _checkPlugin() + { + $nodes = $this->_getClient()->getCluster()->getNodes(); + if (!$nodes[0]->getInfo()->hasPlugin('transport-thrift')) { + $this->markTestSkipped("transport-thrift plugin not installed."); + } + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/Type/MappingTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/Type/MappingTest.php new file mode 100644 index 00000000..796bfb8d --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/Type/MappingTest.php @@ -0,0 +1,304 @@ +<?php + +namespace Elastica\Test\Type; + +use Elastica\Document; +use Elastica\Query; +use Elastica\Query\QueryString; +use Elastica\Test\Base as BaseTest; +use Elastica\Type; +use Elastica\Type\Mapping; + +class MappingTest extends BaseTest +{ + public function testMappingStoreFields() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + + $index->create(array(), true); + $type = $index->getType('test'); + + $mapping = new Mapping($type, + array( + 'firstname' => array('type' => 'string', 'store' => 'yes'), + // default is store => no expected + 'lastname' => array('type' => 'string'), + ) + ); + $mapping->disableSource(); + + $type->setMapping($mapping); + + $firstname = 'Nicolas'; + $doc = new Document(1, + array( + 'firstname' => $firstname, + 'lastname' => 'Ruflin' + ) + ); + + $type->addDocument($doc); + + $index->refresh(); + $queryString = new QueryString('ruflin'); + $query = Query::create($queryString); + $query->setFields(array('*')); + + $resultSet = $type->search($query); + $result = $resultSet->current(); + $fields = $result->getFields(); + + $this->assertEquals($firstname, $fields['firstname'][0]); + $this->assertArrayNotHasKey('lastname', $fields); + $this->assertEquals(1, count($fields)); + + $index->flush(); + $document = $type->getDocument(1); + + $this->assertEmpty($document->getData()); + + $index->delete(); + } + + public function testEnableAllField() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + + $mapping = new Mapping($type, array()); + + $mapping->enableAllField(); + + $data = $mapping->toArray(); + $this->assertTrue($data[$type->getName()]['_all']['enabled']); + + $response = $mapping->send(); + $this->assertTrue($response->isOk()); + + $index->delete(); + } + + public function testEnableTtl() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + + $index->create(array(), true); + $type = $index->getType('test'); + + $mapping = new Mapping($type, array()); + + $mapping->enableTtl(); + + $data = $mapping->toArray(); + $this->assertTrue($data[$type->getName()]['_ttl']['enabled']); + + $index->delete(); + } + + public function testNestedMapping() + { + $client = $this->_getClient(); + $index = $client->getIndex('test'); + + $index->create(array(), true); + $type = $index->getType('test'); + + $this->markTestIncomplete('nested mapping is not set right yet'); + $mapping = new Mapping($type, + array( + 'test' => array( + 'type' => 'object', 'store' => 'yes', 'properties' => array( + 'user' => array( + 'properties' => array( + 'firstname' => array('type' => 'string', 'store' => 'yes'), + 'lastname' => array('type' => 'string', 'store' => 'yes'), + 'age' => array('type' => 'integer', 'store' => 'yes'), + ) + ), + ), + ), + ) + ); + + $type->setMapping($mapping); + + $doc = new Document(1, array( + 'user' => array( + 'firstname' => 'Nicolas', + 'lastname' => 'Ruflin', + 'age' => 9 + ), + )); + + $type->addDocument($doc); + + $index->refresh(); + $resultSet = $type->search('ruflin'); + + $index->delete(); + } + + public function testParentMapping() + { + $index = $this->_createIndex(); + $parenttype = new Type($index, 'parenttype'); + $parentmapping = new Mapping($parenttype, + array( + 'name' => array('type' => 'string', 'store' => 'yes') + ) + ); + + $parenttype->setMapping($parentmapping); + + $childtype = new Type($index, 'childtype'); + $childmapping = new Mapping($childtype, + array( + 'name' => array('type' => 'string', 'store' => 'yes'), + ) + ); + $childmapping->setParent('parenttype'); + + $childtype->setMapping($childmapping); + + $data = $childmapping->toArray(); + $this->assertEquals('parenttype', $data[$childtype->getName()]['_parent']['type']); + + $index->delete(); + } + + public function testMappingExample() + { + $index = $this->_createIndex(); + $type = $index->getType('notes'); + + $mapping = new Mapping($type, + array( + 'note' => array( + 'store' => 'yes', 'properties' => array( + 'titulo' => array('type' => 'string', 'store' => 'no', 'include_in_all' => true, 'boost' => 1.0), + 'contenido' => array('type' => 'string', 'store' => 'no', 'include_in_all' => true, 'boost' => 1.0) + ) + ) + ) + ); + + $type->setMapping($mapping); + + $doc = new Document(1, array( + 'note' => array( + array( + 'titulo' => 'nota1', + 'contenido' => 'contenido1' + ), + array( + 'titulo' => 'nota2', + 'contenido' => 'contenido2' + ) + ) + ) + ); + + $type->addDocument($doc); + + $index->delete(); + } + + /** + * Test setting a dynamic template and validate whether the right mapping is applied after adding a document which + * should match the dynamic template. The example is the template_1 from the Elasticsearch documentation. + * + * @link http://www.elasticsearch.org/guide/reference/mapping/root-object-type/ + */ + public function testDynamicTemplate() + { + $index = $this->_createIndex(); + $type = $index->getType('person'); + + // set a dynamic template "template_1" which creates a multi field for multi* matches. + $mapping = new Mapping($type); + $mapping->setParam('dynamic_templates', array( + array('template_1' => array( + 'match' => 'multi*', + 'mapping' => array( + 'type' => 'multi_field', + 'fields' => array( + '{name}' => array('type' => '{dynamic_type}', 'index' => 'analyzed'), + 'org' => array('type' => '{dynamic_type}', 'index' => 'not_analyzed') + ) + ) + )) + )); + + $mapping->send(); + + // when running the tests, the mapping sometimes isn't available yet. Optimize index to enforce reload mapping. + $index->optimize(); + + // create a document which should create a mapping for the field: multiname. + $testDoc = new Document('person1', array('multiname' => 'Jasper van Wanrooy'), $type); + $index->addDocuments(array($testDoc)); + sleep(1); //sleep 1 to ensure that the test passes every time + + // read the mapping from Elasticsearch and assert that the multiname.org field is "not_analyzed" + $newMapping = $type->getMapping(); + $this->assertArrayHasKey('person', $newMapping, + 'Person type not available in mapping from ES. Mapping set at all?'); + $this->assertArrayHasKey('properties', $newMapping['person'], + 'Person type doesnt have any properties. Document properly added?'); + $this->assertArrayHasKey('multiname', $newMapping['person']['properties'], + 'The multiname property is not added to the mapping. Document properly added?'); + $this->assertArrayHasKey('fields', $newMapping['person']['properties']['multiname'], + 'The multiname field of the Person type is presumably not a multi_field type. Dynamic mapping not applied?'); + $this->assertArrayHasKey('org', $newMapping['person']['properties']['multiname']['fields'], + 'The multi* matcher did not create a mapping for the multiname.org property when indexing the document.'); + $this->assertArrayHasKey('index', $newMapping['person']['properties']['multiname']['fields']['org'], + 'Indexing status of the multiname.org not available. Dynamic mapping not fully applied!'); + $this->assertEquals('not_analyzed', $newMapping['person']['properties']['multiname']['fields']['org']['index']); + + $index->delete(); + } + + public function testSetMeta() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + $mapping = new Mapping($type, array( + 'firstname' => array('type' => 'string', 'store' => 'yes'), + 'lastname' => array('type' => 'string') + )); + $mapping->setMeta(array('class' => 'test')); + $type->setMapping($mapping); + + $mappingData = $type->getMapping(); + $this->assertEquals('test', $mappingData['test']['_meta']['class']); + + $index->delete(); + } + + public function testGetters() + { + $index = $this->_createIndex(); + $type = $index->getType('test'); + $properties = array( + 'firstname' => array('type' => 'string', 'store' => 'yes'), + 'lastname' => array('type' => 'string') + ); + $mapping = new Mapping($type, $properties); + $all = array( + "enabled" => true, + "store" => "yes" + ); + $mapping->setParam('_all', $all); + $get_all = $mapping->getParam('_all'); + + $this->assertEquals($get_all, $all); + + $this->assertNull($mapping->getParam('_boost', $all)); + + $this->assertEquals($properties, $mapping->getProperties()); + + $index->delete(); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/TypeTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/TypeTest.php new file mode 100644 index 00000000..40e56c3b --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/TypeTest.php @@ -0,0 +1,823 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Client; +use Elastica\Document; +use Elastica\Exception\NotFoundException; +use Elastica\Exception\ResponseException; +use Elastica\Query; +use Elastica\Query\MatchAll; +use Elastica\Query\SimpleQueryString; +use Elastica\Script; +use Elastica\Search; +use Elastica\Filter\Term; +use Elastica\Type; +use Elastica\Index; +use Elastica\Type\Mapping; +use Elastica\Test\Base as BaseTest; + +class TypeTest extends BaseTest +{ + public function testSearch() + { + $index = $this->_createIndex(); + + $type = new Type($index, 'user'); + + // Adds 1 document to the index + $doc1 = new Document(1, + array('username' => 'hans', 'test' => array('2', '3', '5')) + ); + $type->addDocument($doc1); + + // Adds a list of documents with _bulk upload to the index + $docs = array(); + $docs[] = new Document(2, + array('username' => 'john', 'test' => array('1', '3', '6')) + ); + $docs[] = new Document(3, + array('username' => 'rolf', 'test' => array('2', '3', '7')) + ); + $type->addDocuments($docs); + $index->refresh(); + + $resultSet = $type->search('rolf'); + $this->assertEquals(1, $resultSet->count()); + + $count = $type->count('rolf'); + $this->assertEquals(1, $count); + + // Test if source is returned + $result = $resultSet->current(); + $this->assertEquals(3, $result->getId()); + $data = $result->getData(); + $this->assertEquals('rolf', $data['username']); + } + + public function testCreateSearch() + { + $client = $this->_getClient(); + $index = new Index($client, 'test_index'); + $type = new Type($index, 'test_type'); + + $query = new Query\QueryString('test'); + $options = array( + 'limit' => 5, + 'explain' => true, + ); + + $search = $type->createSearch($query, $options); + + $expected = array( + 'query' => array( + 'query_string' => array( + 'query' => 'test' + ) + ), + 'size' => 5, + 'explain' => true + ); + $this->assertEquals($expected, $search->getQuery()->toArray()); + $this->assertEquals(array('test_index'), $search->getIndices()); + $this->assertTrue($search->hasIndices()); + $this->assertTrue($search->hasIndex($index)); + $this->assertTrue($search->hasIndex('test_index')); + $this->assertFalse($search->hasIndex('test')); + $this->assertEquals(array('test_type'), $search->getTypes()); + $this->assertTrue($search->hasTypes()); + $this->assertTrue($search->hasType($type)); + $this->assertTrue($search->hasType('test_type')); + $this->assertFalse($search->hasType('test_type2')); + } + + public function testCreateSearchWithArray() + { + $client = $this->_getClient(); + $index = new Index($client, 'test_index'); + $type = new Type($index, 'test_type'); + + $query = array( + 'query' => array( + 'query_string' => array( + 'query' => 'test' + ) + ) + ); + + $options = array( + 'limit' => 5, + 'explain' => true, + ); + + $search = $type->createSearch($query, $options); + + $expected = array( + 'query' => array( + 'query_string' => array( + 'query' => 'test' + ) + ), + 'size' => 5, + 'explain' => true + ); + $this->assertEquals($expected, $search->getQuery()->toArray()); + $this->assertEquals(array('test_index'), $search->getIndices()); + $this->assertTrue($search->hasIndices()); + $this->assertTrue($search->hasIndex($index)); + $this->assertTrue($search->hasIndex('test_index')); + $this->assertFalse($search->hasIndex('test')); + $this->assertEquals(array('test_type'), $search->getTypes()); + $this->assertTrue($search->hasTypes()); + $this->assertTrue($search->hasType($type)); + $this->assertTrue($search->hasType('test_type')); + $this->assertFalse($search->hasType('test_type2')); + } + + public function testNoSource() + { + $index = $this->_createIndex(); + + $type = new Type($index, 'user'); + $mapping = new Mapping($type, array( + 'id' => array('type' => 'integer', 'store' => 'yes'), + 'username' => array('type' => 'string', 'store' => 'no'), + )); + $mapping->setSource(array('enabled' => false)); + $type->setMapping($mapping); + + $mapping = $type->getMapping(); + + $this->assertArrayHasKey('user', $mapping); + $this->assertArrayHasKey('properties', $mapping['user']); + $this->assertArrayHasKey('id', $mapping['user']['properties']); + $this->assertArrayHasKey('type', $mapping['user']['properties']['id']); + $this->assertEquals('integer', $mapping['user']['properties']['id']['type']); + + // Adds 1 document to the index + $doc1 = new Document(1, + array('username' => 'hans', 'test' => array('2', '3', '5')) + ); + $type->addDocument($doc1); + + // Adds a list of documents with _bulk upload to the index + $docs = array(); + $docs[] = new Document(2, + array('username' => 'john', 'test' => array('1', '3', '6')) + ); + $docs[] = new Document(3, + array('username' => 'rolf', 'test' => array('2', '3', '7')) + ); + $type->addDocuments($docs); + + // To update index + $index->refresh(); + + $resultSet = $type->search('rolf'); + + $this->assertEquals(1, $resultSet->count()); + + // Tests if no source is in response except id + $result = $resultSet->current(); + $this->assertEquals(3, $result->getId()); + $this->assertEmpty($result->getData()); + } + + public function testDeleteById() + { + $index = $this->_createIndex(); + $type = new Type($index, 'user'); + + // Adds hans, john and rolf to the index + $docs = array( + new Document(1, array('username' => 'hans', 'test' => array('2', '3', '5'))), + new Document(2, array('username' => 'john', 'test' => array('1', '3', '6'))), + new Document(3, array('username' => 'rolf', 'test' => array('2', '3', '7'))), + new Document('foo/bar', array('username' => 'georg', 'test' => array('4', '2', '5'))), + ); + $type->addDocuments($docs); + $index->refresh(); + + // sanity check for rolf + $resultSet = $type->search('rolf'); + $this->assertEquals(1, $resultSet->count()); + $data = $resultSet->current()->getData(); + $this->assertEquals('rolf', $data['username']); + + // delete rolf + $type->deleteById(3); + $index->refresh(); + + // rolf should no longer be there + $resultSet = $type->search('rolf'); + $this->assertEquals(0, $resultSet->count()); + + // sanity check for id with slash + $resultSet = $type->search('georg'); + $this->assertEquals(1, $resultSet->count()); + + // delete georg + $type->deleteById('foo/bar'); + $index->refresh(); + + // georg should no longer be there + $resultSet = $type->search('georg'); + $this->assertEquals(0, $resultSet->count()); + + // it should not be possible to delete the entire type with this method + try { + $type->deleteById(''); + $this->fail('Delete with empty string id should fail'); + } catch (\InvalidArgumentException $e) { + $this->assertTrue(true); + } + + try { + $type->deleteById(' '); + $this->fail('Delete with one space string id should fail'); + } catch (\InvalidArgumentException $e) { + $this->assertTrue(true); + } + + try { + $type->deleteById(null); + $this->fail('Delete with null id should fail'); + } catch (\InvalidArgumentException $e) { + $this->assertTrue(true); + } + + try { + $type->deleteById(array()); + $this->fail('Delete with empty array id should fail'); + } catch (\InvalidArgumentException $e) { + $this->assertTrue(true); + } + + try { + $type->deleteById('*'); + $this->fail('Delete request should fail because of invalid id: *'); + } catch (NotFoundException $e) { + $this->assertTrue(true); + } + + try { + $type->deleteById('*:*'); + $this->fail('Delete request should fail because document with id *.* does not exist'); + } catch (NotFoundException $e) { + $this->assertTrue(true); + } + + try { + $type->deleteById('!'); + $this->fail('Delete request should fail because document with id ! does not exist'); + } catch (NotFoundException $e) { + $this->assertTrue(true); + } + + $index->refresh(); + + // rolf should no longer be there + $resultSet = $type->search('john'); + $this->assertEquals(1, $resultSet->count()); + } + + public function testDeleteDocument() + { + $index = $this->_createIndex(); + $type = new Type($index, 'user'); + + // Adds hans, john and rolf to the index + $docs = array( + new Document(1, array('username' => 'hans', 'test' => array('2', '3', '5'))), + new Document(2, array('username' => 'john', 'test' => array('1', '3', '6'))), + new Document(3, array('username' => 'rolf', 'test' => array('2', '3', '7'))), + ); + $type->addDocuments($docs); + $index->refresh(); + + $document = $type->getDocument(1); + $this->assertEquals(1, $document->getId()); + $this->assertEquals('hans', $document->get('username')); + + $this->assertEquals(3, $type->count()); + + $type->deleteDocument($document); + $index->refresh(); + + try { + $type->getDocument(1); + $this->fail('Document was not deleted'); + } catch (NotFoundException $e) { + $this->assertTrue(true); + $this->assertEquals(2, $type->count(), 'Documents count in type should be 2'); + } + } + + /** + * @expectedException \Elastica\Exception\NotFoundException + */ + public function testGetDocumentNotExist() + { + $index = $this->_createIndex(); + $type = new Type($index, 'test'); + $type->addDocument(new Document(1, array('name' => 'ruflin'))); + $index->refresh(); + + $type->getDocument(1); + + $type->getDocument(2); + } + + /** + * @expectedException \Elastica\Exception\NotFoundException + */ + public function testGetDocumentNotExistingIndex() + { + $client = new Client(); + $index = new Index($client, 'index'); + $type = new Type($index, 'type'); + + $type->getDocument(1); + } + + public function testDeleteByQueryWithQueryString() + { + $index = $this->_createIndex(); + $type = new Type($index, 'test'); + $type->addDocument(new Document(1, array('name' => 'ruflin nicolas'))); + $type->addDocument(new Document(2, array('name' => 'ruflin'))); + $index->refresh(); + + $response = $index->search('ruflin*'); + $this->assertEquals(2, $response->count()); + + $response = $index->search('nicolas'); + $this->assertEquals(1, $response->count()); + + // Delete first document + $response = $type->deleteByQuery('nicolas'); + $this->assertTrue($response->isOk()); + + $index->refresh(); + + // Makes sure, document is deleted + $response = $index->search('ruflin*'); + $this->assertEquals(1, $response->count()); + + $response = $index->search('nicolas'); + $this->assertEquals(0, $response->count()); + } + + public function testDeleteByQueryWithQuery() + { + $index = $this->_createIndex(); + $type = new Type($index, 'test'); + $type->addDocument(new Document(1, array('name' => 'ruflin nicolas'))); + $type->addDocument(new Document(2, array('name' => 'ruflin'))); + $index->refresh(); + + $response = $index->search('ruflin*'); + $this->assertEquals(2, $response->count()); + + $response = $index->search('nicolas'); + $this->assertEquals(1, $response->count()); + + // Delete first document + $response = $type->deleteByQuery(new SimpleQueryString('nicolas')); + $this->assertTrue($response->isOk()); + + $index->refresh(); + + // Makes sure, document is deleted + $response = $index->search('ruflin*'); + $this->assertEquals(1, $response->count()); + + $response = $index->search('nicolas'); + $this->assertEquals(0, $response->count()); + } + + public function testDeleteByQueryWithQueryAndOptions() + { + $index = $this->_createIndex('test', true, 2); + $type = new Type($index, 'test'); + $type->addDocument(new Document(1, array('name' => 'ruflin nicolas'))); + $type->addDocument(new Document(2, array('name' => 'ruflin'))); + $index->refresh(); + + $response = $index->search('ruflin*'); + $this->assertEquals(2, $response->count()); + + $response = $index->search('nicolas'); + $this->assertEquals(1, $response->count()); + + // Route to the wrong document id; should not delete + $response = $type->deleteByQuery(new SimpleQueryString('nicolas'), array('routing'=>'2')); + $this->assertTrue($response->isOk()); + + $index->refresh(); + + $response = $index->search('ruflin*'); + $this->assertEquals(2, $response->count()); + + $response = $index->search('nicolas'); + $this->assertEquals(1, $response->count()); + + // Delete first document + $response = $type->deleteByQuery(new SimpleQueryString('nicolas'), array('routing'=>'1')); + $this->assertTrue($response->isOk()); + + $index->refresh(); + + // Makes sure, document is deleted + $response = $index->search('ruflin*'); + $this->assertEquals(1, $response->count()); + + $response = $index->search('nicolas'); + $this->assertEquals(0, $response->count()); + } + + /** + * Test to see if Elastica_Type::getDocument() is properly using + * the fields array when available instead of _source + */ + public function testGetDocumentWithFieldsSelection() + { + $index = $this->_createIndex(); + $type = new Type($index, 'test'); + $type->addDocument(new Document(1, array('name' => 'loris', 'country' => 'FR', 'email' => 'test@test.com'))); + $index->refresh(); + + $document = $type->getDocument(1, array('fields' => 'name,email')); + $data = $document->getData(); + + $this->assertArrayHasKey('name', $data); + $this->assertArrayHasKey('email', $data); + $this->assertArrayNotHasKey('country', $data); + } + + /** + * Test to see if search Default Limit works + */ + public function testLimitDefaultType() + { + $client = $this->_getClient(); + $index = $client->getIndex('zero'); + $index->create(array('index' => array('number_of_shards' => 1, 'number_of_replicas' => 0)), true); + + $docs = array(); + $docs[] = new Document(1, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(2, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(3, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(4, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(5, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(6, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(7, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(8, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(9, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(10, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + $docs[] = new Document(11, array('id' => 1, 'email' => 'test@test.com', 'username' => 'farrelley')); + + $type = $index->getType('zeroType'); + $type->addDocuments($docs); + $index->refresh(); + + // default results (limit default is 10) + $resultSet = $type->search('farrelley'); + $this->assertEquals(10, $resultSet->count()); + + // limit = 1 + $resultSet = $type->search('farrelley', 1); + $this->assertEquals(1, $resultSet->count()); + } + + /** + * Test Delete of index type. After delete will check for type mapping. + */ + public function testDeleteType() + { + $index = $this->_createIndex(); + $type = new Type($index, 'test'); + $type->addDocument(new Document(1, array('name' => 'ruflin nicolas'))); + $type->addDocument(new Document(2, array('name' => 'ruflin'))); + $index->refresh(); + + $type->delete(); + $this->assertFalse($type->exists()); + } + + public function testMoreLikeThisApi() + { + $client = new Client(array('persistent' => false)); + $index = $client->getIndex('elastica_test'); + $index->create(array('index' => array('number_of_shards' => 1, 'number_of_replicas' => 0)), true); + + $type = new Type($index, 'mlt_test'); + $type->addDocument(new Document(1, array('visible' => true, 'name' => 'bruce wayne batman'))); + $type->addDocument(new Document(2, array('visible' => true, 'name' => 'bruce wayne'))); + $type->addDocument(new Document(3, array('visible' => false, 'name' => 'bruce wayne'))); + $type->addDocument(new Document(4, array('visible' => true, 'name' => 'batman'))); + $type->addDocument(new Document(5, array('visible' => false, 'name' => 'batman'))); + $type->addDocument(new Document(6, array('visible' => true, 'name' => 'superman'))); + $type->addDocument(new Document(7, array('visible' => true, 'name' => 'spiderman'))); + + $index->refresh(); + + $document = $type->getDocument(1); + + // Return all similar + $resultSet = $type->moreLikeThis($document, array('min_term_freq' => '1', 'min_doc_freq' => '1')); + $this->assertEquals(4, $resultSet->count()); + + // Return just the visible similar + $query = new Query(); + $filterTerm = new Term(); + $filterTerm->setTerm('visible', true); + $query->setFilter($filterTerm); + + $resultSet = $type->moreLikeThis($document, array('min_term_freq' => '1', 'min_doc_freq' => '1'), $query); + $this->assertEquals(2, $resultSet->count()); + } + + public function testUpdateDocument() + { + $client = $this->_getClient(); + $index = $client->getIndex('elastica_test'); + $type = $index->getType('update_type'); + $id = 1; + $type->addDocument(new Document($id, array('name' => 'bruce wayne batman', 'counter' => 1))); + $newName = 'batman'; + + $document = new Document(); + $script = new Script( + "ctx._source.name = name; ctx._source.counter += count", + array( + 'name' => $newName, + 'count' => 2, + ), + null, + $id + ); + $script->setUpsert($document); + + $type->updateDocument($script, array('refresh' => true)); + $updatedDoc = $type->getDocument($id)->getData(); + $this->assertEquals($newName, $updatedDoc['name'], "Name was not updated"); + $this->assertEquals(3, $updatedDoc['counter'], "Counter was not incremented"); + } + + public function testUpdateDocumentWithFieldsSource() + { + $client = $this->_getClient(); + $index = $client->getIndex('elastica_test'); + $type = $index->getType('update_type'); + + $client->setConfigValue('document', array('autoPopulate' => true)); + + $newDocument = new Document(null, array('counter' => 5, 'name' => 'Batman')); + + $this->assertFalse($newDocument->hasVersion()); + + $response = $type->addDocument($newDocument); + $responseData = $response->getData(); + + $this->assertTrue($newDocument->hasVersion()); + $this->assertArrayHasKey('_version', $responseData, '_version is missing in response data it is weird'); + $this->assertEquals(1, $responseData['_version']); + $this->assertEquals($responseData['_version'], $newDocument->getVersion()); + + $this->assertTrue($newDocument->hasId()); + + $script = new Script('ctx._source.counter += count; ctx._source.realName = realName'); + $script->setId($newDocument->getId()); + $script->setParam('count', 7); + $script->setParam('realName', 'Bruce Wayne'); + $script->setUpsert($newDocument); + + $newDocument->setFieldsSource(); + + $response = $type->updateDocument($script); + $responseData = $response->getData(); + + $data = $type->getDocument($newDocument->getId())->getData(); + + $this->assertEquals(12, $data['counter']); + $this->assertEquals('Batman', $data['name']); + $this->assertEquals('Bruce Wayne', $data['realName']); + + $this->assertTrue($newDocument->hasVersion()); + $this->assertArrayHasKey('_version', $responseData, '_version is missing in response data it is weird'); + $this->assertEquals(2, $responseData['_version']); + + $document = $type->getDocument($newDocument->getId()); + } + + /** + * @expectedException \Elastica\Exception\InvalidException + */ + public function testUpdateDocumentWithoutId() + { + $index = $this->_createIndex(); + $type = $index->getType('elastica_type'); + + $document = new Document(); + + $type->updateDocument($document); + } + + public function testUpdateDocumentWithoutSource() + { + $index = $this->_createIndex(); + $type = $index->getType('elastica_type'); + + $mapping = new Mapping(); + $mapping->setProperties(array( + 'name' => array( + 'type' => 'string', + 'store' => 'yes'), + 'counter' => array( + 'type' => 'integer', + 'store' => 'no' + ), + )); + $mapping->disableSource(); + $type->setMapping($mapping); + + $newDocument = new Document(); + $newDocument->setAutoPopulate(); + $newDocument->set('name', 'Batman'); + $newDocument->set('counter', 1); + + $type->addDocument($newDocument); + + $script = new Script('ctx._source.counter += count; ctx._source.name = name'); + $script->setId($newDocument->getId()); + $script->setParam('count', 2); + $script->setParam('name', 'robin'); + + $script->setUpsert($newDocument); + + try { + $type->updateDocument($script); + $this->fail('Update request should fail because source is disabled. Fields param is not set'); + } catch (ResponseException $e) { + $this->assertContains('DocumentSourceMissingException', $e->getMessage()); + } + + $newDocument->setFieldsSource(); + + try { + $type->updateDocument($newDocument); + $this->fail('Update request should fail because source is disabled. Fields param is set to _source'); + } catch (ResponseException $e) { + $this->assertContains('DocumentSourceMissingException', $e->getMessage()); + } + } + + public function testAddDocumentHashId() + { + $index = $this->_createIndex(); + $type = $index->getType('test2'); + + $hashId = '#1'; + + $doc = new Document($hashId, array('name' => 'ruflin')); + $type->addDocument($doc); + + $index->refresh(); + + $search = new Search($index->getClient()); + $search->addIndex($index); + $resultSet = $search->search(new MatchAll()); + $this->assertEquals($hashId, $resultSet->current()->getId()); + + $doc = $type->getDocument($hashId); + $this->assertEquals($hashId, $doc->getId()); + } + + public function testAddDocumentAutoGeneratedId() + { + $index = $this->_createIndex(); + $type = $index->getType('elastica_type'); + + $document = new Document(); + $document->setAutoPopulate(); + $document->set('name', 'ruflin'); + $this->assertEquals('', $document->getId()); + $this->assertFalse($document->hasId()); + + $type->addDocument($document); + + $this->assertNotEquals('', $document->getId()); + $this->assertTrue($document->hasId()); + + $foundDoc = $type->getDocument($document->getId()); + $this->assertInstanceOf('Elastica\Document', $foundDoc); + $this->assertEquals($document->getId(), $foundDoc->getId()); + $data = $foundDoc->getData(); + $this->assertArrayHasKey('name', $data); + $this->assertEquals('ruflin', $data['name']); + } + + /** + * @expectedException \Elastica\Exception\RuntimeException + */ + public function testAddDocumentWithoutSerializer() + { + $index = $this->_createIndex(); + + $type = new Type($index, 'user'); + + $type->addObject(new \stdClass()); + } + + public function testAddObject() + { + $index = $this->_createIndex(); + + $type = new Type($index, 'user'); + $type->setSerializer(array(new SerializerMock(), 'serialize')); + + $userObject = new \stdClass(); + $userObject->username = 'hans'; + $userObject->test = array('2', '3', '5'); + + $type->addObject($userObject); + + $index->refresh(); + + $resultSet = $type->search('hans'); + $this->assertEquals(1, $resultSet->count()); + + // Test if source is returned + $result = $resultSet->current(); + $data = $result->getData(); + $this->assertEquals('hans', $data['username']); + } + + public function testExists() + { + $index = $this->_createIndex(); + $this->assertTrue($index->exists()); + + $type = new Type($index, 'user'); + $this->assertFalse($type->exists()); + + $type->addDocument(new Document(1, array('name' => 'test name'))); + $index->optimize(); + + //Test if type exists + $this->assertTrue($type->exists()); + + $index->delete(); + $this->assertFalse($index->exists()); + } + + public function testGetMapping() { + $indexName = 'test'; + $typeName = 'test-type'; + + $index = $this->_createIndex($indexName); + $indexName = $index->getName(); + $type = new Type($index, $typeName); + $mapping = new Mapping($type, $expect = array( + 'id' => array('type' => 'integer', 'store' => true) + )); + $type->setMapping($mapping); + + $client = $index->getClient(); + + $this->assertEquals( + array('test-type' => array('properties' => $expect)), + $client->getIndex($indexName)->getType($typeName)->getMapping() + ); + } + + public function testGetMappingAlias() { + $indexName = 'test'; + $aliasName = 'test-alias'; + $typeName = 'test-alias-type'; + + $index = $this->_createIndex($indexName); + $index->addAlias($aliasName); + $type = new Type($index, $typeName); + $mapping = new Mapping($type, $expect = array( + 'id' => array('type' => 'integer', 'store' => true) + )); + $type->setMapping($mapping); + + $client = $index->getClient(); + + $this->assertEquals( + array('test-alias-type' => array('properties' => $expect)), + $client->getIndex($aliasName)->getType($typeName)->getMapping() + ); + } +} + +class SerializerMock +{ + public function serialize($object) + { + return get_object_vars($object); + } +} diff --git a/vendor/ruflin/elastica/test/lib/Elastica/Test/UtilTest.php b/vendor/ruflin/elastica/test/lib/Elastica/Test/UtilTest.php new file mode 100644 index 00000000..09d4b5b1 --- /dev/null +++ b/vendor/ruflin/elastica/test/lib/Elastica/Test/UtilTest.php @@ -0,0 +1,77 @@ +<?php + +namespace Elastica\Test; + +use Elastica\Util; +use Elastica\Request; +use Elastica\Connection; +use Elastica\Test\Base as BaseTest; + +class UtilTest extends BaseTest +{ + /** + * @dataProvider getEscapeTermPairs + */ + public function testEscapeTerm($unescaped, $escaped) + { + $this->assertEquals($escaped, Util::escapeTerm($unescaped)); + } + + public function getEscapeTermPairs() + { + return array( + array('', ''), + array('pragmatic banana', 'pragmatic banana'), + array('oh yeah!', 'oh yeah\\!'), + // Seperate test below because phpunit seems to have some problems + //array('\\+-&&||!(){}[]^"~*?:', '\\\\\\+\\-\\&&\\||\\!\\(\\)\\{\\}\\[\\]\\^\\"\\~\\*\\?\\:'), + array('some signs, can stay.', 'some signs, can stay.') + ); + } + + public function testEscapeTermSpecialCharacters() + { + $before = '\\+-&&||!(){}[]^"~*?:/'; + $after = '\\\\\\+\\-\\&&\\||\\!\\(\\)\\{\\}\\[\\]\\^\\"\\~\\*\\?\\:\\\\/'; + + $this->assertEquals(Util::escapeTerm($before), $after); + } + + public function testToCamelCase() + { + $string = 'hello_world'; + $this->assertEquals('HelloWorld', Util::toCamelCase($string)); + + $string = 'how_are_you_today'; + $this->assertEquals('HowAreYouToday', Util::toCamelCase($string)); + } + + public function testToSnakeCase() + { + $string = 'HelloWorld'; + $this->assertEquals('hello_world', Util::toSnakeCase($string)); + + $string = 'HowAreYouToday'; + $this->assertEquals('how_are_you_today', Util::toSnakeCase($string)); + } + + public function testConvertRequestToCurlCommand() + { + $path = 'test'; + $method = Request::POST; + $query = array('no' => 'params'); + $data = array('key' => 'value'); + + $connection = new Connection(); + $connection->setHost('localhost'); + $connection->setPort('9200'); + + $request = new Request($path, $method, $data, $query, $connection); + + $curlCommand = Util::convertRequestToCurlCommand($request); + + $expected = 'curl -XPOST \'http://localhost:9200/test?no=params\' -d \'{"key":"value"}\''; + $this->assertEquals($expected, $curlCommand); + + } +} |