ElasticsearchBaseTest::setUp()   C
last analyzed

Complexity

Conditions 8
Paths 360

Size

Total Lines 68
Code Lines 35

Duplication

Lines 6
Ratio 8.82 %

Code Coverage

Tests 34
CRAP Score 8.4425
Metric Value
dl 6
loc 68
ccs 34
cts 42
cp 0.8095
rs 5.3008
cc 8
eloc 35
nc 360
nop 0
crap 8.4425

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
use SilverStripe\Elastica\ElasticaUtil;
3
use SilverStripe\Elastica\ReindexTask;
4
use SilverStripe\Elastica\ElasticaService;
5
6
class ElasticsearchBaseTest extends SapphireTest {
7
8
	public static $ignoreFixtureFileFor = array();
9
10
	protected $extraDataObjects = array(
11
		'SearchableTestPage','FlickrPhotoTO','FlickrAuthorTO','FlickrSetTO','FlickrTagTO',
12
		'SearchableTestFatherPage','SearchableTestGrandFatherPage','AutoCompleteOption'
13
	);
14
15
16
	public function setUpOnce() {
17
		ElasticaUtil::setPrinterOutput(false);
18
19
		// add Searchable extension where appropriate
20
		FlickrSetTO::add_extension('SilverStripe\Elastica\Searchable');
21
		FlickrPhotoTO::add_extension('SilverStripe\Elastica\Searchable');
22
		FlickrTagTO::add_extension('SilverStripe\Elastica\Searchable');
23
		FlickrAuthorTO::add_extension('SilverStripe\Elastica\Searchable');
24
		SearchableTestPage::add_extension('SilverStripe\Elastica\Searchable');
25
26
27
		$config = Config::inst();
28
		$config->remove('Injector', 'SilverStripe\Elastica\ElasticaService');
29
		$constructor = array('constructor' => array('%$Elastica\Client', 'elastica_ss_module_test'));
30
		$config->update('Injector', 'SilverStripe\Elastica\ElasticaService', $constructor);
31
		parent::setUpOnce();
32
	}
33
34
35 10
	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...
36 10
		// no need to index here as it's done when fixtures are loaded during setup method
37
		$cache = SS_Cache::factory('elasticsearch');
38 10
		$cache->clean(Zend_Cache::CLEANING_MODE_ALL);
39 10
		SS_Cache::set_cache_lifetime('elasticsearch', 3600, 1000);
40 10
41 10
		// this needs to be called in order to create the list of searchable
42
		// classes and fields that are available.  Simulates part of a build
43
		$classes = array('SearchableTestPage','SiteTree','Page','FlickrPhotoTO','FlickrSetTO',
44
			'FlickrTagTO', 'FlickrAuthorTO');
45 10
		$this->requireDefaultRecordsFrom = $classes;
46 10
47 10
		// clear the index
48
		$this->service = Injector::inst()->create('SilverStripe\Elastica\ElasticaService');
49 10
		$this->service->setTestMode(true);
50
51
		$elasticException = false;
52 10
53 10
		try {
54
			// A previous test may have deleted the index and then failed, so check for this
55 10
			if (!$this->service->getIndex()->exists()) {
56
				$this->service->getIndex()->create();
57 10
			}
58
			$this->service->reset();
59
			// FIXME - use request getVar instead?
60
			$_GET['progress'] = 20;
61 10
			// load fixtures
62 1
63
			$orig_fixture_file = static::$fixture_file;
64 1
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 10
				$pattern = '/'.$testPattern.'/';
67 10
				if (preg_match($pattern, $this->getName())) {
68 10
					static::$fixture_file = null;
69
				}
70 10
			}
71
72
		} catch (Exception $e) {
73 10
			$elasticException = true;
74 10
		}
75
76 10
		// this needs to run otherwise nested injector errors show up
77
		parent::setUp();
78
79
		if ($elasticException) {
80
			$this->fail('T1 An error has occurred trying to contact Elasticsearch server');
0 ignored issues
show
Bug introduced by
The method fail() does not seem to exist on object<ElasticsearchBaseTest>.

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...
81 10
		}
82
83 10
		try {
84 10
			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...
85
86
			$this->publishSiteTree();
87
			$this->service->reset();
88 10
89
			// index loaded fixtures
90
			$task = new ReindexTask($this->service);
91
			// null request is fine as no parameters used
92 10
93
			$task->run(null);
94 10
		} catch (Exception $e) {
95
			$elasticException = true;
96
		}
97
98
		if ($elasticException) {
99 10
			$this->fail('T2 An error has occurred trying to contact Elasticsearch server');
0 ignored issues
show
Bug introduced by
The method fail() does not seem to exist on object<ElasticsearchBaseTest>.

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...
100
		}
101 10
102 10
	}
103
104
105 10
	protected function devBuild() {
106
		$task = new \BuildTask();
107
		// null request is fine as no parameters used
108 10
		$task->run(null);
109 10
	}
110
111
112
	private function publishSiteTree() {
113
		foreach (SiteTree::get()->getIterator() as $page) {
114 10
			// temporarily disable Elasticsearch indexing, it will be done in a batch
115
			$page->IndexingOff = true;
116
			$page->publish('Stage','Live');
117
		}
118 10
	}
119
120
121 View Code Duplication
	public function generateAssertionsFromArray($toAssert) {
122
		echo '$expected = array('."\n";
123
		foreach ($toAssert as $key => $value) {
124
			$escValue = str_replace("'", '\\\'', $value);
125
			echo "'$key' => '$escValue',\n";
126
		}
127
		echo ");\n";
128 10
		echo '$this->assertEquals($expected, $somevar);'."\n";
129 10
	}
130
131 10
132 10 View Code Duplication
	public function generateAssertionsFromArray1D($toAssert) {
133 10
		echo '$expected = array('."\n";
134 10
		foreach ($toAssert as $key => $value) {
135
			$escValue = str_replace("'", '\\\'', $value);
136
			echo "'$escValue',";
137
		}
138
		echo ");\n";
139
		echo '$this->assertEquals($expected, $somevar);'."\n";
140
	}
141
142
143
	public function generateAssertionsFromArrayRecurse($toAssert) {
144
		echo '$expected = ';
145
			$this->recurseArrayAssertion($toAssert,1, 'FIXME');
146
		echo '$this->assertEquals($expected, $somevar);'."\n";
147
	}
148
149
150
	private function recurseArrayAssertion($toAssert, $depth, $parentKey) {
151
		$prefix = str_repeat("\t",$depth);
152
		echo "\t{$prefix}'$parentKey' => array(\n";
153
		$ctr = 0;
154
		$len = sizeof(array_keys($toAssert));
155
		foreach ($toAssert as $key => $value) {
156
			if (is_array($value)) {
157
				$this->recurseArrayAssertion($value, $depth+1, $key);
158
			} else {
159
				$escValue = str_replace("'", '\\\'', $value);
160
				$comma = ',';
161
				if ($ctr == $len-1) {
162
					$comma = '';
163
				}
164
				echo "\t\t$prefix'$key' => '$escValue'$comma\n";
165
			}
166
167
			$ctr++;
168
169
		}
170
		echo "\t$prefix),\n";
171
	}
172
173
174
	/*
175
	Helper methods for testing CMS fields
176
	 */
177
	public function checkTabExists($fields, $tabName) {
178
		$tab = $fields->findOrMakeTab("Root.{$tabName}");
179
		$actualTabName = $tab->getName();
180
		$splits = explode('.', $tabName);
181
		$size = sizeof($splits);
182
		$nameToCheck = end($splits);
183
		$this->assertEquals($actualTabName, $nameToCheck);
184
		if ($size == 1) {
185
			$this->assertEquals("Root_${tabName}", $tab->id());
186
		} else {
187
			$expected = "Root_{$splits[0]}_set_{$splits[1]}";
188
			$this->assertEquals($expected, $tab->id());
189
		}
190
191
		return $tab;
192
	}
193
194 1
195
	public function checkFieldExists($tab,$fieldName) {
196
		$fields = $tab->Fields();
0 ignored issues
show
Unused Code introduced by
$fields 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...
197
		$field = $tab->fieldByName($fieldName);
198
		$this->assertTrue($field != null);
199 1
		return $field;
200
	}
201
202
203
	/**
204
	 * From https://jtreminio.com/2013/03/unit-testing-tutorial-part-3-testing-protected-private-methods-coverage-reports-and-crap/
205
	 * Call protected/private method of a class.
206
	 *
207
	 * @param object &$object    Instantiated object that we will run method on.
208
	 * @param string $methodName Method name to call
209
	 * @param array  $parameters Array of parameters to pass into method.
210
	 *
211
	 * @return mixed Method return.
212
	 */
213
	public function invokeMethod(&$object, $methodName, array $parameters = array())
214
	{
215
	    $reflection = new \ReflectionClass(get_class($object));
216
	    $method = $reflection->getMethod($methodName);
217
	    $method->setAccessible(true);
218
219
	    return $method->invokeArgs($object, $parameters);
220
	}
221
222
223 View Code Duplication
	public function checkNumberOfIndexedDocuments($expectedAmount) {
224
		$index = $this->service->getIndex();
225
		$status = $index->getStatus()->getData();
226
227
		$numberDocsInIndex = -1; // flag value for not yet indexed
0 ignored issues
show
Unused Code introduced by
$numberDocsInIndex 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...
228
229
		if (isset($status['indices']['elastica_ss_module_test_en_us']['docs'])) {
230
			$numberDocsInIndex = $status['indices']['elastica_ss_module_test_en_us']['docs']['num_docs'];
231
		} else {
232
			$numberDocsInIndex = 0;
233
		}
234
235
		$this->assertEquals($expectedAmount,$numberDocsInIndex);
236
	}
237
238
	/*
239
	Get the number of documents in an index.  It is assumed the index exists, if not the test will fail
240
	 */
241 View Code Duplication
	public function getNumberOfIndexedDocuments() {
242
		$index = $this->service->getIndex();
243
		$status = $index->getStatus()->getData();
244
245
		$numberDocsInIndex = -1; // flag value for not yet indexed
246
		if (isset($status['indices']['elastica_ss_module_test_en_us']['docs'])) {
247
			$numberDocsInIndex = $status['indices']['elastica_ss_module_test_en_us']['docs']['num_docs'];
248
		}
249
250
		$this->assertGreaterThan(-1, $numberDocsInIndex);
251
		return $numberDocsInIndex;
252
	}
253
}
254