SS 4.0 - Upgrade tests to SilverStripe 4.0 & Replace Phockito

This commit is contained in:
Brett Tasker 2017-04-26 22:52:20 +12:00
parent 168b6745b4
commit 73e4888715
30 changed files with 577 additions and 460 deletions

View File

@ -24,8 +24,7 @@
"monolog/monolog": "~1.15" "monolog/monolog": "~1.15"
}, },
"require-dev": { "require-dev": {
"silverstripe/cms": "4.0.x-dev", "silverstripe/cms": "4.0.x-dev"
"hafriedlander/silverstripe-phockito": "*"
}, },
"extra": { "extra": {
"branch-alias": { "branch-alias": {

View File

@ -4,6 +4,19 @@ namespace SilverStripe\FullTextSearch\Tests;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\FullTextSearch\Search\FullTextSearch; use SilverStripe\FullTextSearch\Search\FullTextSearch;
use SilverStripe\ORM\FieldType\DBDatetime;
use SilverStripe\Core\Config\Config;
use SilverStripe\Versioned\Versioned;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\FullTextSearch\Tests\BatchedProcessorTest\BatchedProcessor_QueuedJobService;
use SilverStripe\FullTextSearch\Tests\BatchedProcessorTest\BatchedProcessorTest_Index;
use SilverStripe\FullTextSearch\Tests\BatchedProcessorTest\BatchedProcessorTest_Object;
use SilverStripe\FullTextSearch\Search\Processors\SearchUpdateCommitJobProcessor;
use SilverStripe\FullTextSearch\Search\Processors\SearchUpdateQueuedJobProcessor;
use SilverStripe\FullTextSearch\Search\Processors\SearchUpdateBatchedProcessor;
use SilverStripe\FullTextSearch\Search\Updaters\SearchUpdater;
use SilverStripe\FullTextSearch\Search\Variants\SearchVariantVersioned;
use SilverStripe\QueuedJobs\Services\QueuedJobService;
/** /**
* Tests {@see SearchUpdateQueuedJobProcessor} * Tests {@see SearchUpdateQueuedJobProcessor}
@ -12,8 +25,8 @@ class BatchedProcessorTest extends SapphireTest
{ {
protected $oldProcessor; protected $oldProcessor;
protected $extraDataObjects = array( protected static $extra_dataobjects = array(
'BatchedProcessorTest_Object' BatchedProcessorTest_Object::class
); );
protected $illegalExtensions = array( protected $illegalExtensions = array(
@ -26,7 +39,7 @@ class BatchedProcessorTest extends SapphireTest
public function setUpOnce() public function setUpOnce()
{ {
// Disable illegal extensions if skipping this test // Disable illegal extensions if skipping this test
if (class_exists('Subsite') || !interface_exists('QueuedJob')) { if (class_exists('Subsite') || !interface_exists('SilverStripe\QueuedJobs\Services\QueuedJob')) {
$this->illegalExtensions = array(); $this->illegalExtensions = array();
} }
parent::setUpOnce(); parent::setUpOnce();
@ -36,7 +49,7 @@ class BatchedProcessorTest extends SapphireTest
{ {
parent::setUp(); parent::setUp();
if (!interface_exists('QueuedJob')) { if (!interface_exists('SilverStripe\QueuedJobs\Services\QueuedJob')) {
$this->skipTest = true; $this->skipTest = true;
$this->markTestSkipped("These tests need the QueuedJobs module installed to run"); $this->markTestSkipped("These tests need the QueuedJobs module installed to run");
} }
@ -46,17 +59,17 @@ class BatchedProcessorTest extends SapphireTest
$this->markTestSkipped(get_class() . ' skipped when running with subsites'); $this->markTestSkipped(get_class() . ' skipped when running with subsites');
} }
SS_Datetime::set_mock_now('2015-05-07 06:00:00'); DBDatetime::set_mock_now('2015-05-07 06:00:00');
Config::modify()->set('SearchUpdateBatchedProcessor', 'batch_size', 5); Config::modify()->set(SearchUpdateBatchedProcessor::class, 'batch_size', 5);
Config::modify()->set('SearchUpdateBatchedProcessor', 'batch_soft_cap', 0); Config::modify()->set(SearchUpdateBatchedProcessor::class, 'batch_soft_cap', 0);
Config::modify()->set('SearchUpdateCommitJobProcessor', 'cooldown', 600); Config::modify()->set(SearchUpdateCommitJobProcessor::class, 'cooldown', 600);
Versioned::reading_stage("Stage"); Versioned::set_stage("Stage");
Injector::inst()->registerService(new BatchedProcessor_QueuedJobService(), 'QueuedJobService'); Injector::inst()->registerService(new BatchedProcessor_QueuedJobService(), QueuedJobService::class);
FullTextSearch::force_index_list('BatchedProcessorTest_Index'); FullTextSearch::force_index_list(BatchedProcessorTest_Index::class);
SearchUpdateCommitJobProcessor::$dirty_indexes = array(); SearchUpdateCommitJobProcessor::$dirty_indexes = array();
SearchUpdateCommitJobProcessor::$has_run = false; SearchUpdateCommitJobProcessor::$has_run = false;
@ -87,12 +100,12 @@ class BatchedProcessorTest extends SapphireTest
$object->write(); $object->write();
// Add to index manually // Add to index manually
$processor->addDirtyIDs( $processor->addDirtyIDs(
'BatchedProcessorTest_Object', BatchedProcessorTest_Object::class,
array(array( array(array(
'id' => $id, 'id' => $id,
'state' => array('SearchVariantVersioned' => 'Stage') 'state' => array(SearchVariantVersioned::class => 'Stage')
)), )),
'BatchedProcessorTest_Index' BatchedProcessorTest_Index::class
); );
} }
$processor->batchData(); $processor->batchData();
@ -104,7 +117,7 @@ class BatchedProcessorTest extends SapphireTest
*/ */
public function testBatching() public function testBatching()
{ {
$index = singleton('BatchedProcessorTest_Index'); $index = singleton(BatchedProcessorTest_Index::class);
$index->reset(); $index->reset();
$processor = $this->generateDirtyIds(); $processor = $this->generateDirtyIds();
@ -132,10 +145,10 @@ class BatchedProcessorTest extends SapphireTest
// Check any additional queued jobs // Check any additional queued jobs
$processor->afterComplete(); $processor->afterComplete();
$service = singleton('QueuedJobService'); $service = singleton(QueuedJobService::class);
$jobs = $service->getJobs(); $jobs = $service->getJobs();
$this->assertEquals(1, count($jobs)); $this->assertEquals(1, count($jobs));
$this->assertInstanceOf('SearchUpdateCommitJobProcessor', $jobs[0]['job']); $this->assertInstanceOf(SearchUpdateCommitJobProcessor::class, $jobs[0]['job']);
} }
/** /**
@ -143,7 +156,7 @@ class BatchedProcessorTest extends SapphireTest
*/ */
public function testMultipleCommits() public function testMultipleCommits()
{ {
$index = singleton('BatchedProcessorTest_Index'); $index = singleton(BatchedProcessorTest_Index::class);
$index->reset(); $index->reset();
// Test that running a commit immediately after submitting to the indexes // Test that running a commit immediately after submitting to the indexes
@ -190,25 +203,25 @@ class BatchedProcessorTest extends SapphireTest
*/ */
public function testSoftCap() public function testSoftCap()
{ {
$index = singleton('BatchedProcessorTest_Index'); $index = singleton(BatchedProcessorTest_Index::class);
$index->reset(); $index->reset();
$processor = $this->generateDirtyIds(); $processor = $this->generateDirtyIds();
// Test that increasing the soft cap to 2 will reduce the number of batches // Test that increasing the soft cap to 2 will reduce the number of batches
Config::modify()->set('SearchUpdateBatchedProcessor', 'batch_soft_cap', 2); Config::modify()->set(SearchUpdateBatchedProcessor::class, 'batch_soft_cap', 2);
$processor->batchData(); $processor->batchData();
$data = $processor->getJobData(); $data = $processor->getJobData();
//Debug::dump($data);die; //Debug::dump($data);die;
$this->assertEquals(8, $data->totalSteps); $this->assertEquals(8, $data->totalSteps);
// A soft cap of 1 should not fit in the hanging two items // A soft cap of 1 should not fit in the hanging two items
Config::modify()->set('SearchUpdateBatchedProcessor', 'batch_soft_cap', 1); Config::modify()->set(SearchUpdateBatchedProcessor::class, 'batch_soft_cap', 1);
$processor->batchData(); $processor->batchData();
$data = $processor->getJobData(); $data = $processor->getJobData();
$this->assertEquals(9, $data->totalSteps); $this->assertEquals(9, $data->totalSteps);
// Extra large soft cap should fit both items // Extra large soft cap should fit both items
Config::modify()->set('SearchUpdateBatchedProcessor', 'batch_soft_cap', 4); Config::modify()->set(SearchUpdateBatchedProcessor::class, 'batch_soft_cap', 4);
$processor->batchData(); $processor->batchData();
$data = $processor->getJobData(); $data = $processor->getJobData();
$this->assertEquals(8, $data->totalSteps); $this->assertEquals(8, $data->totalSteps);

View File

@ -9,7 +9,7 @@ class BatchedProcessorTest_Index extends SearchIndex_Recording implements TestOn
{ {
public function init() public function init()
{ {
$this->addClass('BatchedProcessorTest_Object'); $this->addClass(BatchedProcessorTest_Object::class);
$this->addFilterField('TestText'); $this->addFilterField('TestText');
} }
} }

View File

@ -7,6 +7,8 @@ use SilverStripe\Dev\TestOnly;
class BatchedProcessorTest_Object extends SiteTree implements TestOnly class BatchedProcessorTest_Object extends SiteTree implements TestOnly
{ {
private static $table_name = 'BatchedProcessorTest_Object';
private static $db = array( private static $db = array(
'TestText' => 'Varchar' 'TestText' => 'Varchar'
); );

View File

@ -2,6 +2,8 @@
namespace SilverStripe\FullTextSearch\Tests\BatchedProcessorTest; namespace SilverStripe\FullTextSearch\Tests\BatchedProcessorTest;
use SilverStripe\QueuedJobs\Services\QueuedJob;
class BatchedProcessor_QueuedJobService class BatchedProcessor_QueuedJobService
{ {
protected $jobs = array(); protected $jobs = array();

View File

@ -3,11 +3,14 @@
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\FullTextSearch\Search\Updaters\SearchUpdater; use SilverStripe\FullTextSearch\Search\Updaters\SearchUpdater;
use SilverStripe\Core\Config\Config; use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\FullTextSearch\Search\FullTextSearch; use SilverStripe\FullTextSearch\Search\FullTextSearch;
use SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_Container; use SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_Container;
use SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_HasOne; use SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_HasOne;
use SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_HasMany; use SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_HasMany;
use SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_Index; use SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_Index;
use SilverStripe\FullTextSearch\Search\Processors\SearchUpdateProcessor;
use SilverStripe\FullTextSearch\Search\Processors\SearchUpdateImmediateProcessor;
class SearchUpdaterTest extends SapphireTest class SearchUpdaterTest extends SapphireTest
{ {
@ -27,8 +30,8 @@ class SearchUpdaterTest extends SapphireTest
SearchUpdater::bind_manipulation_capture(); SearchUpdater::bind_manipulation_capture();
Config::modify()->set('Injector', 'SearchUpdateProcessor', array( Config::modify()->set(Injector::class, SearchUpdateProcessor::class, array(
'class' => 'SearchUpdateImmediateProcessor' 'class' => SearchUpdateImmediateProcessor::class
)); ));
FullTextSearch::force_index_list(self::$index); FullTextSearch::force_index_list(self::$index);

View File

@ -8,7 +8,7 @@ class SearchUpdaterTest_Index extends SearchIndex_Recording
{ {
public function init() public function init()
{ {
$this->addClass('SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_Container'); $this->addClass(SearchUpdaterTest_Container::class);
$this->addFilterField('Field1'); $this->addFilterField('Field1');
$this->addFilterField('HasOneObject.Field1'); $this->addFilterField('HasOneObject.Field1');

View File

@ -3,23 +3,10 @@
use SilverStripe\CMS\Model\SiteTree; use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\FullTextSearch\Search\Indexes\SearchIndex_Recording; use SilverStripe\FullTextSearch\Search\Indexes\SearchIndex_Recording;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\FullTextSearch\Tests\SearchVariantSiteTreeSubsitesPolyhomeTest\SearchVariantSiteTreeSubsitesPolyhomeTest_Index;
use SilverStripe\FullTextSearch\Tests\SearchVariantSiteTreeSubsitesPolyhomeTest\SearchVariantSiteTreeSubsitesPolyhomeTest_Item;
class SearchVariantSiteTreeSubsitesPolyhomeTest_Item extends SiteTree
{
// TODO: Currently theres a failure if you addClass a non-table class
private static $db = array(
'TestText' => 'Varchar'
);
}
class SearchVariantSiteTreeSubsitesPolyhomeTest_Index extends SearchIndex_Recording
{
public function init()
{
$this->addClass('SearchVariantSiteTreeSubsitesPolyhomeTest_Item');
$this->addFilterField('TestText');
}
}
class SearchVariantSiteTreeSubsitesPolyhomeTest extends SapphireTest class SearchVariantSiteTreeSubsitesPolyhomeTest extends SapphireTest
{ {

View File

@ -0,0 +1,14 @@
<?php
namespace SilverStripe\FullTextSearch\Tests\SearchVariantSiteTreeSubsitesPolyhomeTest;
use SilverStripe\FullTextSearch\Search\Indexes\SearchIndex_Recording;
class SearchVariantSiteTreeSubsitesPolyhomeTest_Index extends SearchIndex_Recording
{
public function init()
{
$this->addClass(SearchVariantSiteTreeSubsitesPolyhomeTest_Item::class);
$this->addFilterField('TestText');
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace SilverStripe\FullTextSearch\Tests\SearchVariantSiteTreeSubsitesPolyhomeTest;
use SilverStripe\CMS\Model\SiteTree;
class SearchVariantSiteTreeSubsitesPolyhomeTest_Item extends SiteTree
{
private static $table_name = 'SearchVariantSiteTreeSubsitesPolyhomeTest_Item';
// TODO: Currently theres a failure if you addClass a non-table class
private static $db = array(
'TestText' => 'Varchar'
);
}

View File

@ -1,9 +1,15 @@
<?php <?php
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\CMS\Model\SiteTree; use SilverStripe\Core\Config\Config;
use SilverStripe\Dev\TestOnly; use SilverStripe\FullTextSearch\Search\FullTextSearch;
use SilverStripe\FullTextSearch\Search\Indexes\SearchIndex_Recording; use SilverStripe\FullTextSearch\Search\Indexes\SearchIndex_Recording;
use SilverStripe\FullTextSearch\Tests\SearchVariantVersionedTest\SearchVariantVersionedTest_Index;
use SilverStripe\FullTextSearch\Tests\SearchVariantVersionedTest\SearchVariantVersionedTest_Item;
use SilverStripe\FullTextSearch\Tests\SearchVariantVersionedTest\SearchVariantVersionedTest_IndexNoStage;
use SilverStripe\FullTextSearch\Search\Processors\SearchUpdateProcessor;
use SilverStripe\FullTextSearch\Search\Processors\SearchUpdateImmediateProcessor;
use SilverStripe\FullTextSearch\Search\Updaters\SearchUpdater;
class SearchVariantVersionedTest extends SapphireTest class SearchVariantVersionedTest extends SapphireTest
{ {
@ -12,27 +18,22 @@ class SearchVariantVersionedTest extends SapphireTest
*/ */
private static $index = null; private static $index = null;
protected $extraDataObjects = array( protected static $extra_dataobjects = array(
'SearchVariantVersionedTest_Item' SearchVariantVersionedTest_Item::class
); );
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
// Check versioned available
if (!class_exists('Versioned')) {
return $this->markTestSkipped('The versioned decorator is not installed');
}
if (self::$index === null) { if (self::$index === null) {
self::$index = singleton('SearchVariantVersionedTest_Index'); self::$index = singleton(SearchVariantVersionedTest_Index::class);
} }
SearchUpdater::bind_manipulation_capture(); SearchUpdater::bind_manipulation_capture();
Config::modify()->set('Injector', 'SearchUpdateProcessor', array( Config::modify()->set('Injector', SearchUpdateProcessor::class, array(
'class' => 'SearchUpdateImmediateProcessor' 'class' => SearchUpdateImmediateProcessor::class
)); ));
FullTextSearch::force_index_list(self::$index); FullTextSearch::force_index_list(self::$index);
@ -47,20 +48,21 @@ class SearchVariantVersionedTest extends SapphireTest
$item->write(); $item->write();
SearchUpdater::flush_dirty_indexes(); SearchUpdater::flush_dirty_indexes();
$this->assertEquals(self::$index->getAdded(array('ID', '_versionedstage')), array( $this->assertEquals(array(
array('ID' => $item->ID, '_versionedstage' => 'Stage') array('ID' => $item->ID, '_versionedstage' => 'Stage')
)); ), self::$index->getAdded(array('ID', '_versionedstage')));
// Check that publish updates Live // Check that publish updates Live
self::$index->reset(); self::$index->reset();
$item->publish("Stage", "Live"); $item->copyVersionToStage('Stage', 'Live');
SearchUpdater::flush_dirty_indexes(); SearchUpdater::flush_dirty_indexes();
$this->assertEquals(self::$index->getAdded(array('ID', '_versionedstage')), array( $this->assertEquals(array(
array('ID' => $item->ID, '_versionedstage' => 'Stage'),
array('ID' => $item->ID, '_versionedstage' => 'Live') array('ID' => $item->ID, '_versionedstage' => 'Live')
)); ), self::$index->getAdded(array('ID', '_versionedstage')));
// Just update a SiteTree field, and check it updates Stage // Just update a SiteTree field, and check it updates Stage
@ -81,48 +83,23 @@ class SearchVariantVersionedTest extends SapphireTest
public function testExcludeVariantState() public function testExcludeVariantState()
{ {
$index = singleton('SearchVariantVersionedTest_IndexNoStage'); $index = singleton(SearchVariantVersionedTest_IndexNoStage::class);
FullTextSearch::force_index_list($index); FullTextSearch::force_index_list($index);
// Check that write doesn't update stage // Check that write doesn't update stage
$item = new SearchVariantVersionedTest_Item(array('TestText' => 'Foo')); $item = new SearchVariantVersionedTest_Item(array('TestText' => 'Foo'));
$item->write(); $item->write();
SearchUpdater::flush_dirty_indexes(); SearchUpdater::flush_dirty_indexes();
$this->assertEquals($index->getAdded(array('ID', '_versionedstage')), array()); $this->assertEquals(array(), $index->getAdded(array('ID', '_versionedstage')));
// Check that publish updates Live // Check that publish updates Live
$index->reset(); $index->reset();
$item->publish("Stage", "Live");
$item->copyVersionToStage('Stage', 'Live');
SearchUpdater::flush_dirty_indexes(); SearchUpdater::flush_dirty_indexes();
$this->assertEquals($index->getAdded(array('ID', '_versionedstage')), array( $this->assertEquals(array(
array('ID' => $item->ID, '_versionedstage' => 'Live') array('ID' => $item->ID, '_versionedstage' => 'Live')
)); ), $index->getAdded(array('ID', '_versionedstage')));
}
}
class SearchVariantVersionedTest_Item extends SiteTree implements TestOnly
{
// TODO: Currently theres a failure if you addClass a non-table class
private static $db = array(
'TestText' => 'Varchar'
);
}
class SearchVariantVersionedTest_Index extends SearchIndex_Recording
{
public function init()
{
$this->addClass('SearchVariantVersionedTest_Item');
$this->addFilterField('TestText');
}
}
class SearchVariantVersionedTest_IndexNoStage extends SearchIndex_Recording
{
public function init()
{
$this->addClass('SearchVariantVersionedTest_Item');
$this->addFilterField('TestText');
$this->excludeVariantState(array('SearchVariantVersioned' => 'Stage'));
} }
} }

View File

@ -0,0 +1,14 @@
<?php
namespace SilverStripe\FullTextSearch\Tests\SearchVariantVersionedTest;
use SilverStripe\FullTextSearch\Search\Indexes\SearchIndex_Recording;
class SearchVariantVersionedTest_Index extends SearchIndex_Recording
{
public function init()
{
$this->addClass(SearchVariantVersionedTest_Item::class);
$this->addFilterField('TestText');
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace SilverStripe\FullTextSearch\Tests\SearchVariantVersionedTest;
use SilverStripe\FullTextSearch\Search\Indexes\SearchIndex_Recording;
use SilverStripe\FullTextSearch\Search\Variants\SearchVariantVersioned;
class SearchVariantVersionedTest_IndexNoStage extends SearchIndex_Recording
{
public function init()
{
$this->addClass(SearchVariantVersionedTest_Item::class);
$this->addFilterField('TestText');
$this->excludeVariantState(array(SearchVariantVersioned::class => 'Stage'));
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace SilverStripe\FullTextSearch\Tests\SearchVariantVersionedTest;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Dev\TestOnly;
class SearchVariantVersionedTest_Item extends SiteTree implements TestOnly
{
private static $table_name = 'SearchVariantVersionedTest_Item';
// TODO: Currently theres a failure if you addClass a non-table class
private static $db = array(
'TestText' => 'Varchar'
);
}

View File

@ -3,8 +3,8 @@
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\FullTextSearch\Tests\SolrIndexSubsitesTest\SolrIndexSubsitesTest_Index; use SilverStripe\FullTextSearch\Tests\SolrIndexSubsitesTest\SolrIndexSubsitesTest_Index;
if (class_exists('Phockito')) { if (class_exists('\Phockito')) {
Phockito::include_hamcrest(false); \Phockito::include_hamcrest(false);
} }
/** /**
@ -33,9 +33,9 @@ class SolrIndexSubsitesTest extends SapphireTest {
$this->server = $_SERVER; $this->server = $_SERVER;
if (!class_exists('Phockito')) { if (!class_exists('\Phockito')) {
$this->skipTest = true; $this->skipTest = true;
$this->markTestSkipped("These tests need the Phockito module installed to run"); $this->markTestSkipped("These tests need the \Phockito module installed to run");
return; return;
} }
@ -71,7 +71,7 @@ class SolrIndexSubsitesTest extends SapphireTest {
protected function getServiceMock() protected function getServiceMock()
{ {
return Phockito::mock('Solr4Service'); return \Phockito::mock('Solr4Service');
} }
/** /**
@ -83,7 +83,7 @@ class SolrIndexSubsitesTest extends SapphireTest {
protected function getExpectedDocumentId($object, $subsiteID, $stage = null) protected function getExpectedDocumentId($object, $subsiteID, $stage = null)
{ {
$id = $object->ID; $id = $object->ID;
$class = ClassInfo::baseDataClass($object); $class = DataObject::getSchema()->baseDataClass($object);
$variants = array(); $variants = array();
// Check subsite // Check subsite
@ -109,7 +109,7 @@ class SolrIndexSubsitesTest extends SapphireTest {
// Add records to first subsite // Add records to first subsite
Versioned::reading_stage('Stage'); Versioned::reading_stage('Stage');
$_SERVER['HTTP_HOST'] = 'www.subsite1.com'; $_SERVER['HTTP_HOST'] = 'www.subsite1.com';
Phockito::reset($serviceMock); \Phockito::reset($serviceMock);
$file = new File(); $file = new File();
$file->Title = 'My File'; $file->Title = 'My File';
$file->SubsiteID = $subsite1->ID; $file->SubsiteID = $subsite1->ID;
@ -132,8 +132,8 @@ class SolrIndexSubsitesTest extends SapphireTest {
'File_Title' => 'My File', 'File_Title' => 'My File',
'_subsite' => $subsite1->ID '_subsite' => $subsite1->ID
)); ));
Phockito::verify($serviceMock)->addDocument($doc1); \Phockito::verify($serviceMock)->addDocument($doc1);
Phockito::verify($serviceMock)->addDocument($doc2); \Phockito::verify($serviceMock)->addDocument($doc2);
} }

View File

@ -3,13 +3,15 @@
namespace SilverStripe\FullTextSearch\Tests\SolrIndexSubsitesTest; namespace SilverStripe\FullTextSearch\Tests\SolrIndexSubsitesTest;
use SilverStripe\FullTextSearch\Solr\SolrIndex; use SilverStripe\FullTextSearch\Solr\SolrIndex;
use SilverStripe\Assets\File;
use SilverStripe\CMS\Model\SiteTree;
class SolrIndexSubsitesTest_Index extends SolrIndex class SolrIndexSubsitesTest_Index extends SolrIndex
{ {
public function init() public function init()
{ {
$this->addClass('File'); $this->addClass(File::class);
$this->addClass('SiteTree'); $this->addClass(SiteTree::class);
$this->addAllFulltextFields(); $this->addAllFulltextFields();
} }
} }

View File

@ -4,60 +4,50 @@ use SilverStripe\Dev\SapphireTest;
use SilverStripe\FullTextSearch\Tests\SolrIndexTest\SolrIndexTest_FakeIndex; use SilverStripe\FullTextSearch\Tests\SolrIndexTest\SolrIndexTest_FakeIndex;
use SilverStripe\FullTextSearch\Tests\SolrIndexTest\SolrIndexTest_FakeIndex2; use SilverStripe\FullTextSearch\Tests\SolrIndexTest\SolrIndexTest_FakeIndex2;
use SilverStripe\FullTextSearch\Tests\SolrIndexTest\SolrIndexTest_BoostedIndex; use SilverStripe\FullTextSearch\Tests\SolrIndexTest\SolrIndexTest_BoostedIndex;
use SilverStripe\FullTextSearch\Solr\Services\Solr3Service;
use SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_Container;
use SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_HasOne;
use SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_HasMany;
use SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_ManyMany;
use SilverStripe\Core\Config\Config;
use SilverStripe\Control\Director;
use SilverStripe\FullTextSearch\Search\Queries\SearchQuery;
class SolrIndexTest extends SapphireTest class SolrIndexTest extends SapphireTest
{ {
public function setUpOnce()
{
parent::setUpOnce();
if (class_exists('Phockito')) {
Phockito::include_hamcrest(false);
}
}
public function setUp()
{
parent::setUp();
if (!class_exists('Phockito')) {
$this->markTestSkipped("These tests need the Phockito module installed to run");
$this->skipTest = true;
}
}
public function testFieldDataHasOne() public function testFieldDataHasOne()
{ {
$index = new SolrIndexTest_FakeIndex(); $index = new SolrIndexTest_FakeIndex();
$data = $index->fieldData('HasOneObject.Field1'); $data = $index->fieldData('HasOneObject.Field1');
$data = $data['SearchUpdaterTest_Container_HasOneObject_Field1'];
$this->assertEquals('SearchUpdaterTest_Container', $data['origin']); $data = $data[SearchUpdaterTest_Container::class . '_HasOneObject_Field1'];
$this->assertEquals('SearchUpdaterTest_Container', $data['base']);
$this->assertEquals('SearchUpdaterTest_HasOne', $data['class']); $this->assertEquals(SearchUpdaterTest_Container::class, $data['origin']);
$this->assertEquals(SearchUpdaterTest_Container::class, $data['base']);
$this->assertEquals(SearchUpdaterTest_HasOne::class, $data['class']);
} }
public function testFieldDataHasMany() public function testFieldDataHasMany()
{ {
$index = new SolrIndexTest_FakeIndex(); $index = new SolrIndexTest_FakeIndex();
$data = $index->fieldData('HasManyObjects.Field1'); $data = $index->fieldData('HasManyObjects.Field1');
$data = $data['SearchUpdaterTest_Container_HasManyObjects_Field1']; $data = $data[SearchUpdaterTest_Container::class . '_HasManyObjects_Field1'];
$this->assertEquals('SearchUpdaterTest_Container', $data['origin']); $this->assertEquals(SearchUpdaterTest_Container::class, $data['origin']);
$this->assertEquals('SearchUpdaterTest_Container', $data['base']); $this->assertEquals(SearchUpdaterTest_Container::class, $data['base']);
$this->assertEquals('SearchUpdaterTest_HasMany', $data['class']); $this->assertEquals(SearchUpdaterTest_HasMany::class, $data['class']);
} }
public function testFieldDataManyMany() public function testFieldDataManyMany()
{ {
$index = new SolrIndexTest_FakeIndex(); $index = new SolrIndexTest_FakeIndex();
$data = $index->fieldData('ManyManyObjects.Field1'); $data = $index->fieldData('ManyManyObjects.Field1');
$data = $data['SearchUpdaterTest_Container_ManyManyObjects_Field1']; $data = $data[SearchUpdaterTest_Container::class . '_ManyManyObjects_Field1'];
$this->assertEquals('SearchUpdaterTest_Container', $data['origin']); $this->assertEquals(SearchUpdaterTest_Container::class, $data['origin']);
$this->assertEquals('SearchUpdaterTest_Container', $data['base']); $this->assertEquals(SearchUpdaterTest_Container::class, $data['base']);
$this->assertEquals('SearchUpdaterTest_ManyMany', $data['class']); $this->assertEquals(SearchUpdaterTest_ManyMany::class, $data['class']);
} }
/** /**
@ -65,15 +55,19 @@ class SolrIndexTest extends SapphireTest
*/ */
public function testBoostedQuery() public function testBoostedQuery()
{ {
$serviceMock = $this->getServiceMock(); /** @var Solr3Service|PHPUnit_Framework_MockObject_MockObject $serviceMock */
Phockito::when($serviceMock) $serviceMock = $this->getMockBuilder(Solr3Service::class)
->search( ->setMethods(['search'])
\Hamcrest_Matchers::anything(), ->getMock();
\Hamcrest_Matchers::anything(),
\Hamcrest_Matchers::anything(), $serviceMock->expects($this->once())
\Hamcrest_Matchers::anything(), ->method('search')
\Hamcrest_Matchers::anything() ->with($this->equalTo('+(Field1:term^1.5 OR HasOneObject_Field1:term^3)'),
)->return($this->getFakeRawSolrResponse()); $this->anything(),
$this->anything(),
$this->anything(),
$this->anything()
)->willReturn($this->getFakeRawSolrResponse());
$index = new SolrIndexTest_FakeIndex(); $index = new SolrIndexTest_FakeIndex();
$index->setService($serviceMock); $index->setService($serviceMock);
@ -85,15 +79,6 @@ class SolrIndexTest extends SapphireTest
array('Field1' => 1.5, 'HasOneObject_Field1' => 3) array('Field1' => 1.5, 'HasOneObject_Field1' => 3)
); );
$index->search($query); $index->search($query);
Phockito::verify($serviceMock)
->search(
'+(Field1:term^1.5 OR HasOneObject_Field1:term^3)',
\Hamcrest_Matchers::anything(),
\Hamcrest_Matchers::anything(),
\Hamcrest_Matchers::anything(),
\Hamcrest_Matchers::anything()
);
} }
/** /**
@ -101,15 +86,20 @@ class SolrIndexTest extends SapphireTest
*/ */
public function testBoostedField() public function testBoostedField()
{ {
$serviceMock = $this->getServiceMock(); /** @var Solr3Service|PHPUnit_Framework_MockObject_MockObject $serviceMock */
Phockito::when($serviceMock) $serviceMock = $this->getMockBuilder(Solr3Service::class)
->search( ->setMethods(['search'])
\Hamcrest_Matchers::anything(), ->getMock();
\Hamcrest_Matchers::anything(),
\Hamcrest_Matchers::anything(), $serviceMock->expects($this->once())
\Hamcrest_Matchers::anything(), ->method('search')
\Hamcrest_Matchers::anything() ->with($this->equalTo('+term'),
)->return($this->getFakeRawSolrResponse()); $this->anything(),
$this->anything(),
$this->equalTo(['qf' => SearchUpdaterTest_Container::class . '_Field1^1.5 ' . SearchUpdaterTest_Container::class . '_Field2^2.1 _text',
'fq' => '+(_versionedstage:"" (*:* -_versionedstage:[* TO *]))']),
$this->anything()
)->willReturn($this->getFakeRawSolrResponse());
$index = new SolrIndexTest_BoostedIndex(); $index = new SolrIndexTest_BoostedIndex();
$index->setService($serviceMock); $index->setService($serviceMock);
@ -117,32 +107,34 @@ class SolrIndexTest extends SapphireTest
$query = new SearchQuery(); $query = new SearchQuery();
$query->search('term'); $query->search('term');
$index->search($query); $index->search($query);
// Ensure matcher contains correct boost in 'qf' parameter
$matcher = new Hamcrest_Array_IsArrayContainingKeyValuePair(
new Hamcrest_Core_IsEqual('qf'),
new Hamcrest_Core_IsEqual('SearchUpdaterTest_Container_Field1^1.5 SearchUpdaterTest_Container_Field2^2.1 _text')
);
Phockito::verify($serviceMock)
->search(
'+term',
\Hamcrest_Matchers::anything(),
\Hamcrest_Matchers::anything(),
$matcher,
\Hamcrest_Matchers::anything()
);
} }
public function testHighlightQueryOnBoost() public function testHighlightQueryOnBoost()
{ {
$serviceMock = $this->getServiceMock(); /** @var SilverStripe\FullTextSearch\Solr\Services\Solr3Service|ObjectProphecy $serviceMock */
Phockito::when($serviceMock)->search( $serviceMock = $this->getMockBuilder(Solr3Service::class)
\Hamcrest_Matchers::anything(), ->setMethods(['search'])
\Hamcrest_Matchers::anything(), ->getMock();
\Hamcrest_Matchers::anything(),
\Hamcrest_Matchers::anything(), $serviceMock->expects($this->exactly(2))
\Hamcrest_Matchers::anything() ->method('search')
)->return($this->getFakeRawSolrResponse()); ->withConsecutive([
$this->equalTo('+(Field1:term^1.5 OR HasOneObject_Field1:term^3)'),
$this->anything(),
$this->anything(),
$this->logicalNot(
$this->arrayHasKey('hl.q')
),
$this->anything()
],
[
$this->equalTo('+(Field1:term^1.5 OR HasOneObject_Field1:term^3)'),
$this->anything(),
$this->anything(),
$this->arrayHasKey('hl.q'),
$this->anything()
]
)->willReturn($this->getFakeRawSolrResponse());
$index = new SolrIndexTest_FakeIndex(); $index = new SolrIndexTest_FakeIndex();
$index->setService($serviceMock); $index->setService($serviceMock);
@ -155,14 +147,6 @@ class SolrIndexTest extends SapphireTest
array('Field1' => 1.5, 'HasOneObject_Field1' => 3) array('Field1' => 1.5, 'HasOneObject_Field1' => 3)
); );
$index->search($query); $index->search($query);
Phockito::verify(
$serviceMock)->search(
'+(Field1:term^1.5 OR HasOneObject_Field1:term^3)',
\Hamcrest_Matchers::anything(),
\Hamcrest_Matchers::anything(),
\Hamcrest_Matchers::not(\Hamcrest_Matchers::hasKeyInArray('hl.q')),
\Hamcrest_Matchers::anything()
);
// Search with highlighting // Search with highlighting
$query = new SearchQuery(); $query = new SearchQuery();
@ -172,57 +156,50 @@ class SolrIndexTest extends SapphireTest
array('Field1' => 1.5, 'HasOneObject_Field1' => 3) array('Field1' => 1.5, 'HasOneObject_Field1' => 3)
); );
$index->search($query, -1, -1, array('hl' => true)); $index->search($query, -1, -1, array('hl' => true));
Phockito::verify(
$serviceMock)->search(
'+(Field1:term^1.5 OR HasOneObject_Field1:term^3)',
\Hamcrest_Matchers::anything(),
\Hamcrest_Matchers::anything(),
\Hamcrest_Matchers::hasKeyInArray('hl.q'),
\Hamcrest_Matchers::anything()
);
} }
public function testIndexExcludesNullValues() public function testIndexExcludesNullValues()
{ {
$serviceMock = $this->getServiceMock(); /** @var Solr3Service|ObjectProphecy $serviceMock */
$serviceMock = $this->createMock(Solr3Service::class);
$index = new SolrIndexTest_FakeIndex(); $index = new SolrIndexTest_FakeIndex();
$index->setService($serviceMock); $index->setService($serviceMock);
$obj = new Container(); $obj = new SearchUpdaterTest_Container();
$obj->Field1 = 'Field1 val'; $obj->Field1 = 'Field1 val';
$obj->Field2 = null; $obj->Field2 = null;
$obj->MyDate = null; $obj->MyDate = null;
$docs = $index->add($obj); $docs = $index->add($obj);
$value = $docs[0]->getField('SearchUpdaterTest_Container_Field1'); $value = $docs[0]->getField(SearchUpdaterTest_Container::class . '_Field1');
$this->assertEquals('Field1 val', $value['value'], 'Writes non-NULL string fields'); $this->assertEquals('Field1 val', $value['value'], 'Writes non-NULL string fields');
$value = $docs[0]->getField('SearchUpdaterTest_Container_Field2'); $value = $docs[0]->getField(SearchUpdaterTest_Container::class . '_Field2');
$this->assertFalse($value, 'Ignores string fields if they are NULL'); $this->assertFalse($value, 'Ignores string fields if they are NULL');
$value = $docs[0]->getField('SearchUpdaterTest_Container_MyDate'); $value = $docs[0]->getField(SearchUpdaterTest_Container::class . '_MyDate');
$this->assertFalse($value, 'Ignores date fields if they are NULL'); $this->assertFalse($value, 'Ignores date fields if they are NULL');
$obj->MyDate = '2010-12-30'; $obj->MyDate = '2010-12-30';
$docs = $index->add($obj); $docs = $index->add($obj);
$value = $docs[0]->getField('SearchUpdaterTest_Container_MyDate'); $value = $docs[0]->getField(SearchUpdaterTest_Container::class . '_MyDate');
$this->assertEquals('2010-12-30T00:00:00Z', $value['value'], 'Writes non-NULL dates'); $this->assertEquals('2010-12-30T00:00:00Z', $value['value'], 'Writes non-NULL dates');
} }
public function testAddFieldExtraOptions() public function testAddFieldExtraOptions()
{ {
Config::inst()->nest(); Config::nest();
Config::modify()->set('Director', 'environment_type', 'live'); // dev mode sets stored=true for everything Director::set_environment_type('live');
$index = new SolrIndexTest_FakeIndex(); $index = new SolrIndexTest_FakeIndex();
$defs = simplexml_load_string('<fields>' . $index->getFieldDefinitions() . '</fields>'); $defs = simplexml_load_string('<fields>' . $index->getFieldDefinitions() . '</fields>');
$defField1 = $defs->xpath('field[@name="SearchUpdaterTest_Container_Field1"]'); $defField1 = $defs->xpath('field[@name="' . SearchUpdaterTest_Container::class . '_Field1"]');
$this->assertEquals((string)$defField1[0]['stored'], 'false'); $this->assertEquals((string)$defField1[0]['stored'], 'false');
$index->addFilterField('Field1', null, array('stored' => 'true')); $index->addFilterField('Field1', null, array('stored' => 'true'));
$defs = simplexml_load_string('<fields>' . $index->getFieldDefinitions() . '</fields>'); $defs = simplexml_load_string('<fields>' . $index->getFieldDefinitions() . '</fields>');
$defField1 = $defs->xpath('field[@name="SearchUpdaterTest_Container_Field1"]'); $defField1 = $defs->xpath('field[@name="' . SearchUpdaterTest_Container::class . '_Field1"]');
$this->assertEquals((string)$defField1[0]['stored'], 'true'); $this->assertEquals((string)$defField1[0]['stored'], 'true');
Config::inst()->unnest(); Config::unnest();
} }
public function testAddAnalyzer() public function testAddAnalyzer()
@ -230,13 +207,13 @@ class SolrIndexTest extends SapphireTest
$index = new SolrIndexTest_FakeIndex(); $index = new SolrIndexTest_FakeIndex();
$defs = simplexml_load_string('<fields>' . $index->getFieldDefinitions() . '</fields>'); $defs = simplexml_load_string('<fields>' . $index->getFieldDefinitions() . '</fields>');
$defField1 = $defs->xpath('field[@name="SearchUpdaterTest_Container_Field1"]'); $defField1 = $defs->xpath('field[@name="' . SearchUpdaterTest_Container::class . '_Field1"]');
$analyzers = $defField1[0]->analyzer; $analyzers = $defField1[0]->analyzer;
$this->assertFalse((bool)$analyzers); $this->assertFalse((bool)$analyzers);
$index->addAnalyzer('Field1', 'charFilter', array('class' => 'solr.HTMLStripCharFilterFactory')); $index->addAnalyzer('Field1', 'charFilter', array('class' => 'solr.HTMLStripCharFilterFactory'));
$defs = simplexml_load_string('<fields>' . $index->getFieldDefinitions() . '</fields>'); $defs = simplexml_load_string('<fields>' . $index->getFieldDefinitions() . '</fields>');
$defField1 = $defs->xpath('field[@name="SearchUpdaterTest_Container_Field1"]'); $defField1 = $defs->xpath('field[@name="' . SearchUpdaterTest_Container::class . '_Field1"]');
$analyzers = $defField1[0]->analyzer; $analyzers = $defField1[0]->analyzer;
$this->assertTrue((bool)$analyzers); $this->assertTrue((bool)$analyzers);
$this->assertEquals('solr.HTMLStripCharFilterFactory', $analyzers[0]->charFilter[0]['class']); $this->assertEquals('solr.HTMLStripCharFilterFactory', $analyzers[0]->charFilter[0]['class']);
@ -265,11 +242,11 @@ class SolrIndexTest extends SapphireTest
$index->addFulltextField('Field2'); $index->addFulltextField('Field2');
$schema = $index->getFieldDefinitions(); $schema = $index->getFieldDefinitions();
$this->assertContains( $this->assertContains(
"<field name='SearchUpdaterTest_Container_Field1' type='text' indexed='true' stored='true'", "<field name='" . SearchUpdaterTest_Container::class . "_Field1' type='text' indexed='true' stored='true'",
$schema $schema
); );
$this->assertContains( $this->assertContains(
"<field name='SearchUpdaterTest_Container_Field2' type='text' indexed='true' stored='false'", "<field name='" . SearchUpdaterTest_Container::class . "_Field2' type='text' indexed='true' stored='false'",
$schema $schema
); );
@ -279,35 +256,19 @@ class SolrIndexTest extends SapphireTest
$index2->addStoredField('Field2'); $index2->addStoredField('Field2');
$schema2 = $index2->getFieldDefinitions(); $schema2 = $index2->getFieldDefinitions();
$this->assertContains( $this->assertContains(
"<field name='SearchUpdaterTest_Container_Field1' type='text' indexed='true' stored='false'", "<field name='" . SearchUpdaterTest_Container::class . "_Field1' type='text' indexed='true' stored='false'",
$schema2 $schema2
); );
$this->assertContains( $this->assertContains(
"<field name='SearchUpdaterTest_Container_Field2' type='text' indexed='true' stored='true'", "<field name='" . SearchUpdaterTest_Container::class . "_Field2' type='text' indexed='true' stored='true'",
$schema2 $schema2
); );
} }
/**
* @return Solr3Service
*/
protected function getServiceMock()
{
return Phockito::mock('Solr3Service');
}
protected function getServiceSpy()
{
$serviceSpy = Phockito::spy('Solr3Service');
Phockito::when($serviceSpy)->_sendRawPost()->return($this->getFakeRawSolrResponse());
return $serviceSpy;
}
protected function getFakeRawSolrResponse() protected function getFakeRawSolrResponse()
{ {
return new Apache_Solr_Response( return new \Apache_Solr_Response(
new Apache_Solr_HttpTransport_Response( new \Apache_Solr_HttpTransport_Response(
null, null,
null, null,
'{}' '{}'

View File

@ -3,6 +3,7 @@
namespace SilverStripe\FullTextSearch\Tests\SolrIndexTest; namespace SilverStripe\FullTextSearch\Tests\SolrIndexTest;
use SilverStripe\FullTextSearch\Solr\SolrIndex; use SilverStripe\FullTextSearch\Solr\SolrIndex;
use SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_Container;
class SolrIndexTest_BoostedIndex extends SolrIndex class SolrIndexTest_BoostedIndex extends SolrIndex
{ {
@ -14,9 +15,9 @@ class SolrIndexTest_BoostedIndex extends SolrIndex
public function init() public function init()
{ {
$this->addClass('SearchUpdaterTest_Container'); $this->addClass(SearchUpdaterTest_Container::class);
$this->addAllFulltextFields(); $this->addAllFulltextFields();
$this->setFieldBoosting('SearchUpdaterTest_Container_Field1', 1.5); $this->setFieldBoosting(SearchUpdaterTest_Container::class . '_Field1', 1.5);
$this->addBoostedField('Field2', null, array(), 2.1); $this->addBoostedField('Field2', null, array(), 2.1);
} }
} }

View File

@ -3,12 +3,13 @@
namespace SilverStripe\FullTextSearch\Tests\SolrIndexTest; namespace SilverStripe\FullTextSearch\Tests\SolrIndexTest;
use SilverStripe\FullTextSearch\Solr\SolrIndex; use SilverStripe\FullTextSearch\Solr\SolrIndex;
use SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_Container;
class SolrIndexTest_FakeIndex extends SolrIndex class SolrIndexTest_FakeIndex extends SolrIndex
{ {
public function init() public function init()
{ {
$this->addClass('SearchUpdaterTest_Container'); $this->addClass(SearchUpdaterTest_Container::class);
$this->addFilterField('Field1'); $this->addFilterField('Field1');
$this->addFilterField('MyDate', 'Date'); $this->addFilterField('MyDate', 'Date');

View File

@ -3,6 +3,7 @@
namespace SilverStripe\FullTextSearch\Tests\SolrIndexTest; namespace SilverStripe\FullTextSearch\Tests\SolrIndexTest;
use SilverStripe\FullTextSearch\Solr\SolrIndex; use SilverStripe\FullTextSearch\Solr\SolrIndex;
use SilverStripe\FullTextSearch\Tests\SearchUpdaterTest\SearchUpdaterTest_Container;
class SolrIndexTest_FakeIndex2 extends SolrIndex class SolrIndexTest_FakeIndex2 extends SolrIndex
{ {
@ -14,7 +15,7 @@ class SolrIndexTest_FakeIndex2 extends SolrIndex
public function init() public function init()
{ {
$this->addClass('SearchUpdaterTest_Container'); $this->addClass(SearchUpdaterTest_Container::class);
$this->addFilterField('MyDate', 'Date'); $this->addFilterField('MyDate', 'Date');
$this->addFilterField('HasOneObject.Field1'); $this->addFilterField('HasOneObject.Field1');
$this->addFilterField('HasManyObjects.Field1'); $this->addFilterField('HasManyObjects.Field1');

View File

@ -1,58 +1,51 @@
<?php <?php
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\FullTextSearch\Tests\SolrVersionedTest\SolrDocumentMatcher; use SilverStripe\Core\Config\Config;
use SilverStripe\FullTextSearch\Tests\SolrVersionedTest\SolrIndexVersionedTest_Object; use SilverStripe\ORM\DataObject;
use SilverStripe\FullTextSearch\Tests\SolrVersionedTest\SolrVersionedTest_Index; use SilverStripe\FullTextSearch\Search\FullTextSearch;
use SilverStripe\FullTextSearch\Search\SearchIntrospection;
use SilverStripe\FullTextSearch\Search\Indexes\SearchIndex_Recording;
use SilverStripe\FullTextSearch\Solr\Services\Solr3Service;
use SilverStripe\FullTextSearch\Tests\SearchVariantVersionedTest\SearchVariantVersionedTest_Item;
use SilverStripe\FullTextSearch\Tests\SolrIndexVersionedTest\SolrIndexVersionedTest_Object;
use SilverStripe\FullTextSearch\Tests\SolrIndexVersionedTest\SolrVersionedTest_Index;
use SilverStripe\FullTextSearch\Search\Processors\SearchUpdateProcessor;
use SilverStripe\FullTextSearch\Search\Processors\SearchUpdateImmediateProcessor;
use SilverStripe\FullTextSearch\Search\Updaters\SearchUpdater;
use SilverStripe\FullTextSearch\Search\Variants\SearchVariantVersioned;
use SilverStripe\Versioned\Versioned; use SilverStripe\Versioned\Versioned;
if (class_exists('Phockito')) {
Phockito::include_hamcrest(false);
}
class SolrIndexVersionedTest extends SapphireTest class SolrIndexVersionedTest extends SapphireTest
{ {
protected $oldMode = null; protected $oldMode = null;
protected static $index = null; protected static $index = null;
protected $extraDataObjects = array( protected static $extra_dataobjects = array(
'SearchVariantVersionedTest_Item', SearchVariantVersionedTest_Item::class,
'SolrIndexVersionedTest_Object', SolrIndexVersionedTest_Object::class
); );
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
if (!class_exists('Phockito')) {
$this->skipTest = true;
$this->markTestSkipped("These tests need the Phockito module installed to run");
return;
}
// Check versioned available
if (!class_exists('Versioned')) {
$this->skipTest = true;
$this->markTestSkipped('The versioned decorator is not installed');
return;
}
if (self::$index === null) { if (self::$index === null) {
self::$index = singleton('SolrVersionedTest_Index'); self::$index = singleton(SolrVersionedTest_Index::class);
} }
SearchUpdater::bind_manipulation_capture(); SearchUpdater::bind_manipulation_capture();
Config::modify()->set('Injector', 'SearchUpdateProcessor', array( Config::modify()->set('Injector', SearchUpdateProcessor::class, array(
'class' => 'SearchUpdateImmediateProcessor' 'class' => SearchUpdateImmediateProcessor::class
)); ));
FullTextSearch::force_index_list(self::$index); FullTextSearch::force_index_list(self::$index);
SearchUpdater::clear_dirty_indexes(); SearchUpdater::clear_dirty_indexes();
$this->oldMode = Versioned::get_reading_mode(); $this->oldMode = Versioned::get_reading_mode();
Versioned::reading_stage('Stage'); Versioned::set_stage('Stage');
} }
public function tearDown() public function tearDown()
@ -61,9 +54,17 @@ class SolrIndexVersionedTest extends SapphireTest
parent::tearDown(); parent::tearDown();
} }
protected function getServiceMock() protected function getServiceMock($setMethods = array())
{ {
return Phockito::mock('Solr3Service'); // Setup mock
/** @var SilverStripe\FullTextSearch\Solr\Services\Solr3Service|ObjectProphecy $serviceMock */
$serviceMock = $this->getMockBuilder(Solr3Service::class)
->setMethods($setMethods)
->getMock();
self::$index->setService($serviceMock);
return $serviceMock;
} }
/** /**
@ -74,104 +75,164 @@ class SolrIndexVersionedTest extends SapphireTest
protected function getExpectedDocumentId($object, $stage) protected function getExpectedDocumentId($object, $stage)
{ {
$id = $object->ID; $id = $object->ID;
$class = ClassInfo::baseDataClass($object); $class = DataObject::getSchema()->baseDataClass($object);
// Prevent subsites from breaking tests // Prevent subsites from breaking tests
// TODO: Subsites currently isn't migrated. This needs to be fixed when subsites is fixed.
$subsites = ''; $subsites = '';
if(class_exists('Subsite') && DataObject::getSchema()->hasOneComponent($object->getClassName(), 'Subsite')) { if(class_exists('Subsite') && DataObject::getSchema()->hasOneComponent($object->getClassName(), 'Subsite')) {
$subsites = '"SearchVariantSubsites":"0",'; $subsites = '"SearchVariantSubsites":"0",';
} }
return $id.'-'.$class.'-{'.$subsites.'"SearchVariantVersioned":"'.$stage.'"}'; return $id.'-'.$class.'-{'.$subsites. json_encode(SearchVariantVersioned::class) . ':"'.$stage.'"}';
}
/**
* @param string $class
* @param DataObject $object Item being added
* @param string $value Value for class
* @param string $stage Stage updated
* @return Apache_Solr_Document
*/
protected function getSolrDocument($class, $object, $value, $stage)
{
$doc = new \Apache_Solr_Document();
$doc->setField('_documentid', $this->getExpectedDocumentId($object, $stage));
$doc->setField('ClassName', $class);
$doc->setField(DataObject::getSchema()->baseDataClass($class) . '_TestText', $value);
$doc->setField('_versionedstage', $stage);
$doc->setField('ID', $object->ID);
$doc->setField('ClassHierarchy', SearchIntrospection::hierarchy($class));
$doc->setFieldBoost('ID', false);
$doc->setFieldBoost('ClassHierarchy', false);
return $doc;
} }
public function testPublishing() public function testPublishing()
{ {
// Setup mocks
$serviceMock = $this->getServiceMock();
self::$index->setService($serviceMock);
// Check that write updates Stage // Check that write updates Stage
Versioned::reading_stage('Stage'); Versioned::set_stage('Stage');
Phockito::reset($serviceMock);
$item = new SearchVariantVersionedTest_Item(array('TestText' => 'Foo')); $item = new SearchVariantVersionedTest_Item(array('TestText' => 'Foo'));
$item->write(); $item->write();
$object = new SolrIndexVersionedTest_Object(array('TestText' => 'Bar')); $object = new SolrIndexVersionedTest_Object(array('TestText' => 'Bar'));
$object->write(); $object->write();
$doc1 = $this->getSolrDocument(SearchVariantVersionedTest_Item::class, $item, 'Foo', 'Stage');
$doc2 = $this->getSolrDocument(SolrIndexVersionedTest_Object::class, $object, 'Bar', 'Stage');
// Ensure correct call is made to Solr
$this->getServiceMock(['addDocument', 'commit'])
->expects($this->exactly(2))
->method('addDocument')
->withConsecutive(
[
$this->equalTo($doc1),
$this->anything(),
$this->anything(),
$this->anything(),
$this->anything()
],
[
$this->equalTo($doc2),
$this->anything(),
$this->anything(),
$this->anything(),
$this->anything()
]
);
SearchUpdater::flush_dirty_indexes(); SearchUpdater::flush_dirty_indexes();
$doc1 = new SolrDocumentMatcher(array(
'_documentid' => $this->getExpectedDocumentId($item, 'Stage'),
'ClassName' => 'SearchVariantVersionedTest_Item',
'SearchVariantVersionedTest_Item_TestText' => 'Foo',
'_versionedstage' => 'Stage'
));
$doc2 = new SolrDocumentMatcher(array(
'_documentid' => $this->getExpectedDocumentId($object, 'Stage'),
'ClassName' => 'SolrIndexVersionedTest_Object',
'SolrIndexVersionedTest_Object_TestText' => 'Bar',
'_versionedstage' => 'Stage'
));
Phockito::verify($serviceMock)->addDocument($doc1);
Phockito::verify($serviceMock)->addDocument($doc2);
// Check that write updates Live // Check that write updates Live
Versioned::reading_stage('Stage'); Versioned::set_stage('Stage');
Phockito::reset($serviceMock);
$item = new SearchVariantVersionedTest_Item(array('TestText' => 'Foo')); $item = new SearchVariantVersionedTest_Item(array('TestText' => 'Foo'));
$item->write(); $item->write();
$item->publish('Stage', 'Live'); $item->copyVersionToStage('Stage', 'Live');
$object = new SolrIndexVersionedTest_Object(array('TestText' => 'Bar')); $object = new SolrIndexVersionedTest_Object(array('TestText' => 'Bar'));
$object->write(); $object->write();
$object->publish('Stage', 'Live'); $object->copyVersionToStage('Stage', 'Live');
$doc1 = $this->getSolrDocument(SearchVariantVersionedTest_Item::class, $item, 'Foo', 'Stage');
$doc2 = $this->getSolrDocument(SearchVariantVersionedTest_Item::class, $item, 'Foo', 'Live');
$doc3 = $this->getSolrDocument(SolrIndexVersionedTest_Object::class, $object, 'Bar', 'Stage');
$doc4 = $this->getSolrDocument(SolrIndexVersionedTest_Object::class, $object, 'Bar', 'Live');
// Ensure correct call is made to Solr
$this->getServiceMock(['addDocument', 'commit'])
->expects($this->exactly(4))
->method('addDocument')
->withConsecutive(
[
$this->equalTo($doc1),
$this->anything(),
$this->anything(),
$this->anything(),
$this->anything()
],
[
$this->equalTo($doc2),
$this->anything(),
$this->anything(),
$this->anything(),
$this->anything()
],
[
$this->equalTo($doc3),
$this->anything(),
$this->anything(),
$this->anything(),
$this->anything()
],
[
$this->equalTo($doc4),
$this->anything(),
$this->anything(),
$this->anything(),
$this->anything()
]
);
SearchUpdater::flush_dirty_indexes(); SearchUpdater::flush_dirty_indexes();
$doc = new SolrDocumentMatcher(array(
'_documentid' => $this->getExpectedDocumentId($item, 'Live'),
'ClassName' => 'SearchVariantVersionedTest_Item',
'SearchVariantVersionedTest_Item_TestText' => 'Foo',
'_versionedstage' => 'Live'
));
$doc2 = new SolrDocumentMatcher(array(
'_documentid' => $this->getExpectedDocumentId($object, 'Live'),
'ClassName' => 'SolrIndexVersionedTest_Object',
'SolrIndexVersionedTest_Object_TestText' => 'Bar',
'_versionedstage' => 'Live'
));
Phockito::verify($serviceMock)->addDocument($doc);
Phockito::verify($serviceMock)->addDocument($doc2);
} }
public function testDelete() public function testDelete()
{ {
// Setup mocks
$serviceMock = $this->getServiceMock();
self::$index->setService($serviceMock);
// Delete the live record (not the stage) // Delete the live record (not the stage)
Versioned::reading_stage('Stage'); Versioned::set_stage('Stage');
Phockito::reset($serviceMock);
$item = new SearchVariantVersionedTest_Item(array('TestText' => 'Too')); $item = new SearchVariantVersionedTest_Item(array('TestText' => 'Too'));
$item->write(); $item->write();
$item->publish('Stage', 'Live'); $item->copyVersionToStage('Stage', 'Live');
Versioned::reading_stage('Live'); Versioned::set_stage('Live');
$id = clone $item; $id = clone $item;
$item->delete(); $item->delete();
// Check that only the 'Live' version is deleted
$this->getServiceMock(['addDocument', 'commit', 'deleteById'])
->expects($this->exactly(1))
->method('deleteById')
->with($this->equalTo($this->getExpectedDocumentId($id, 'Live')));
SearchUpdater::flush_dirty_indexes(); SearchUpdater::flush_dirty_indexes();
Phockito::verify($serviceMock, 1)
->deleteById($this->getExpectedDocumentId($id, 'Live'));
Phockito::verify($serviceMock, 0)
->deleteById($this->getExpectedDocumentId($id, 'Stage'));
// Delete the stage record // Delete the stage record
Versioned::reading_stage('Stage'); Versioned::set_stage('Stage');
Phockito::reset($serviceMock);
$item = new SearchVariantVersionedTest_Item(array('TestText' => 'Too')); $item = new SearchVariantVersionedTest_Item(array('TestText' => 'Too'));
$item->write(); $item->write();
$item->publish('Stage', 'Live'); $item->copyVersionToStage('Stage', 'Live');
$id = clone $item; $id = clone $item;
$item->delete(); $item->delete();
// Check that only the 'Stage' version is deleted
$this->getServiceMock(['addDocument', 'commit', 'deleteById'])
->expects($this->exactly(1))
->method('deleteById')
->with($this->equalTo($this->getExpectedDocumentId($id, 'Stage')));
SearchUpdater::flush_dirty_indexes(); SearchUpdater::flush_dirty_indexes();
Phockito::verify($serviceMock, 1)
->deleteById($this->getExpectedDocumentId($id, 'Stage'));
Phockito::verify($serviceMock, 0)
->deleteById($this->getExpectedDocumentId($id, 'Live'));
} }
} }

View File

@ -1,14 +1,14 @@
<?php <?php
namespace SilverStripe\FullTextSearch\Tests\SolrVersionedTest; namespace SilverStripe\FullTextSearch\Tests\SolrIndexVersionedTest;
if (!class_exists('Phockito')) { if (!class_exists('\Phockito')) {
return; return;
} }
Phockito::include_hamcrest(false); \Phockito::include_hamcrest(false);
class SolrDocumentMatcher extends Hamcrest_BaseMatcher class SolrDocumentMatcher extends \Hamcrest_BaseMatcher
{ {
protected $properties; protected $properties;

View File

@ -1,6 +1,6 @@
<?php <?php
namespace SilverStripe\FullTextSearch\Tests\SolrVersionedTest; namespace SilverStripe\FullTextSearch\Tests\SolrIndexVersionedTest;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use SilverStripe\Dev\TestOnly; use SilverStripe\Dev\TestOnly;
@ -11,6 +11,8 @@ use SilverStripe\Versioned\Versioned;
*/ */
class SolrIndexVersionedTest_Object extends DataObject implements TestOnly { class SolrIndexVersionedTest_Object extends DataObject implements TestOnly {
private static $table_name = 'SolrIndexVersionedTest_Object';
private static $extensions = [ private static $extensions = [
Versioned::class Versioned::class
]; ];

View File

@ -1,15 +1,17 @@
<?php <?php
namespace SilverStripe\FullTextSearch\Tests\SolrVersionedTest; namespace SilverStripe\FullTextSearch\Tests\SolrIndexVersionedTest;
use SilverStripe\FullTextSearch\Solr\SolrIndex; use SilverStripe\FullTextSearch\Solr\SolrIndex;
use SilverStripe\FullTextSearch\Tests\SearchVariantVersionedTest\SearchVariantVersionedTest_Item;
use SilverStripe\FullTextSearch\Tests\SolrIndexVersionedTest\SolrIndexVersionedTest_Object;
class SolrVersionedTest_Index extends SolrIndex class SolrVersionedTest_Index extends SolrIndex
{ {
public function init() public function init()
{ {
$this->addClass('SearchVariantVersionedTest_Item'); $this->addClass(SearchVariantVersionedTest_Item::class);
$this->addClass('SolrIndexVersionedTest_Object'); $this->addClass(SolrIndexVersionedTest_Object::class);
$this->addFilterField('TestText'); $this->addFilterField('TestText');
$this->addFulltextField('Content'); $this->addFulltextField('Content');
} }

View File

@ -1,9 +1,23 @@
<?php <?php
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DB;
use SilverStripe\FullTextSearch\Search\FullTextSearch; use SilverStripe\FullTextSearch\Search\FullTextSearch;
use SilverStripe\FullTextSearch\Solr\Reindex\Handlers\SolrReindexQueuedHandler;
use SilverStripe\FullTextSearch\Solr\Reindex\Handlers\SolrReindexHandler;
use SilverStripe\FullTextSearch\Solr\Services\Solr4Service;
use SilverStripe\FullTextSearch\Solr\Reindex\Jobs\SolrReindexQueuedJob;
use SilverStripe\FullTextSearch\Solr\Reindex\Jobs\SolrReindexGroupQueuedJob;
use SilverStripe\FullTextSearch\Tests\SolrReindexTest\SolrReindexTest_Variant; use SilverStripe\FullTextSearch\Tests\SolrReindexTest\SolrReindexTest_Variant;
use SilverStripe\FullTextSearch\Tests\SolrReindexTest\SolrReindexTest_Index;
use SilverStripe\FullTextSearch\Tests\SolrReindexTest\SolrReindexTest_Item;
use SilverStripe\FullTextSearch\Tests\SolrReindexTest\SolrReindexTest_RecordingLogger;
use SilverStripe\FullTextSearch\Tests\SolrReindexQueuedTest\SolrReindexQueuedTest_Service;
use SilverStripe\QueuedJobs\Services\QueuedJob;
use SilverStripe\QueuedJobs\Services\QueuedJobService;
/** /**
* Additional tests of solr reindexing processes when run with queuedjobs * Additional tests of solr reindexing processes when run with queuedjobs
@ -12,8 +26,8 @@ class SolrReindexQueuedTest extends SapphireTest
{ {
protected $usesDatabase = true; protected $usesDatabase = true;
protected $extraDataObjects = array( protected static $extra_dataobjects = array(
'SolrReindexTest_Item' SolrReindexTest_Item::class
); );
/** /**
@ -34,28 +48,23 @@ class SolrReindexQueuedTest extends SapphireTest
{ {
parent::setUp(); parent::setUp();
if (!class_exists('Phockito')) { if (!interface_exists('SilverStripe\QueuedJobs\Services\QueuedJob')) {
$this->skipTest = true;
return $this->markTestSkipped("These tests need the Phockito module installed to run");
}
if (!interface_exists('QueuedJob')) {
$this->skipTest = true; $this->skipTest = true;
return $this->markTestSkipped("These tests need the QueuedJobs module installed to run"); return $this->markTestSkipped("These tests need the QueuedJobs module installed to run");
} }
// Set queued handler for reindex // Set queued handler for reindex
Config::modify()->set('Injector', 'SolrReindexHandler', array( Config::modify()->set(Injector::class, SolrReindexHandler::class, array(
'class' => 'SolrReindexQueuedHandler' 'class' => SolrReindexQueuedHandler::class
)); ));
Injector::inst()->registerService(new SolrReindexQueuedHandler(), 'SolrReindexHandler'); Injector::inst()->registerService(new SolrReindexQueuedHandler(), SolrReindexHandler::class);
// Set test variant // Set test variant
SolrReindexTest_Variant::enable(); SolrReindexTest_Variant::enable();
// Set index list // Set index list
$this->service = $this->getServiceMock(); $this->service = $this->serviceMock();
$this->index = singleton('SolrReindexTest_Index'); $this->index = singleton(SolrReindexTest_Index::class);
$this->index->setService($this->service); $this->index->setService($this->service);
FullTextSearch::force_index_list($this->index); FullTextSearch::force_index_list($this->index);
} }
@ -68,7 +77,8 @@ class SolrReindexQueuedTest extends SapphireTest
protected function createDummyData($number) protected function createDummyData($number)
{ {
// Populate dataobjects. Use truncate to generate predictable IDs // Populate dataobjects. Use truncate to generate predictable IDs
DB::query('TRUNCATE "SolrReindexTest_Item"'); $tableName = DataObject::getSchema()->tableName(SolrReindexTest_Item::class);
DB::get_conn()->clearTable($tableName);
// Note that we don't create any records in variant = 2, to represent a variant // Note that we don't create any records in variant = 2, to represent a variant
// that should be cleared without any re-indexes performed // that should be cleared without any re-indexes performed
@ -87,9 +97,15 @@ class SolrReindexQueuedTest extends SapphireTest
* *
* @return SolrService * @return SolrService
*/ */
protected function getServiceMock() protected function serviceMock()
{ {
return Phockito::mock('Solr4Service'); // Setup mock
/** @var SilverStripe\FullTextSearch\Solr\Services\Solr4Service|ObjectProphecy $serviceMock */
$serviceMock = $this->getMockBuilder(Solr4Service::class)
->setMethods(['deleteByQuery', 'addDocument'])
->getMock();
return $serviceMock;
} }
public function tearDown() public function tearDown()
@ -106,7 +122,7 @@ class SolrReindexQueuedTest extends SapphireTest
*/ */
protected function getHandler() protected function getHandler()
{ {
return Injector::inst()->get('SolrReindexHandler'); return Injector::inst()->get(SolrReindexHandler::class);
} }
/** /**
@ -114,7 +130,7 @@ class SolrReindexQueuedTest extends SapphireTest
*/ */
protected function getQueuedJobService() protected function getQueuedJobService()
{ {
return singleton('SolrReindexQueuedTest_Service'); return Injector::inst()->get(SolrReindexQueuedTest_Service::class);
} }
/** /**
@ -125,6 +141,20 @@ class SolrReindexQueuedTest extends SapphireTest
{ {
$this->createDummyData(18); $this->createDummyData(18);
// Deletes are performed in the main task prior to individual groups being processed
// 18 records means 3 groups of 6 in each variant (6 total)
// Ensure correct call is made to Solr
$this->service->expects($this->exactly(2))
->method('deleteByQuery')
->withConsecutive(
[
$this->equalTo('-(ClassHierarchy:' . SolrReindexTest_Item::class . ')')
],
[
$this->equalTo('+(ClassHierarchy:' . SolrReindexTest_Item::class . ') +(_testvariant:"2")')
]
);
// Create pre-existing jobs // Create pre-existing jobs
$this->getQueuedJobService()->queueJob(new SolrReindexQueuedJob()); $this->getQueuedJobService()->queueJob(new SolrReindexQueuedJob());
$this->getQueuedJobService()->queueJob(new SolrReindexGroupQueuedJob()); $this->getQueuedJobService()->queueJob(new SolrReindexGroupQueuedJob());
@ -140,7 +170,7 @@ class SolrReindexQueuedTest extends SapphireTest
// Next job should be queue job // Next job should be queue job
$job = $this->getQueuedJobService()->getNextJob(); $job = $this->getQueuedJobService()->getNextJob();
$this->assertInstanceOf('SolrReindexQueuedJob', $job); $this->assertInstanceOf(SolrReindexQueuedJob::class, $job);
$this->assertEquals(6, $job->getBatchSize()); $this->assertEquals(6, $job->getBatchSize());
// Test that necessary items are created // Test that necessary items are created
@ -148,28 +178,19 @@ class SolrReindexQueuedTest extends SapphireTest
$job->setLogger($logger); $job->setLogger($logger);
$job->process(); $job->process();
// Deletes are performed in the main task prior to individual groups being processed
// 18 records means 3 groups of 6 in each variant (6 total)
Phockito::verify($this->service, 2)
->deleteByQuery(\Hamcrest_Matchers::anything());
$this->assertEquals(1, $logger->countMessages('Beginning init of reindex')); $this->assertEquals(1, $logger->countMessages('Beginning init of reindex'));
$this->assertEquals(6, $logger->countMessages('Queued Solr Reindex Group ')); $this->assertEquals(6, $logger->countMessages('Queued Solr Reindex Group '));
$this->assertEquals(3, $logger->countMessages(' of SolrReindexTest_Item in {"SolrReindexTest_Variant":"0"}')); $this->assertEquals(3, $logger->countMessages(' of ' . SolrReindexTest_Item::class . ' in {' . json_encode(SolrReindexTest_Variant::class) . ':"0"}'));
$this->assertEquals(3, $logger->countMessages(' of SolrReindexTest_Item in {"SolrReindexTest_Variant":"1"}')); $this->assertEquals(3, $logger->countMessages(' of ' . SolrReindexTest_Item::class . ' in {' . json_encode(SolrReindexTest_Variant::class) . ':"1"}'));
$this->assertEquals(1, $logger->countMessages('Completed init of reindex')); $this->assertEquals(1, $logger->countMessages('Completed init of reindex'));
// Test that invalid classes are removed // Test that invalid classes are removed
$this->assertNotEmpty($logger->getMessages('Clearing obsolete classes from SolrReindexTest_Index')); $this->assertNotEmpty($logger->getMessages('Clearing obsolete classes from SolrReindexTest_Index'));
Phockito::verify($this->service, 1)
->deleteByQuery('-(ClassHierarchy:SolrReindexTest_Item)');
// Test that valid classes in invalid variants are removed // Test that valid classes in invalid variants are removed
$this->assertNotEmpty($logger->getMessages( $this->assertNotEmpty($logger->getMessages(
'Clearing all records of type SolrReindexTest_Item in the current state: {"SolrReindexTest_Variant":"2"}' 'Clearing all records of type ' . SolrReindexTest_Item::class . ' in the current state: {"' . SolrReindexTest_Variant::class . '":"2"}'
)); ));
Phockito::verify($this->service, 1)
->deleteByQuery('+(ClassHierarchy:SolrReindexTest_Item) +(_testvariant:"2")');
} }
/** /**
@ -188,9 +209,9 @@ class SolrReindexQueuedTest extends SapphireTest
// Check next job is a group queued job // Check next job is a group queued job
$job = $this->getQueuedJobService()->getNextJob(); $job = $this->getQueuedJobService()->getNextJob();
$this->assertInstanceOf('SolrReindexGroupQueuedJob', $job); $this->assertInstanceOf(SolrReindexGroupQueuedJob::class, $job);
$this->assertEquals( $this->assertEquals(
'Solr Reindex Group (1/3) of SolrReindexTest_Item in {"SolrReindexTest_Variant":"0"}', 'Solr Reindex Group (1/3) of ' . SolrReindexTest_Item::class . ' in {' . json_encode(SolrReindexTest_Variant::class) . ':"0"}',
$job->getTitle() $job->getTitle()
); );
@ -201,7 +222,7 @@ class SolrReindexQueuedTest extends SapphireTest
// Check tasks completed (as per non-queuedjob version) // Check tasks completed (as per non-queuedjob version)
$this->assertEquals(1, $logger->countMessages('Beginning reindex group')); $this->assertEquals(1, $logger->countMessages('Beginning reindex group'));
$this->assertEquals(1, $logger->countMessages('Adding SolrReindexTest_Item')); $this->assertEquals(1, $logger->countMessages('Adding ' . SolrReindexTest_Item::class . ''));
$this->assertEquals(1, $logger->countMessages('Queuing commit on all changes')); $this->assertEquals(1, $logger->countMessages('Queuing commit on all changes'));
$this->assertEquals(1, $logger->countMessages('Completed reindex group')); $this->assertEquals(1, $logger->countMessages('Completed reindex group'));
@ -216,19 +237,3 @@ class SolrReindexQueuedTest extends SapphireTest
} }
} }
} }
if (!class_exists('QueuedJobService')) {
return;
}
class SolrReindexQueuedTest_Service extends QueuedJobService implements TestOnly
{
/**
* @return QueuedJob
*/
public function getNextJob()
{
$job = $this->getNextPendingJob();
return $this->initialiseJob($job);
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace SilverStripe\FullTextSearch\Tests\SolrReindexQueuedTest;
use SilverStripe\Dev\TestOnly;
if (!class_exists('SilverStripe\QueuedJobs\Services\QueuedJobService')) {
return;
}
use SilverStripe\QueuedJobs\Services\QueuedJobService;
class SolrReindexQueuedTest_Service extends QueuedJobService implements TestOnly
{
private static $dependencies = [
'queueHandler' => '%$QueueHandler'
];
/**
* @return QueuedJob
*/
public function getNextJob()
{
$job = $this->getNextPendingJob();
return $this->initialiseJob($job);
}
}

View File

@ -1,20 +1,26 @@
<?php <?php
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\FullTextSearch\Search\FullTextSearch; use SilverStripe\FullTextSearch\Search\FullTextSearch;
use SilverStripe\FullTextSearch\Search\Variants\SearchVariant;
use SilverStripe\FullTextSearch\Tests\SolrReindexTest\SolrReindexTest_Variant; use SilverStripe\FullTextSearch\Tests\SolrReindexTest\SolrReindexTest_Variant;
use SilverStripe\FullTextSearch\Tests\SolrReindexTest\SolrReindexTest_Index;
if (class_exists('Phockito')) { use SilverStripe\FullTextSearch\Tests\SolrReindexTest\SolrReindexTest_TestHandler;
Phockito::include_hamcrest(false); use SilverStripe\FullTextSearch\Tests\SolrReindexTest\SolrReindexTest_Item;
} use SilverStripe\FullTextSearch\Tests\SolrReindexTest\SolrReindexTest_RecordingLogger;
use SilverStripe\FullTextSearch\Solr\Services\Solr4Service;
use SilverStripe\FullTextSearch\Solr\Tasks\Solr_Reindex;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DB;
class SolrReindexTest extends SapphireTest class SolrReindexTest extends SapphireTest
{ {
protected $usesDatabase = true; protected $usesDatabase = true;
protected $extraDataObjects = array( protected static $extra_dataobjects = array(
'SolrReindexTest_Item' SolrReindexTest_Item::class
); );
/** /**
@ -35,14 +41,9 @@ class SolrReindexTest extends SapphireTest
{ {
parent::setUp(); parent::setUp();
if (!class_exists('Phockito')) {
$this->skipTest = true;
return $this->markTestSkipped("These tests need the Phockito module installed to run");
}
// Set test handler for reindex // Set test handler for reindex
Config::modify()->set('Injector', 'SolrReindexHandler', array( Config::modify()->set('Injector', 'SolrReindexHandler', array(
'class' => 'SolrReindexTest_TestHandler' 'class' => SolrReindexTest_TestHandler::class
)); ));
Injector::inst()->registerService(new SolrReindexTest_TestHandler(), 'SolrReindexHandler'); Injector::inst()->registerService(new SolrReindexTest_TestHandler(), 'SolrReindexHandler');
@ -51,7 +52,7 @@ class SolrReindexTest extends SapphireTest
// Set index list // Set index list
$this->service = $this->getServiceMock(); $this->service = $this->getServiceMock();
$this->index = singleton('SolrReindexTest_Index'); $this->index = singleton(SolrReindexTest_Index::class);
$this->index->setService($this->service); $this->index->setService($this->service);
FullTextSearch::force_index_list($this->index); FullTextSearch::force_index_list($this->index);
} }
@ -63,8 +64,7 @@ class SolrReindexTest extends SapphireTest
*/ */
protected function createDummyData($number) protected function createDummyData($number)
{ {
// Populate dataobjects. Use truncate to generate predictable IDs self::resetDBSchema();
DB::query('TRUNCATE "SolrReindexTest_Item"');
// Note that we don't create any records in variant = 2, to represent a variant // Note that we don't create any records in variant = 2, to represent a variant
// that should be cleared without any re-indexes performed // that should be cleared without any re-indexes performed
@ -85,7 +85,10 @@ class SolrReindexTest extends SapphireTest
*/ */
protected function getServiceMock() protected function getServiceMock()
{ {
return Phockito::mock('Solr4Service'); $serviceMock = $this->getMockBuilder(Solr4Service::class)
->setMethods(['deleteByQuery', 'addDocument']);
return $serviceMock->getMock();
} }
public function tearDown() public function tearDown()
@ -114,7 +117,7 @@ class SolrReindexTest extends SapphireTest
$variant = SearchVariant::current_state(); $variant = SearchVariant::current_state();
$this->assertEquals( $this->assertEquals(
array( array(
"SolrReindexTest_Variant" => "0" SolrReindexTest_Variant::class => "0"
), ),
$variant $variant
); );
@ -124,13 +127,13 @@ class SolrReindexTest extends SapphireTest
$this->assertEquals( $this->assertEquals(
array( array(
array( array(
"SolrReindexTest_Variant" => "0" SolrReindexTest_Variant::class => "0"
), ),
array( array(
"SolrReindexTest_Variant" => "1" SolrReindexTest_Variant::class => "1"
), ),
array( array(
"SolrReindexTest_Variant" => "2" SolrReindexTest_Variant::class => "2"
) )
), ),
$allStates $allStates
@ -157,36 +160,36 @@ class SolrReindexTest extends SapphireTest
*/ */
public function testReindexSegmentsGroups() public function testReindexSegmentsGroups()
{ {
$this->service->method('deleteByQuery')
->withConsecutive(
['-(ClassHierarchy:' . SolrReindexTest_Item::class . ')'],
['+(ClassHierarchy:' . SolrReindexTest_Item::class . ') +(_testvariant:"2")']
);
$this->createDummyData(120); $this->createDummyData(120);
// Initiate re-index // Initiate re-index
$logger = new SolrReindexTest_RecordingLogger(); $logger = new SolrReindexTest_RecordingLogger();
$this->getHandler()->runReindex($logger, 21, 'Solr_Reindex'); $this->getHandler()->runReindex($logger, 21, Solr_Reindex::class);
// Test that invalid classes are removed // Test that invalid classes are removed
$this->assertNotEmpty($logger->getMessages('Clearing obsolete classes from SolrReindexTest_Index')); $this->assertContains('Clearing obsolete classes from ' . SolrReindexTest_Index::class, $logger->getMessages());
Phockito::verify($this->service, 1) //var_dump($logger->getMessages());
->deleteByQuery('-(ClassHierarchy:SolrReindexTest_Item)');
// Test that valid classes in invalid variants are removed // Test that valid classes in invalid variants are removed
$this->assertNotEmpty($logger->getMessages( $this->assertContains('Clearing all records of type ' . SolrReindexTest_Item::class . ' in the current state: {' . json_encode(SolrReindexTest_Variant::class) . ':"2"}', $logger->getMessages());
'Clearing all records of type SolrReindexTest_Item in the current state: {"SolrReindexTest_Variant":"2"}'
));
Phockito::verify($this->service, 1)
->deleteByQuery('+(ClassHierarchy:SolrReindexTest_Item) +(_testvariant:"2")');
// 120x2 grouped into groups of 21 results in 12 groups // 120x2 grouped into groups of 21 results in 12 groups
$this->assertEquals(12, $logger->countMessages('Called processGroup with ')); $this->assertEquals(12, $logger->countMessages('Called processGroup with '));
$this->assertEquals(6, $logger->countMessages('{"SolrReindexTest_Variant":"0"}')); $this->assertEquals(6, $logger->countMessages('{' . json_encode(SolrReindexTest_Variant::class) . ':"0"}'));
$this->assertEquals(6, $logger->countMessages('{"SolrReindexTest_Variant":"1"}')); $this->assertEquals(6, $logger->countMessages('{' . json_encode(SolrReindexTest_Variant::class) . ':"1"}'));
// Given that there are two variants, there should be two group ids of each number // Given that there are two variants, there should be two group ids of each number
$this->assertEquals(2, $logger->countMessages(' SolrReindexTest_Item, group 0 of 6')); $this->assertEquals(2, $logger->countMessages(' ' . SolrReindexTest_Item::class . ', group 0 of 6'));
$this->assertEquals(2, $logger->countMessages(' SolrReindexTest_Item, group 1 of 6')); $this->assertEquals(2, $logger->countMessages(' ' . SolrReindexTest_Item::class . ', group 1 of 6'));
$this->assertEquals(2, $logger->countMessages(' SolrReindexTest_Item, group 2 of 6')); $this->assertEquals(2, $logger->countMessages(' ' . SolrReindexTest_Item::class . ', group 2 of 6'));
$this->assertEquals(2, $logger->countMessages(' SolrReindexTest_Item, group 3 of 6')); $this->assertEquals(2, $logger->countMessages(' ' . SolrReindexTest_Item::class . ', group 3 of 6'));
$this->assertEquals(2, $logger->countMessages(' SolrReindexTest_Item, group 4 of 6')); $this->assertEquals(2, $logger->countMessages(' ' . SolrReindexTest_Item::class . ', group 4 of 6'));
$this->assertEquals(2, $logger->countMessages(' SolrReindexTest_Item, group 5 of 6')); $this->assertEquals(2, $logger->countMessages(' ' . SolrReindexTest_Item::class . ', group 5 of 6'));
// Check various group sizes // Check various group sizes
$logger->clear(); $logger->clear();
@ -208,25 +211,23 @@ class SolrReindexTest extends SapphireTest
*/ */
public function testRunGroup() public function testRunGroup()
{ {
$this->service->method('deleteByQuery')
->with('+(ClassHierarchy:' . SolrReindexTest_Item::class . ') +_query_:"{!frange l=2 u=2}mod(ID, 6)" +(_testvariant:"1")');
$this->createDummyData(120); $this->createDummyData(120);
$logger = new SolrReindexTest_RecordingLogger(); $logger = new SolrReindexTest_RecordingLogger();
// Initiate re-index of third group (index 2 of 6) // Initiate re-index of third group (index 2 of 6)
$state = array('SolrReindexTest_Variant' => '1'); $state = array(SolrReindexTest_Variant::class => '1');
$this->getHandler()->runGroup($logger, $this->index, $state, 'SolrReindexTest_Item', 6, 2); $this->getHandler()->runGroup($logger, $this->index, $state, SolrReindexTest_Item::class, 6, 2);
$idMessage = $logger->filterMessages('Updated '); $idMessage = $logger->filterMessages('Updated ');
$this->assertNotEmpty(preg_match('/^Updated (?<ids>[,\d]+)/i', $idMessage[0], $matches)); $this->assertNotEmpty(preg_match('/^Updated (?<ids>[,\d]+)/i', $idMessage[0], $matches));
$ids = array_unique(explode(',', $matches['ids'])); $ids = array_unique(explode(',', $matches['ids']));
// Test successful // Test successful
$this->assertNotEmpty($logger->getMessages('Adding SolrReindexTest_Item')); $this->assertNotEmpty($logger->getMessages('Adding ' . SolrReindexTest_Item::class));
$this->assertNotEmpty($logger->getMessages('Done')); $this->assertNotEmpty($logger->getMessages('Done'));
// Test that items in this variant / group are cleared from solr
Phockito::verify($this->service, 1)->deleteByQuery(
'+(ClassHierarchy:SolrReindexTest_Item) +_query_:"{!frange l=2 u=2}mod(ID, 6)" +(_testvariant:"1")'
);
// Test that items in this variant / group are re-indexed // Test that items in this variant / group are re-indexed
// 120 divided into 6 groups should be 20 at least (max 21) // 120 divided into 6 groups should be 20 at least (max 21)
$this->assertEquals(21, count($ids), 'Group size is about 20', 1); $this->assertEquals(21, count($ids), 'Group size is about 20', 1);
@ -241,16 +242,27 @@ class SolrReindexTest extends SapphireTest
*/ */
public function testRunAllGroups() public function testRunAllGroups()
{ {
$this->service->method('deleteByQuery')
->withConsecutive(
['+(ClassHierarchy:' . SolrReindexTest_Item::class . ') +_query_:"{!frange l=0 u=0}mod(ID, 6)" +(_testvariant:"1")'],
['+(ClassHierarchy:' . SolrReindexTest_Item::class . ') +_query_:"{!frange l=1 u=1}mod(ID, 6)" +(_testvariant:"1")'],
['+(ClassHierarchy:' . SolrReindexTest_Item::class . ') +_query_:"{!frange l=2 u=2}mod(ID, 6)" +(_testvariant:"1")'],
['+(ClassHierarchy:' . SolrReindexTest_Item::class . ') +_query_:"{!frange l=3 u=3}mod(ID, 6)" +(_testvariant:"1")'],
['+(ClassHierarchy:' . SolrReindexTest_Item::class . ') +_query_:"{!frange l=4 u=4}mod(ID, 6)" +(_testvariant:"1")'],
['+(ClassHierarchy:' . SolrReindexTest_Item::class . ') +_query_:"{!frange l=5 u=5}mod(ID, 6)" +(_testvariant:"1")'],
['+(ClassHierarchy:' . SolrReindexTest_Item::class . ') +_query_:"{!frange l=6 u=6}mod(ID, 6)" +(_testvariant:"1")']
);
$this->createDummyData(120); $this->createDummyData(120);
$logger = new SolrReindexTest_RecordingLogger(); $logger = new SolrReindexTest_RecordingLogger();
// Test that running all groups covers the complete set of ids // Test that running all groups covers the complete set of ids
$state = array('SolrReindexTest_Variant' => '1'); $state = array(SolrReindexTest_Variant::class => '1');
for ($i = 0; $i < 6; $i++) { for ($i = 0; $i < 6; $i++) {
// See testReindexSegmentsGroups for test that each of these states is invoked during a full reindex // See testReindexSegmentsGroups for test that each of these states is invoked during a full reindex
$this $this
->getHandler() ->getHandler()
->runGroup($logger, $this->index, $state, 'SolrReindexTest_Item', 6, $i); ->runGroup($logger, $this->index, $state, SolrReindexTest_Item::class, 6, $i);
} }
// Count all ids updated // Count all ids updated
@ -262,24 +274,5 @@ class SolrReindexTest extends SapphireTest
// Check ids // Check ids
$this->assertEquals(120, count($ids)); $this->assertEquals(120, count($ids));
Phockito::verify($this->service, 6)->deleteByQuery(\Hamcrest_Matchers::anything());
Phockito::verify($this->service, 1)->deleteByQuery(
'+(ClassHierarchy:SolrReindexTest_Item) +_query_:"{!frange l=0 u=0}mod(ID, 6)" +(_testvariant:"1")'
);
Phockito::verify($this->service, 1)->deleteByQuery(
'+(ClassHierarchy:SolrReindexTest_Item) +_query_:"{!frange l=1 u=1}mod(ID, 6)" +(_testvariant:"1")'
);
Phockito::verify($this->service, 1)->deleteByQuery(
'+(ClassHierarchy:SolrReindexTest_Item) +_query_:"{!frange l=2 u=2}mod(ID, 6)" +(_testvariant:"1")'
);
Phockito::verify($this->service, 1)->deleteByQuery(
'+(ClassHierarchy:SolrReindexTest_Item) +_query_:"{!frange l=3 u=3}mod(ID, 6)" +(_testvariant:"1")'
);
Phockito::verify($this->service, 1)->deleteByQuery(
'+(ClassHierarchy:SolrReindexTest_Item) +_query_:"{!frange l=4 u=4}mod(ID, 6)" +(_testvariant:"1")'
);
Phockito::verify($this->service, 1)->deleteByQuery(
'+(ClassHierarchy:SolrReindexTest_Item) +_query_:"{!frange l=5 u=5}mod(ID, 6)" +(_testvariant:"1")'
);
} }
} }

View File

@ -9,7 +9,7 @@ class SolrReindexTest_Index extends SolrIndex implements TestOnly
{ {
public function init() public function init()
{ {
$this->addClass('SolrReindexTest_Item'); $this->addClass(SolrReindexTest_Item::class);
$this->addAllFulltextFields(); $this->addAllFulltextFields();
} }
} }

View File

@ -9,8 +9,10 @@ use SilverStripe\FullTextSearch\Tests\SolrReindexTest\SolrReindexTest_ItemExtens
/** /**
* Does not have any variant extensions * Does not have any variant extensions
*/ */
class SolrReindexTest_Item extends DataObject implements TestOnly class SolrReindexTest_Item extends DataObject
{ {
private static $table_name = 'SolrReindexTest_Item';
private static $extensions = [ private static $extensions = [
SolrReindexTest_ItemExtension::class SolrReindexTest_ItemExtension::class
]; ];

View File

@ -4,6 +4,7 @@ namespace SilverStripe\FullTextSearch\Tests\SolrReindexTest;
use SilverStripe\Dev\TestOnly; use SilverStripe\Dev\TestOnly;
use SilverStripe\FullTextSearch\Search\Variants\SearchVariant; use SilverStripe\FullTextSearch\Search\Variants\SearchVariant;
use SilverStripe\ORM\DataObject;
/** /**
* Dummy variant that selects items with field Varient matching the current value * Dummy variant that selects items with field Varient matching the current value
@ -28,7 +29,7 @@ class SolrReindexTest_Variant extends SearchVariant implements TestOnly
self::$current = 0; self::$current = 0;
self::$variants = array( self::$variants = array(
'SolrReindexTest_Variant' => singleton('SolrReindexTest_Variant') self::class => singleton(self::class)
); );
} }
@ -79,7 +80,7 @@ class SolrReindexTest_Variant extends SearchVariant implements TestOnly
'name' => '_testvariant', 'name' => '_testvariant',
'field' => '_testvariant', 'field' => '_testvariant',
'fullfield' => '_testvariant', 'fullfield' => '_testvariant',
'base' => ClassInfo::baseDataClass($class), 'base' => DataObject::getSchema()->baseDataClass($class),
'origin' => $class, 'origin' => $class,
'type' => 'Int', 'type' => 'Int',
'lookup_chain' => array(array('call' => 'variant', 'variant' => $self, 'method' => 'currentState')) 'lookup_chain' => array(array('call' => 'variant', 'variant' => $self, 'method' => 'currentState'))
@ -94,8 +95,8 @@ class SolrReindexTest_Variant extends SearchVariant implements TestOnly
public function appliesTo($class, $includeSubclasses) public function appliesTo($class, $includeSubclasses)
{ {
return $class === 'SolrReindexTest_Item' || return $class === SolrReindexTest_Item::class ||
($includeSubclasses && is_subclass_of($class, 'SolrReindexTest_Item', true)); ($includeSubclasses && is_subclass_of($class, SolrReindexTest_Item::class, true));
} }
public function appliesToEnvironment() public function appliesToEnvironment()