Completed
Push — dev2 ( 76a09a...1cd385 )
by Gordon
14:51
created

ElasticsearchFunctionalTestBase::setUp()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 55
Code Lines 29

Duplication

Lines 6
Ratio 10.91 %
Metric Value
dl 6
loc 55
rs 9.0781
cc 4
eloc 29
nc 6
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
use SilverStripe\Elastica\ReindexTask;
4
use SilverStripe\Elastica\ElasticaService;
5
6
7
class ElasticsearchFunctionalTestBase extends FunctionalTest {
8
	public static $ignoreFixtureFileFor = array();
9
10
	protected $extraDataObjects = array(
11
		'SearchableTestPage','FlickrPhotoTO','FlickrAuthorTO','FlickrSetTO','FlickrTagTO',
12
		'SearchableTestFatherPage','SearchableTestGrandFatherPage'
13
	);
14
15
16
	public function setUpOnce() {
17
		$config = Config::inst();
18
		$config->remove('Injector', 'SilverStripe\Elastica\ElasticaService');
19
		$constructor = array('constructor' => array('%$Elastica\Client', 'elastica_ss_module_test'));
20
		$config->update('Injector', 'SilverStripe\Elastica\ElasticaService', $constructor);
21
		parent::setUpOnce();
22
	}
23
24
25
	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...
26
		$cache = SS_Cache::factory('elasticsearch');
27
		$cache->clean(Zend_Cache::CLEANING_MODE_ALL);
28
		SS_Cache::set_cache_lifetime('elasticsearch', 3600, 1000);
29
30
		// this needs to be called in order to create the list of searchable
31
		// classes and fields that are available.  Simulates part of a build
32
		$classes = array('SearchableTestPage','SiteTree','Page','FlickrPhotoTO','FlickrSetTO',
33
			'FlickrTagTO', 'FlickrAuthorTO');
34
		$this->requireDefaultRecordsFrom = $classes;
35
36
		// add Searchable extension where appropriate
37
		FlickrSetTO::add_extension('SilverStripe\Elastica\Searchable');
38
		FlickrPhotoTO::add_extension('SilverStripe\Elastica\Searchable');
39
		FlickrTagTO::add_extension('SilverStripe\Elastica\Searchable');
40
		FlickrAuthorTO::add_extension('SilverStripe\Elastica\Searchable');
41
		SearchableTestPage::add_extension('SilverStripe\Elastica\Searchable');
42
43
		// clear the index
44
		$this->service = Injector::inst()->create('SilverStripe\Elastica\ElasticaService');
45
		$this->service->setTestMode(true);
46
47
		// A previous test may have deleted the index and then failed, so check for this
48
		if (!$this->service->getIndex()->exists()) {
49
			$this->service->getIndex()->create();
50
		}
51
		$this->service->reset();
52
53
		// FIXME - use request getVar instead?
54
		$_GET['progress'] = 20;
55
		// load fixtures
56
57
		$orig_fixture_file = static::$fixture_file;
58
59 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...
60
			$pattern = '/'.$testPattern.'/';
61
			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...
62
				static::$fixture_file = null;
63
			}
64
		}
65
66
		parent::setUp();
67
		static::$fixture_file = $orig_fixture_file;
68
69
		$this->publishSiteTree();
70
71
		$this->service->reset();
72
73
		// index loaded fixtures
74
		$task = new ReindexTask($this->service);
75
		// null request is fine as no parameters used
76
77
		$task->run(null);
78
79
	}
80
81
82
	private function publishSiteTree() {
83
		foreach (SiteTree::get()->getIterator() as $page) {
84
			// temporarily disable Elasticsearch indexing, it will be done in a batch
85
			$page->IndexingOff = true;
86
87
			$page->publish('Stage','Live');
88
		}
89
	}
90
91
92
	//---- The HTML for search results is too long to check for, so instead check just the starting text ----
93
94
	/**
95
	 *Assert that the indexth matching css node has a prefix as expected
96
	 *
97
	 * Note: &nbsp; characters are stripped from the content; make sure that your assertions take this into account.
98
	 *
99
	 * @param string $selector A basic CSS selector, e.g. 'li.jobs h3'
100
	 * @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...
101
	 * @throws PHPUnit_Framework_AssertionFailedError
102
	 * @return boolean
103
	 */
104
	public function assertSelectorStartsWithOrEquals($selector, $index, $expectedPrefix) {
105
		$items = $this->cssParser()->getBySelector($selector);
106
107
		$ctr = 0;
108
		foreach ($items as $item) {
109
			$text = strip_tags($item);
110
			$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...
111
			$ctr++;
112
		}
113
114
		$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...
115
		$item = strip_tags($items[$index]);
116
117
118
		$errorMessage = "Failed to assert that '$item' started with '$expectedPrefix'";
119
		$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...
120
121
		return true;
122
	}
123
124
125
	/*
126
	Check all the nodes matching the selector for attribute name = expected value
127
	 */
128
	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...
129
		$items = $this->cssParser()->getBySelector($selector);
130
		foreach ($items as $item) {
131
			$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...
132
		}
133
	}
134
135
136
	public function assertAttributesHaveExactValues($selector, $expectedValues) {
137
		$attributeNames = array_keys($expectedValues);
138
		$items = $this->cssParser()->getBySelector($selector);
139
		foreach ($items as $item) {
140
			$actualValues = array();
141
			foreach ($attributeNames as $attributeName) {
142
				$actualValues[$attributeName] = (string)$item[$attributeName];
143
			}
144
			$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...
145
		}
146
	}
147
148
149
	public function assertNumberOfNodes($selector, $expectedAmount) {
150
		$items = $this->cssParser()->getBySelector($selector);
151
		foreach ($items as $item) {
152
			$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...
153
		}
154
155
		$ct = sizeof($items);
156
		$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...
157
	}
158
159
160
	/* Collect an array of all the <ClassName>_<ID> search results, used for checking pagination */
161
	public function collateSearchResults() {
162
		$items = $this->cssParser()->getBySelector('div.searchResults .searchResult');
163
		$result = array();
164
		foreach ($items as $item) {
165
			$attr = $item->attributes()->id;
166
			array_push($result, $attr."");
167
		}
168
169
		return $result;
170
	}
171
172
}
173