summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/tests/phpunit/Utils/Validators/SemanticDataValidator.php
blob: 8eec37b2c1e32f864e0602dde51c00de163b18c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
<?php

namespace SMW\Tests\Utils\Validators;

use RuntimeException;
use SMW\DataValueFactory;
use SMW\DIProperty;
use SMW\SemanticData;
use SMWDataItem as DataItem;

/**
 *
 * @group SMW
 * @group SMWExtension
 *
 * @licence GNU GPL v2+
 * @since 1.9.1
 *
 * @author mwjames
 */
class SemanticDataValidator extends \PHPUnit_Framework_Assert {

	/**
	 * @var boolean
	 */
	private $strictModeForValueMatch = true;

	/**
	 * @param boolean $strictMode
	 */
	public function setStrictModeForValueMatch( $strictMode ) {
		$this->strictModeForValueMatch = (bool)$strictMode;
	}

	/**
	 * @since 1.9.1
	 *
	 * @param SemanticData $semanticData
	 */
	public function assertThatSemanticDataIsEmpty( SemanticData $semanticData ) {
		$this->assertTrue(
			$this->assertThatSemanticDataIsIndeedEmpty( $semanticData ),
			'Asserts that the SemanticData container is empty'
		);
	}

	/**
	 * @since 1.9.1
	 *
	 * @param SemanticData $semanticData
	 */
	public function assertThatSemanticDataIsNotEmpty( SemanticData $semanticData ) {
		$this->assertFalse(
			$this->assertThatSemanticDataIsIndeedEmpty( $semanticData ),
			'Asserts that the SemanticData container is not empty'
		);
	}

	/**
	 * @since 1.9.1
	 *
	 * @param array $expected
	 * @param SemanticData $semanticData
	 */
	public function assertThatCategoriesAreSet( array $expected, SemanticData $semanticData ) {

		$runCategoryInstanceAssert = false;

		foreach ( $semanticData->getProperties() as $property ) {

			if ( $property->getKey() === DIProperty::TYPE_CATEGORY ) {
				$runCategoryInstanceAssert = true;

				$this->assertThatPropertyValuesAreSet(
					$expected,
					$property,
					$semanticData->getPropertyValues( $property )
				);
			}

			if ( $property->getKey() === DIProperty::TYPE_SUBCATEGORY ) {
				$runCategoryInstanceAssert = true;

				$this->assertThatPropertyValuesAreSet(
					$expected,
					$property,
					$semanticData->getPropertyValues( $property )
				);
			}

		}

		// Issue #124 needs to be resolved first
		// $this->assertTrue( $runCategoryInstanceAssert, __METHOD__ );
	}

	/**
	 * @since 1.9.1
	 *
	 * @param integer $count
	 * @param SemanticData $semanticData
	 * @param string|null $msg
	 */
	public function assertThatSemanticDataHasPropertyCountOf( $count, SemanticData $semanticData, $msg = null ) {

		$prop = [];

		foreach ( $semanticData->getProperties() as $property ) {
			$prop[] = $property->getKey();
		}

		$msg = $msg === null ? "Failed asserting property count of {$count}" : $msg;
		$msg .= ' Counted properties include: ' . json_encode( $prop, JSON_PRETTY_PRINT );

		$this->assertCount( $count, $prop, $msg );
	}

	/**
	 * @since 2.1
	 *
	 * @param array $expected
	 * @param array $properties
	 */
	public function assertHasProperties( array $expected, array $properties ) {

		$expected = isset( $expected['properties'] ) ? $expected['properties'] : $expected;

		foreach ( $properties as $property ) {

			foreach ( $expected as $key => $expectedProperty ) {
				if ( $property->equals( $expectedProperty ) ) {
					unset( $expected[$key] );
				}
			}
		}

		$this->assertEmpty(
			$expected,
			'Failed asserting that properties array contains [ ' . $this->formatAsString( $expected ) .' ].'
		);
	}

	/**
	 * @since 1.9.1
	 *
	 * @param array $expected
	 * @param DIProperty $property
	 */
	public function assertThatPropertyHasCharacteristicsAs( array $expected, DIProperty $property ) {

		$runAssertThatPropertyHasCharacteristicsAs = false;

		if ( isset( $expected['property'] ) ) {
			$this->assertPropertyIsSameAs( $expected['property'], $property );
			$runAssertThatPropertyHasCharacteristicsAs = true;
		}

		if ( isset( $expected['propertyKey'] ) ) {
			$this->assertEquals(
				$expected['propertyKey'],
				$property->getKey(),
				__METHOD__ . " asserts property key for {$property->getLabel()}"
			);

			$runAssertThatPropertyHasCharacteristicsAs = true;
		}

		if ( isset( $expected['propertyLabel'] ) ) {
			$this->assertEquals(
				$expected['propertyLabel'],
				$property->getLabel(),
				__METHOD__ . " asserts property label for '{$property->getKey()}'"
			);

			$runAssertThatPropertyHasCharacteristicsAs = true;
		}

		if ( isset( $expected['propertyTypeId'] ) ) {
			$this->assertEquals(
				$expected['propertyTypeId'],
				$property->findPropertyTypeID(),
				__METHOD__ . " asserts property typeId for '{$property->getKey()}'"
			);

			$runAssertThatPropertyHasCharacteristicsAs = true;
		}

		$this->assertTrue( $runAssertThatPropertyHasCharacteristicsAs, __METHOD__ );

	}

	/**
	 * Assertion array should follow:
	 * 'propertyCount'  => int
	 * 'propertyLabels' => array() or 'propertyKeys' => array()
	 * 'propertyValues' => array()
	 *
	 * @since 1.9.1
	 *
	 * @param array $expected
	 * @param SemanticData $semanticData
	 */
	public function assertThatPropertiesAreSet( array $expected, SemanticData $semanticData, $message = '' ) {

		$runPropertiesAreSetAssert = false;
		$properties = $semanticData->getProperties();

		// Deprecated, use strictPropertyValueMatch
		if ( isset( $expected['strict-mode-valuematch'] ) ) {
			$this->setStrictModeForValueMatch( $expected['strict-mode-valuematch'] );
		}

		if ( isset( $expected['strictPropertyValueMatch'] ) ) {
			$this->setStrictModeForValueMatch( $expected['strictPropertyValueMatch'] );
		}

		if ( isset( $expected['propertyCount'] ) ) {
			$this->assertThatSemanticDataHasPropertyCountOf( $expected['propertyCount'], $semanticData, $message );
		}

		$report = [
			'@unresolved' => [],
			'@valueHint' => []
		];

		foreach ( $properties as $property ) {

			$this->assertInstanceOf( '\SMW\DIProperty', $property );

			if ( isset( $expected['properties'] ) ) {
				$this->assertContainsProperty( $expected['properties'], $property );
				$runPropertiesAreSetAssert = true;
			}

			if ( isset( $expected['property'] ) ) {
				$this->assertPropertyIsSameAs( $expected['property'], $property );
				$runPropertiesAreSetAssert = true;
			}

			if ( isset( $expected['propertyKeys'] ) ) {
				$this->assertContainsPropertyKeys( $expected['propertyKeys'], $property, $message );
				$runPropertiesAreSetAssert = true;
			}

			if ( isset( $expected['propertyLabels'] ) ) {
				$this->assertContainsPropertyLabels( $expected['propertyLabels'], $property );
				$runPropertiesAreSetAssert = true;
			}

			if ( isset( $expected['propertyValues'] ) ) {
				$pv = $semanticData->getPropertyValues( $property );
				$report[$property->getKey()] =  $this->formatAsString( $pv );

				$this->assertThatPropertyValuesAreSet(
					$expected,
					$property,
					$pv
				);

				$runPropertiesAreSetAssert = true;
			}
		}

		// Final ceck for values distributed over different properties
		if ( isset( $expected['propertyValues'] ) && !$this->strictModeForValueMatch ) {
			$report['@unresolved'] = $expected['propertyValues'];
			$report['@valueHint'] = $expected['@valueHint'];
			$this->assertEmpty(
				$expected['propertyValues'],
				"Unmatched values in {$message} for:\n" . json_encode( $report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES )
			);
		}

		// Issue #124 needs to be resolved first
		// $this->assertTrue( $runPropertiesAreSetAssert, __METHOD__ );

		return $runPropertiesAreSetAssert;
	}

	/**
	 * @since 1.9.1
	 *
	 * @param array $expected
	 * @param DIProperty $property,
	 * @param array $dataItems
	 */
	public function assertThatPropertyValuesAreSet( array &$expected, DIProperty $property, array $dataItems ) {

		$runPropertyValueAssert = false;

		if ( !isset( $expected['@valueHint'] ) ) {
			$expected['@valueHint'] = [];
		}

		foreach ( $dataItems as $dataItem ) {

			$dataValue = DataValueFactory::getInstance()->newDataValueByItem( $dataItem, $property );

			switch ( $dataValue->getDataItem()->getDIType() ) {
				case DataItem::TYPE_TIME:
					$runPropertyValueAssert = $this->assertContainsPropertyValues( $expected, $dataValue, 'getISO8601Date' );
					break;
				case DataItem::TYPE_NUMBER:
					$runPropertyValueAssert = $this->assertContainsPropertyValues( $expected, $dataValue, 'getNumber' );
					break;
				case DataItem::TYPE_BOOLEAN:
					$runPropertyValueAssert = $this->assertContainsPropertyValues( $expected, $dataValue, 'getBoolean' );
					break;
				default:
					$runPropertyValueAssert = $this->assertContainsPropertyValues( $expected, $dataValue, 'getWikiValue' );
					break;
			}
		}

		// Issue #124 needs to be resolved first
		// $this->assertTrue( $runPropertyValueAssert, __METHOD__ );

		return $runPropertyValueAssert;
	}

	private function assertThatSemanticDataIsIndeedEmpty( SemanticData $semanticData ) {

		$property = new DIProperty( '_SKEY' );

		foreach( $semanticData->getPropertyValues( $property ) as $dataItem ) {
			$semanticData->removePropertyObjectValue( $property, $dataItem );
		}

		return $semanticData->isEmpty();
	}

	private function assertContainsPropertyKeys( $keys, DIProperty $property, $message = null ) {

		$keys = str_replace( " ", "_", $keys );
		$message = ( $message === null ? 'Failed asserting' : "Failed asserting \"$message\"" );

		$this->assertContains(
			$property->getKey(),
			$keys,
			"{$message} property key: '{$property->getLabel()}' in ({$this->formatAsString( $keys )})"
		);
	}

	private function assertContainsPropertyLabels( $labels, DIProperty $property ) {
		$this->assertContains(
			$property->getLabel(),
			$labels,
			__METHOD__ . " asserts property label for '{$property->getKey()}' with ({$this->formatAsString( $labels )})"
		);
	}

	private function assertContainsProperty( array $properties, DIProperty $property ) {

		$runContainsPropertyAssert = false;

		foreach ( $properties as $expectedproperty ) {

			if ( $property->equals( $expectedproperty ) ) {
				$runContainsPropertyAssert = true;
				break;
			}
		}

		// Issue #124 needs to be resolved first
		// $this->assertTrue( $runContainsPropertyAssert, __METHOD__ );
	}

	private function assertPropertyIsSameAs( DIProperty $expectedproperty, DIProperty $property ) {
		$this->assertTrue(
			$property->equals( $expectedproperty ),
			__METHOD__ . ' asserts that two properties are equal'
		);
	}

	private function assertContainsPropertyValues( &$expected, $dataValue, $defaultFormatter, $formatterParameters = [] ) {

		if ( !isset( $expected['propertyValues'] ) ) {
			throw new RuntimeException( "Expected a 'propertyValues' array index" );
		}

		$formatter = [ $dataValue, $defaultFormatter ];
		$valueSerialization = $dataValue->getDataItem()->getSerialization();

		if ( isset( $expected['valueFormatter'] ) && is_callable( $expected['valueFormatter'] ) ) {
			$formatter = $expected['valueFormatter'];
			$formatterParameters = [ $dataValue ];
		}

		$value = call_user_func_array( $formatter, $formatterParameters );
		$expected['@valueHint'][] = $value;

		if ( $this->strictModeForValueMatch ) {

			$this->assertContains(
				$value,
				$expected['propertyValues'],
				__METHOD__ .
				" for '{$dataValue->getProperty()->getKey()}'" .
				" as '{$dataValue->getTypeID()}'" .
				" with ({$this->formatAsString( $expected['propertyValues'] )})"
			);

			return true;
		}

		// Be more lenient towards value comparison by just eliminating a matched pair
		foreach ( $expected['propertyValues'] as $key => $propertyValue ) {

			if ( is_bool( $value ) && $value === $propertyValue ) {
				unset( $expected['propertyValues'][$key] );
				continue;
			}

			if ( ( is_numeric( $value ) && is_numeric( $propertyValue ) )  && $value == $propertyValue ) {
				unset( $expected['propertyValues'][$key] );
				continue;
			}

			if ( strpos( $propertyValue, (string)$value ) !== false ) {
				unset( $expected['propertyValues'][$key] );
				continue;
			}

			if ( $propertyValue === $valueSerialization ) {
				unset( $expected['propertyValues'][$key] );
			}
		}

		return true;
	}

	private function formatAsString( $expected ) {
		return is_array( $expected ) ? implode( ', ', $expected ) : $expected;
	}

}