Completed
Push — dev2 ( f75d77...01a103 )
by Gordon
15:27
created

assertSelectorContains()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 12

Duplication

Lines 18
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 6
Metric Value
dl 18
loc 18
ccs 0
cts 14
cp 0
rs 9.4286
cc 2
eloc 12
nc 2
nop 3
crap 6
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
	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
		error_log("*************** 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
		$cache = SS_Cache::factory('elasticsearch');
33
		$cache->clean(Zend_Cache::CLEANING_MODE_ALL);
34
		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
		$classes = array('SearchableTestPage','SiteTree','Page','FlickrPhotoTO','FlickrSetTO',
39
			'FlickrTagTO', 'FlickrAuthorTO');
40
		$this->requireDefaultRecordsFrom = $classes;
41
42
		// add Searchable extension where appropriate
43
		FlickrSetTO::add_extension('SilverStripe\Elastica\Searchable');
44
		FlickrPhotoTO::add_extension('SilverStripe\Elastica\Searchable');
45
		FlickrTagTO::add_extension('SilverStripe\Elastica\Searchable');
46
		FlickrAuthorTO::add_extension('SilverStripe\Elastica\Searchable');
47
		SearchableTestPage::add_extension('SilverStripe\Elastica\Searchable');
48
49
		$elasticaException = false;
50
51
		try {
52
			// clear the index
53
			$this->service = Injector::inst()->create('SilverStripe\Elastica\ElasticaService');
54
			$this->service->setTestMode(true);
55
56
			// A previous test may have deleted the index and then failed, so check for this
57
			if (!$this->service->getIndex()->exists()) {
58
				$this->service->getIndex()->create();
59
			}
60
			$this->service->reset();
61
62
			// FIXME - use request getVar instead?
63
			$_GET['progress'] = 20;
64
65
			// load fixtures
66
			$orig_fixture_file = static::$fixture_file;
67
68 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...
69
				$pattern = '/'.$testPattern.'/';
70
				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...
71
					static::$fixture_file = null;
72
				}
73
			}
74
		} catch (Exception $e) {
75
			error_log('**** T1 EXCEPTION ' . $e->getMessage());
76
			$elasticaException = true;
77
		}
78
79
		// this has to be executed otherwise nesting exceptions occur
80
		parent::setUp();
81
82
		if ($elasticaException) {
83
			$this->fail('T1 Exception with Elasticsearch');
0 ignored issues
show
Bug introduced by
The method fail() 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...
84
		}
85
86
87
		try {
88
			static::$fixture_file = $orig_fixture_file;
0 ignored issues
show
Bug introduced by
The variable $orig_fixture_file does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
89
90
			$this->publishSiteTree();
91
92
			$this->service->reset();
93
94
			// index loaded fixtures
95
			$task = new ReindexTask($this->service);
96
			// null request is fine as no parameters used
97
98
			$task->run(null);
99
		} catch (Exception $e) {
100
			error_log('**** T2 EXCEPTION ' . $e->getMessage());
101
			$elasticaException = true;
102
		}
103
104
		if ($elasticaException) {
105
			$this->fail('T2 Exception with Elasticsearch');
0 ignored issues
show
Bug introduced by
The method fail() 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...
106
		}
107
	}
108
109
110
	private function publishSiteTree() {
111
		foreach (SiteTree::get()->getIterator() as $page) {
112
			// temporarily disable Elasticsearch indexing, it will be done in a batch
113
			$page->IndexingOff = true;
114
115
			$page->publish('Stage','Live');
116
		}
117
	}
118
119
120
	//---- The HTML for search results is too long to check for, so instead check just the starting text ----
121
122
	/**
123
	 *Assert that the indexth matching css node has a prefix as expected
124
	 *
125
	 * Note: &nbsp; characters are stripped from the content; make sure that your assertions take this into account.
126
	 *
127
	 * @param string $selector A basic CSS selector, e.g. 'li.jobs h3'
128
	 * @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...
129
	 * @throws PHPUnit_Framework_AssertionFailedError
130
	 * @return boolean
131
	 */
132 View Code Duplication
	public function assertSelectorStartsWithOrEquals($selector, $index, $expectedPrefix) {
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in 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...
133
		$items = $this->cssParser()->getBySelector($selector);
134
135
		$ctr = 0;
136
		foreach ($items as $item) {
137
			$text = strip_tags($item);
138
			$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...
139
			$ctr++;
140
		}
141
142
		$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...
143
		$item = strip_tags($items[$index]);
144
145
		$errorMessage = "Failed to assert that '$item' started with '$expectedPrefix'";
146
		$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...
147
148
		return true;
149
	}
150
151
152
		/**
153
	 *Assert that the indexth matching css node has a prefix as expected
154
	 *
155
	 * Note: &nbsp; characters are stripped from the content; make sure that your assertions take this into account.
156
	 *
157
	 * @param string $selector A basic CSS selector, e.g. 'li.jobs h3'
158
	 * @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...
159
	 * @throws PHPUnit_Framework_AssertionFailedError
160
	 * @return boolean
161
	 */
162 View Code Duplication
	public function assertSelectorContains($selector, $index, $expectedClause) {
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in 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...
163
		$items = $this->cssParser()->getBySelector($selector);
164
165
		$ctr = 0;
166
		foreach ($items as $item) {
167
			$text = strip_tags($item);
168
			$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...
169
			$ctr++;
170
		}
171
172
		$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...
173
		$item = strip_tags($items[$index]);
174
175
		$errorMessage = "Failed to assert that '$item' started with '$expectedClause'";
176
		$this->assertContains($expectedClause, $item, $errorMessage);
177
178
		return true;
179
	}
180
181
182
183
	/*
184
	Check all the nodes matching the selector for attribute name = expected value
185
	 */
186
	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...
187
		$items = $this->cssParser()->getBySelector($selector);
188
		foreach ($items as $item) {
189
			$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...
190
		}
191
	}
192
193
194
	public function assertAttributesHaveExactValues($selector, $expectedValues) {
195
		$attributeNames = array_keys($expectedValues);
196
		$items = $this->cssParser()->getBySelector($selector);
197
		foreach ($items as $item) {
198
			$actualValues = array();
199
			foreach ($attributeNames as $attributeName) {
200
				$actualValues[$attributeName] = (string)$item[$attributeName];
201
			}
202
			$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...
203
		}
204
	}
205
206
207
	public function assertNumberOfNodes($selector, $expectedAmount) {
208
		$items = $this->cssParser()->getBySelector($selector);
209
		foreach ($items as $item) {
210
			$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...
211
		}
212
213
		$ct = sizeof($items);
214
		$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...
215
	}
216
217
218
	/* Collect an array of all the <ClassName>_<ID> search results, used for checking pagination */
219
	public function collateSearchResults() {
220
		$items = $this->cssParser()->getBySelector('div.searchResults .searchResult');
221
		$result = array();
222
		foreach ($items as $item) {
223
			$attr = $item->attributes()->id;
224
			array_push($result, $attr."");
225
		}
226
227
		return $result;
228
	}
229
230
}
231