Completed
Push — 2.0-dev ( 5df328...6a45b1 )
by Michael
09:06
created

ClientTest::testAuthenticate()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 104
Code Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 104
rs 8.1463
cc 5
eloc 65
nc 9
nop 3

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
 * @copyright  Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
4
 * @license    GNU General Public License version 2 or later; see LICENSE
5
 */
6
7
namespace Joomla\OAuth1\Tests;
8
9
use Joomla\OAuth1\Client;
10
use Joomla\OAuth1\Tests\Stub\TestClient;
11
use Joomla\Registry\Registry;
12
use Joomla\Input\Input;
13
use Joomla\Test\WebInspector;
14
use Joomla\Test\TestHelper;
15
16
/**
17
 * Test class for \Joomla\OAuth1\Client.
18
 */
19
class ClientTest extends \PHPUnit_Framework_TestCase
20
{
21
	/**
22
	 * Input object for the Client object.
23
	 *
24
	 * @var  Input
25
	 */
26
	protected $input;
27
28
	/**
29
	 * Options for the Client object.
30
	 *
31
	 * @var  Registry
32
	 */
33
	protected $options;
34
35
	/**
36
	 * Mock HTTP object.
37
	 *
38
	 * @var  \Joomla\Http\Http
39
	 */
40
	protected $client;
41
42
	/**
43
	 * An instance of the object to test.
44
	 *
45
	 * @var  ClientInspector
46
	 */
47
	protected $object;
48
49
	/**
50
	 * The application object to send HTTP headers for redirects.
51
	 *
52
	 * @var  \Joomla\Application\AbstractWebApplication
53
	 */
54
	protected $application;
55
56
	/**
57
	 * Sample JSON string.
58
	 *
59
	 * @var  string
60
	 */
61
	protected $sampleString = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
62
63
	/**
64
	 * Sample JSON error message.
65
	 *
66
	 * @var  string
67
	 */
68
	protected $errorString = '{"errorCode":401, "message": "Generic error"}';
69
70
	/**
71
	 * Sets up the fixture, for example, opens a network connection.
72
	 * This method is called before a test is executed.
73
	 *
74
	 * @return  void
75
	 */
76
	protected function setUp()
0 ignored issues
show
Coding Style introduced by
setUp uses the super-global variable $_SERVER 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...
77
	{
78
		$_SERVER['HTTP_HOST'] = 'example.com';
79
		$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0';
80
		$_SERVER['REQUEST_URI'] = '/index.php';
81
		$_SERVER['SCRIPT_NAME'] = '/index.php';
82
83
		$key    = 'TEST_KEY';
84
		$secret = 'TEST_SECRET';
85
		$my_url = 'TEST_URL';
0 ignored issues
show
Unused Code introduced by
$my_url 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...
86
87
		$this->options     = new Registry;
88
		$this->client      = $this->getMock('Joomla\\Http\\Http', array('get', 'post', 'delete', 'put'));
0 ignored issues
show
Deprecated Code introduced by
The method PHPUnit_Framework_TestCase::getMock() has been deprecated with message: Method deprecated since Release 5.4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
89
		$this->input       = new Input;
90
		$this->application = new WebInspector;
91
92
		$mockSession = $this->getMock('Joomla\\Session\\SessionInterface');
0 ignored issues
show
Deprecated Code introduced by
The method PHPUnit_Framework_TestCase::getMock() has been deprecated with message: Method deprecated since Release 5.4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
93
94
		$this->application->setSession($mockSession);
95
96
		$this->options->set('consumer_key', $key);
97
		$this->options->set('consumer_secret', $secret);
98
		$this->object = new TestClient($this->application, $this->client, $this->input, $this->options);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Joomla\OAuth1\Tests...>input, $this->options) of type object<Joomla\OAuth1\Tests\Stub\TestClient> is incompatible with the declared type object<Joomla\OAuth1\Tests\ClientInspector> of property $object.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
99
	}
100
101
	/**
102
	 * Provides test data.
103
	 *
104
	 * @return  array
105
	 */
106
	public function seedAuthenticate()
107
	{
108
		// Token, fail and oauth version.
109
		return array(
110
			array(array('key' => 'valid', 'secret' => 'valid'), false, '1.0'),
111
			array(null, false, '1.0'),
112
			array(null, false, '1.0a'),
113
			array(null, true, '1.0a')
114
		);
115
	}
116
117
	/**
118
	 * Tests the constructor to ensure only arrays or ArrayAccess objects are allowed
119
	 *
120
	 * @expectedException  \InvalidArgumentException
121
	 */
122
	public function testConstructorDisallowsNonArrayObjects()
123
	{
124
		new TestClient($this->application, $this->client, $this->input, new \stdClass);
0 ignored issues
show
Documentation introduced by
new \stdClass() is of type object<stdClass>, but the function expects a array|object<ArrayAccess>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
125
	}
126
127
	/**
128
	 * Tests the authenticate method
129
	 *
130
	 * @param   array    $token    The passed token.
131
	 * @param   boolean  $fail     Mark if should fail or not.
132
	 * @param   string   $version  Specify oauth version 1.0 or 1.0a.
133
	 *
134
	 * @dataProvider seedAuthenticate
135
	 */
136
	public function testAuthenticate($token, $fail, $version)
137
	{
138
		// Already got some credentials stored?
139
		if (!is_null($token))
140
		{
141
			$this->object->setToken($token);
142
			$result = $this->object->authenticate();
143
			$this->assertEquals($result, $token);
144
		}
145
		else
146
		{
147
			$this->object->setOption('requestTokenURL', 'https://example.com/request_token');
148
			$this->object->setOption('authoriseURL', 'https://example.com/authorize');
149
			$this->object->setOption('accessTokenURL', 'https://example.com/access_token');
150
151
			// Request token.
152
			$returnData = new \stdClass;
153
			$returnData->code = 200;
154
			$returnData->body = 'oauth_token=token&oauth_token_secret=secret&oauth_callback_confirmed=true';
155
156
			$this->client->expects($this->at(0))
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Joomla\Http\Http>.

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
				->method('post')
158
				->with($this->object->getOption('requestTokenURL'))
159
				->willReturn($returnData);
160
161
			$input = TestHelper::getValue($this->object, 'input');
162
			$input->set('oauth_verifier', null);
163
			TestHelper::setValue($this->object, 'input', $input);
164
165
			if (strcmp($version, '1.0a') === 0)
166
			{
167
				$this->object->setOption('callback', 'TEST_URL');
168
			}
169
170
			$this->object->authenticate();
171
172
			$token = $this->object->getToken();
173
			$this->assertEquals($token['key'], 'token');
174
			$this->assertEquals($token['secret'], 'secret');
175
176
			// Access token.
177
			$input = TestHelper::getValue($this->object, 'input');
178
179
			if (strcmp($version, '1.0a') === 0)
180
			{
181
				TestHelper::setValue($this->object, 'version', $version);
182
				$data = array('oauth_verifier' => 'verifier', 'oauth_token' => 'token');
183
			}
184
			else
185
			{
186
				TestHelper::setValue($this->object, 'version', $version);
187
				$data = array('oauth_token' => 'token');
188
			}
189
190
			TestHelper::setValue($input, 'data', $data);
191
192
			// Get mock session
193
			$mockSession = $this->getMock('Joomla\\Session\\SessionInterface');
0 ignored issues
show
Deprecated Code introduced by
The method PHPUnit_Framework_TestCase::getMock() has been deprecated with message: Method deprecated since Release 5.4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
194
195
			if ($fail)
196
			{
197
				$mockSession->expects($this->at(0))
198
					->method('get')
199
					->with('oauth_token.key')
200
					->willReturn('bad');
201
202
				$mockSession->expects($this->at(1))
203
					->method('get')
204
					->with('oauth_token.secret')
205
					->willReturn('session');
206
207
				$this->application->setSession($mockSession);
208
209
				$this->setExpectedException('DomainException');
0 ignored issues
show
Deprecated Code introduced by
The method PHPUnit_Framework_TestCase::setExpectedException() has been deprecated with message: Method deprecated since Release 5.2.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
210
				$result = $this->object->authenticate();
0 ignored issues
show
Unused Code introduced by
$result 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
			$mockSession->expects($this->at(0))
214
				->method('get')
215
				->with('oauth_token.key')
216
				->willReturn('token');
217
218
			$mockSession->expects($this->at(1))
219
				->method('get')
220
				->with('oauth_token.secret')
221
				->willReturn('secret');
222
223
			$this->application->setSession($mockSession);
224
225
			$returnData = new \stdClass;
226
			$returnData->code = 200;
227
			$returnData->body = 'oauth_token=token_key&oauth_token_secret=token_secret';
228
229
			$this->client->expects($this->at(0))
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Joomla\Http\Http>.

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...
230
				->method('post')
231
				->with($this->object->getOption('accessTokenURL'))
232
				->willReturn($returnData);
233
234
			$result = $this->object->authenticate();
235
236
			$this->assertEquals($result['key'], 'token_key');
237
			$this->assertEquals($result['secret'], 'token_secret');
238
		}
239
	}
240
241
	/**
242
	 * Tests the _generateRequestToken method - failure
243
	 *
244
	 * @expectedException  \DomainException
245
	 */
246
	public function testGenerateRequestTokenFailure()
247
	{
248
		$this->object->setOption('requestTokenURL', 'https://example.com/request_token');
249
250
		$returnData = new \stdClass;
251
		$returnData->code = 200;
252
		$returnData->body = 'oauth_token=token&oauth_token_secret=secret&oauth_callback_confirmed=false';
253
254
		$this->client->expects($this->at(0))
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Joomla\Http\Http>.

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...
255
			->method('post')
256
			->with($this->object->getOption('requestTokenURL'))
257
			->willReturn($returnData);
258
259
		TestHelper::invoke($this->object, 'generateRequestToken');
260
	}
261
262
	/**
263
	* Provides test data.
264
	*
265
	* @return  array
266
	*/
267
	public function seedOauthRequest()
268
	{
269
		// Method
270
		return array(
271
			array('GET'),
272
			array('PUT'),
273
			array('DELETE')
274
		);
275
	}
276
277
	/**
278
	 * Tests the oauthRequest method
279
	 *
280
	 * @param   string  $method  The request method.
281
	 *
282
	 * @dataProvider seedOauthRequest
283
	 */
284
	public function testOauthRequest($method)
285
	{
286
		$returnData = new \stdClass;
287
		$returnData->code = 200;
288
		$returnData->body = $this->sampleString;
289
290
		if (strcmp($method, 'PUT') === 0)
291
		{
292
			$data = array('key1' => 'value1', 'key2' => 'value2');
293
			$this->client->expects($this->at(0))
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Joomla\Http\Http>.

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...
294
				->method($method, $data)
295
				->with('www.example.com')
296
				->willReturn($returnData);
297
298
			$this->assertSame(
299
				$returnData,
300
				$this->object->oauthRequest(
301
					'www.example.com',
302
					$method,
303
					array('oauth_token' => '1235'),
304
					$data,
305
					array('Content-Type' => 'multipart/form-data')
306
				)
307
			);
308
		}
309
		else
310
		{
311
			$this->client->expects($this->at(0))
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Joomla\Http\Http>.

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...
312
				->method($method)
313
				->with('www.example.com')
314
				->willReturn($returnData);
315
316
			$this->assertSame(
317
				$returnData,
318
				$this->object->oauthRequest(
319
					'www.example.com',
320
					$method,
321
					array('oauth_token' => '1235'),
322
					array(),
323
					array('Content-Type' => 'multipart/form-data')
324
				)
325
			);
326
		}
327
	}
328
329
	/**
330
	 * Tests the safeEncode
331
	 *
332
	 * @return  void
333
	 */
334
	public function testSafeEncodeEmpty()
335
	{
336
		$this->assertEmpty(
337
			$this->object->safeEncode(null)
338
		);
339
	}
340
}
341