1<?php 2 3class Search_Elastic_MoreLikeThisTest extends PHPUnit_Framework_TestCase 4{ 5 private $index; 6 private $indexer; 7 8 function setUp() 9 { 10 $elasticSearchHost = empty(getenv('ELASTICSEARCH_HOST')) ? 'localhost' : getenv('ELASTICSEARCH_HOST'); 11 $connection = new Search_Elastic_Connection('http://' . $elasticSearchHost . ':9200'); 12 $connection->startBulk(); 13 14 $status = $connection->getStatus(); 15 if (! $status->ok) { 16 $this->markTestSkipped('Elasticsearch needs to be available on ' . $elasticSearchHost . ':9200 for the test to run.'); 17 } 18 19 $this->index = new Search_Elastic_Index($connection, 'test_index'); 20 $this->index->destroy(); 21 22 $this->populate($this->index); 23 } 24 25 function tearDown() 26 { 27 if ($this->index) { 28 $this->index->destroy(); 29 } 30 } 31 32 function populate($index) 33 { 34 $data = [ 35 'X' => [ 36 'wiki_content' => 'this does not work', 37 ], 38 ]; 39 40 $words = ['hello', 'world', 'some', 'random', 'content', 'populated', 'through', 'automatic', 'sampling']; 41 42 // Generate 50 documents with random words (in a stable way) 43 foreach (range(1, 50) as $doc) { 44 $parts = []; 45 foreach ($words as $key => $word) { 46 if ($doc % ($key + 2) === 0) { 47 $parts[] = $word; 48 $parts[] = $word; 49 $parts[] = $word; 50 } 51 } 52 53 $data[$doc] = [ 54 'object_type' => 'wiki page', 55 'object_id' => $doc, 56 'wiki_content' => implode(' ', $parts), 57 ]; 58 } 59 60 $source = new Search_ContentSource_Static( 61 $data, 62 [ 63 'object_type' => 'identifier', 64 'object_id' => 'identifier', 65 'wiki_content' => 'plaintext', 66 ] 67 ); 68 69 $this->indexer = new Search_Indexer($index); 70 $this->indexer->addContentSource('wiki page', $source); 71 72 $this->indexer->rebuild(); 73 } 74 75 function testObtainSimilarDocument() 76 { 77 $query = new Search_Query; 78 $query->filterSimilar('wiki page', 12); 79 80 $results = $query->search($this->index); 81 82 $this->assertGreaterThan(0, count($results)); 83 } 84 85 function testDocumentTooDifferent() 86 { 87 $query = new Search_Query; 88 $query->filterSimilar('wiki page', 'X'); 89 90 $results = $query->search($this->index); 91 92 $this->assertCount(0, $results); 93 } 94} 95