Completed
Push — dev2 ( e1c47c...a28405 )
by Gordon
09:31 queued 06:28
created

assertAttributesHaveExactValues()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12
Metric Value
dl 0
loc 11
ccs 0
cts 11
cp 0
rs 9.4286
cc 3
eloc 8
nc 3
nop 2
crap 12
1
<?php
2
3
use SilverStripe\Elastica\ReindexTask;
4
use SilverStripe\Elastica\ElasticaService;
5
use SilverStripe\Elastica\ElasticaUtil;
6
7
8
class ElasticsearchFunctionalTestBase extends FunctionalTest {
9
	public static $ignoreFixtureFileFor = array();
10
11
	protected $extraDataObjects = array(
12
		'SearchableTestPage','FlickrPhotoTO','FlickrAuthorTO','FlickrSetTO','FlickrTagTO',
13
		'SearchableTestFatherPage','SearchableTestGrandFatherPage'
14
	);
15
16
17
	public function setUpOnce() {
18
		ElasticaUtil::setPrinterOutput(false);
19
20
		$config = Config::inst();
21
		$config->remove('Injector', 'SilverStripe\Elastica\ElasticaService');
22
		$constructor = array('constructor' => array('%$Elastica\Client', 'elastica_ss_module_test'));
23
		$config->update('Injector', 'SilverStripe\Elastica\ElasticaService', $constructor);
24
		parent::setUpOnce();
25
	}
26
27
28 1
	public function setUp() {
0 ignored issues
show
Coding Style introduced by
setUp uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
29
30 1
		echo "*************** TEST: ".$this->getName();
0 ignored issues
show
Bug introduced by
The method getName() does not seem to exist on object<ElasticsearchFunctionalTestBase>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
31
32 1
		$cache = SS_Cache::factory('elasticsearch');
33 1
		$cache->clean(Zend_Cache::CLEANING_MODE_ALL);
34 1
		SS_Cache::set_cache_lifetime('elasticsearch', 3600, 1000);
35
36
		// this needs to be called in order to create the list of searchable
37
		// classes and fields that are available.  Simulates part of a build
38 1
		$classes = array('SearchableTestPage','SiteTree','Page','FlickrPhotoTO','FlickrSetTO',
39 1
			'FlickrTagTO', 'FlickrAuthorTO');
40 1
		$this->requireDefaultRecordsFrom = $classes;
41
42
		// add Searchable extension where appropriate
43 1
		FlickrSetTO::add_extension('SilverStripe\Elastica\Searchable');
44 1
		FlickrPhotoTO::add_extension('SilverStripe\Elastica\Searchable');
45 1
		FlickrTagTO::add_extension('SilverStripe\Elastica\Searchable');
46 1
		FlickrAuthorTO::add_extension('SilverStripe\Elastica\Searchable');
47 1
		SearchableTestPage::add_extension('SilverStripe\Elastica\Searchable');
48
49
		// clear the index
50 1
		$this->service = Injector::inst()->create('SilverStripe\Elastica\ElasticaService');
51 1
		$this->service->setTestMode(true);
52
53
		// A previous test may have deleted the index and then failed, so check for this
54 1
		if (!$this->service->getIndex()->exists()) {
55 1
			$this->service->getIndex()->create();
56 1
		}
57 1
		$this->service->reset();
58
59
		// FIXME - use request getVar instead?
60 1
		$_GET['progress'] = 20;
61
		// load fixtures
62
63 1
		$orig_fixture_file = static::$fixture_file;
64
65 1 View Code Duplication
		foreach (static::$ignoreFixtureFileFor as $testPattern) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
66
			$pattern = '/'.$testPattern.'/';
67
			if (preg_match($pattern, $this->getName())) {
0 ignored issues
show
Bug introduced by
The method getName() does not seem to exist on object<ElasticsearchFunctionalTestBase>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
68
				static::$fixture_file = null;
69
			}
70 1
		}
71
72 1
		parent::setUp();
73 1
		static::$fixture_file = $orig_fixture_file;
74
75 1
		$this->publishSiteTree();
76
77 1
		$this->service->reset();
78
79
		// index loaded fixtures
80 1
		$task = new ReindexTask($this->service);
81
		// null request is fine as no parameters used
82
83 1
		$task->run(null);
84
85 1
	}
86
87
88 1
	private function publishSiteTree() {
89 1
		foreach (SiteTree::get()->getIterator() as $page) {
90
			// temporarily disable Elasticsearch indexing, it will be done in a batch
91 1
			$page->IndexingOff = true;
92
93 1
			$page->publish('Stage','Live');
94 1
		}
95 1
	}
96
97
98
	//---- The HTML for search results is too long to check for, so instead check just the starting text ----
99
100
	/**
101
	 *Assert that the indexth matching css node has a prefix as expected
102
	 *
103
	 * Note: &nbsp; characters are stripped from the content; make sure that your assertions take this into account.
104
	 *
105
	 * @param string $selector A basic CSS selector, e.g. 'li.jobs h3'
106
	 * @param array|string $expectedMatches The content of at least one of the matched tags
0 ignored issues
show
Bug introduced by
There is no parameter named $expectedMatches. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
107
	 * @throws PHPUnit_Framework_AssertionFailedError
108
	 * @return boolean
109
	 */
110
	public function assertSelectorStartsWithOrEquals($selector, $index, $expectedPrefix) {
111
		$items = $this->cssParser()->getBySelector($selector);
112
113
		$ctr = 0;
114
		foreach ($items as $item) {
115
			$text = strip_tags($item);
116
			$escaped = str_replace("'", "\'", $text);
0 ignored issues
show
Unused Code introduced by
$escaped is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
117
			$ctr++;
118
		}
119
120
		$ctr = 0;
0 ignored issues
show
Unused Code introduced by
$ctr is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
121
		$item = strip_tags($items[$index]);
122
123
124
		$errorMessage = "Failed to assert that '$item' started with '$expectedPrefix'";
125
		$this->assertStringStartsWith($expectedPrefix, $item, $errorMessage);
0 ignored issues
show
Bug introduced by
The method assertStringStartsWith() does not seem to exist on object<ElasticsearchFunctionalTestBase>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
126
127
		return true;
128
	}
129
130
131
	/*
132
	Check all the nodes matching the selector for attribute name = expected value
133
	 */
134
	public function assertAttributeHasExactValue($selector, $attributeName, $expectedValue) {
0 ignored issues
show
Unused Code introduced by
The parameter $attributeName is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
135
		$items = $this->cssParser()->getBySelector($selector);
136
		foreach ($items as $item) {
137
			$this->assertEquals($expectedValue, $item['value']);
0 ignored issues
show
Bug introduced by
The method assertEquals() does not seem to exist on object<ElasticsearchFunctionalTestBase>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
138
		}
139
	}
140
141
142
	public function assertAttributesHaveExactValues($selector, $expectedValues) {
143
		$attributeNames = array_keys($expectedValues);
144
		$items = $this->cssParser()->getBySelector($selector);
145
		foreach ($items as $item) {
146
			$actualValues = array();
147
			foreach ($attributeNames as $attributeName) {
148
				$actualValues[$attributeName] = (string)$item[$attributeName];
149
			}
150
			$this->assertEquals($expectedValues, $actualValues);
0 ignored issues
show
Bug introduced by
The method assertEquals() does not seem to exist on object<ElasticsearchFunctionalTestBase>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
151
		}
152
	}
153
154
155
	public function assertNumberOfNodes($selector, $expectedAmount) {
156
		$items = $this->cssParser()->getBySelector($selector);
157
		foreach ($items as $item) {
158
			$text = strip_tags($item);
0 ignored issues
show
Unused Code introduced by
$text is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
159
		}
160
161
		$ct = sizeof($items);
162
		$this->assertEquals($expectedAmount, $ct);
0 ignored issues
show
Bug introduced by
The method assertEquals() does not seem to exist on object<ElasticsearchFunctionalTestBase>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
163
	}
164
165
166
	/* Collect an array of all the <ClassName>_<ID> search results, used for checking pagination */
167
	public function collateSearchResults() {
168
		$items = $this->cssParser()->getBySelector('div.searchResults .searchResult');
169
		$result = array();
170
		foreach ($items as $item) {
171
			$attr = $item->attributes()->id;
172
			array_push($result, $attr."");
173
		}
174
175
		return $result;
176
	}
177
178
}
179