Completed
Push — master ( 951284...b5c57e )
by
unknown
06:36 queued 11s
created

repo/tests/phpunit/includes/Api/GetClaimsTest.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Wikibase\Repo\Tests\Api;
4
5
use ApiTestCase;
6
use ApiUsageException;
7
use DataValues\Serializers\DataValueSerializer;
8
use DataValues\StringValue;
9
use Wikibase\DataModel\Entity\EntityDocument;
10
use Wikibase\DataModel\Entity\Item;
11
use Wikibase\DataModel\Entity\Property;
12
use Wikibase\DataModel\Entity\PropertyId;
13
use Wikibase\DataModel\SerializerFactory;
14
use Wikibase\DataModel\Snak\PropertyNoValueSnak;
15
use Wikibase\DataModel\Snak\PropertySomeValueSnak;
16
use Wikibase\DataModel\Snak\PropertyValueSnak;
17
use Wikibase\DataModel\Statement\Statement;
18
use Wikibase\DataModel\Statement\StatementList;
19
use Wikibase\DataModel\Statement\StatementListProvider;
20
use Wikibase\Repo\StatementRankSerializer;
21
use Wikibase\Repo\WikibaseRepo;
22
use Wikimedia\TestingAccessWrapper;
23
24
/**
25
 * @covers \Wikibase\Repo\Api\GetClaims
26
 *
27
 * @group API
28
 * @group Database
29
 * @group Wikibase
30
 * @group WikibaseAPI
31
 *
32
 * @group medium
33
 *
34
 * @license GPL-2.0-or-later
35
 * @author Jeroen De Dauw < [email protected] >
36
 * @author Katie Filbert < [email protected] >
37
 * @author Addshore
38
 */
39
class GetClaimsTest extends ApiTestCase {
40
41
	/**
42
	 * @var SerializerFactory
43
	 */
44
	private $serializerFactory;
45
46
	protected function setUp(): void {
47
		parent::setUp();
48
49
		$this->serializerFactory = new SerializerFactory(
50
			new DataValueSerializer(),
51
			SerializerFactory::OPTION_DEFAULT
52
		);
53
	}
54
55
	private function save( EntityDocument $entity ) {
56
		$flags = $entity->getId() ? EDIT_UPDATE : EDIT_NEW;
57
58
		$store = WikibaseRepo::getDefaultInstance()->getEntityStore();
59
60
		$rev = $store->saveEntity( $entity, '', $this->getTestUser()->getUser(), $flags );
61
62
		$entity->setId( $rev->getEntity()->getId() );
63
	}
64
65
	private function addStatements( Item $item, PropertyId $propertyId ) {
66
		if ( !$item->getId() ) {
67
			$this->save( $item );
68
		}
69
70
		/** @var Statement[] $statements */
71
		$statements[0] = new Statement( new PropertyNoValueSnak( $propertyId ) );
0 ignored issues
show
Coding Style Comprehensibility introduced by
$statements was never initialized. Although not strictly required by PHP, it is generally a good practice to add $statements = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
72
		$statements[1] = new Statement( new PropertyNoValueSnak( $propertyId ) );
73
		$statements[2] = new Statement( new PropertySomeValueSnak( $propertyId ) );
74
		$statements[3] = new Statement( new PropertyValueSnak( $propertyId, new StringValue( 'o_O' ) ) );
75
76
		foreach ( $statements as $key => $statement ) {
77
			$statement->setGuid( $item->getId()->getSerialization() . '$D8404CDA-56A1-4334-AF13-A3290BCD9CL' . $key );
78
			$item->getStatements()->addStatement( $statement );
79
		}
80
	}
81
82
	/**
83
	 * @return EntityDocument[]
84
	 */
85
	private function getNewEntities() {
86
		$property = Property::newFromType( 'string' );
87
		$this->save( $property );
88
89
		$propertyId = $property->getId();
90
91
		$item = new Item();
92
		$this->addStatements( $item, $propertyId );
93
		$this->save( $item );
94
95
		return [
96
			$property,
97
			$item,
98
		];
99
	}
100
101
	public function validRequestProvider() {
102
		$entities = $this->getNewEntities();
103
104
		$argLists = [];
105
106
		foreach ( $entities as $entity ) {
107
			$idSerialization = $entity->getId()->getSerialization();
108
			/** @var StatementListProvider $entity */
109
			$statements = $entity->getStatements();
110
111
			$params = [
112
				'action' => 'wbgetclaims',
113
				'entity' => $idSerialization,
114
			];
115
116
			$argLists[] = [ $params, $statements->toArray() ];
117
118
			foreach ( $statements->toArray() as $statement ) {
119
				$params = [
120
					'action' => 'wbgetclaims',
121
					'claim' => $statement->getGuid(),
122
				];
123
				$argLists[] = [ $params, [ $statement ] ];
124
			}
125
126
			foreach ( [ Statement::RANK_DEPRECATED, Statement::RANK_NORMAL, Statement::RANK_PREFERRED ] as $rank ) {
127
				$statementRankSerializer = new StatementRankSerializer();
128
				$params = [
129
					'action' => 'wbgetclaims',
130
					'entity' => $idSerialization,
131
					'rank' => $statementRankSerializer->serialize( $rank ),
132
				];
133
134
				$statementsByRank = $statements->getByRank( $rank )->toArray();
135
				$argLists[] = [ $params, $statementsByRank ];
136
			}
137
		}
138
139
		return $argLists;
140
	}
141
142
	public function testValidRequests() {
143
		foreach ( $this->validRequestProvider() as $argList ) {
144
			list( $params, $statements ) = $argList;
145
146
			$this->doTestValidRequest( $params, $statements );
147
		}
148
	}
149
150
	/**
151
	 * @param string[] $params
152
	 * @param Statement[] $statements
153
	 */
154
	public function doTestValidRequest( array $params, array $statements ) {
155
		$statements = new StatementList( $statements );
156
157
		$serializer = $this->serializerFactory->newStatementListSerializer();
158
		$expected = $serializer->serialize( $statements );
159
160
		list( $resultArray, ) = $this->doApiRequest( $params );
161
162
		$this->assertIsArray( $resultArray, 'top level element is an array' );
163
		$this->assertArrayHasKey( 'claims', $resultArray, 'top level element has a claims key' );
164
165
		// Assert that value mainsnaks have a datatype added
166
		foreach ( $resultArray['claims'] as &$claimsByProperty ) {
167
			foreach ( $claimsByProperty as &$claimArray ) {
168
				$this->assertArrayHasKey( 'datatype', $claimArray['mainsnak'] );
169
				unset( $claimArray['mainsnak']['datatype'] );
170
			}
171
		}
172
173
		$this->assertEquals( $expected, $resultArray['claims'] );
174
	}
175
176
	/**
177
	 * @dataProvider invalidClaimProvider
178
	 */
179
	public function testGetInvalidClaims( $guid ) {
180
		$params = [
181
			'action' => 'wbgetclaims',
182
			'claim' => $guid
183
		];
184
185
		try {
186
			$this->doApiRequest( $params );
187
			$this->fail( 'Invalid claim guid did not throw an error' );
188
		} catch ( ApiUsageException $e ) {
189
			$msg = TestingAccessWrapper::newFromObject( $e )->getApiMessage();
190
			$this->assertEquals( 'invalid-guid', $msg->getApiCode(), 'Invalid claim guid raised correct error' );
191
		}
192
	}
193
194
	public function invalidClaimProvider() {
195
		return [
196
			[ 'xyz' ],
197
			[ 'x$y$z' ]
198
		];
199
	}
200
201
	/**
202
	 * @dataProvider getInvalidIdsProvider
203
	 */
204
	public function testGetInvalidIds( $entity, $property ) {
205
		if ( !$entity ) {
206
			$item = new Item();
207
			$this->addStatements( $item, new PropertyId( 'P13' ) );
208
209
			$this->save( $item );
210
			$entity = $item->getId()->getSerialization();
211
		}
212
213
		$params = [
214
			'action' => 'wbgetclaims',
215
			'entity' => $entity,
216
			'property' => $property,
217
		];
218
219
		try {
220
			$this->doApiRequest( $params );
221
			$this->fail( 'Invalid entity id did not throw an error' );
222
		} catch ( ApiUsageException $e ) {
223
			$msg = TestingAccessWrapper::newFromObject( $e )->getApiMessage();
224
			$this->assertEquals( 'param-invalid', $msg->getApiCode(), 'Invalid entity id raised correct error' );
225
		}
226
	}
227
228
	public function getInvalidIdsProvider() {
229
		return [
230
			[ null, 'nopeNopeNope' ],
231
			[ 'whatTheFuck', 'P42' ],
232
		];
233
	}
234
235
}
236