Codebird library added

This commit is contained in:
Michael 2019-08-04 08:21:18 +00:00
parent f2c05b0222
commit 2e776253e0
38 changed files with 10983 additions and 12 deletions

View file

@ -0,0 +1,16 @@
The following methods are not covered by unit tests yet:
_getMultipartRequestFromParams
_checkForFiles
_buildMultipart
_buildBinaryBody
_callApi
_callApiCurl
_callApiNoCurl
_callApiPreparationsGet
_callApiPreparationsPost
_callApiPreparations
_callApiStreaming
_deliverStreamingMessage

View file

@ -0,0 +1,204 @@
<?php
namespace Codebird;
require_once ('test/codebirdt.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Codebird testing class with mock data source
*
* @package codebird-test
*/
class CodebirdM extends CodebirdT
{
/**
* Stores the request data
*/
protected $_requests = [];
/**
* Mock API replies
*/
protected static $_mock_replies = [
'default' => [
'httpstatus' => 404,
'reply' => "HTTP/1.1 404 Not Found\r\ncontent-length: 68\r\ncontent-type: application/json;charset=utf-8\r\ndate: Sun, 06 Dec 2015 14:43:28 GMT\r\nserver: tsa_b\r\nset-cookie: guest_id=v1%3A144941300885288055; Domain=.twitter.com; Path=/; Expires=Tue, 05-Dec-2017 14:43:28 UTC\r\nstrict-transport-security: max-age=631138519\r\nx-connection-hash: 12218aef9e9757609afb08e661fa3b9b\r\nx-response-time: 2\r\n\r\n{\"errors\":[{\"message\":\"Sorry, that page does not exist\",\"code\":34}]}"
],
'proxy1' => [
'httpstatus' => 404,
'reply' => "HTTP/1.1 200 Connection Established\r\n\r\nHTTP/1.1 404 Not Found\r\ncontent-length: 68\r\ncontent-type: application/json;charset=utf-8\r\ndate: Sun, 06 Dec 2015 14:43:28 GMT\r\nserver: tsa_b\r\nset-cookie: guest_id=v1%3A144941300885288055; Domain=.twitter.com; Path=/; Expires=Tue, 05-Dec-2017 14:43:28 UTC\r\nstrict-transport-security: max-age=631138519\r\nx-connection-hash: 12218aef9e9757609afb08e661fa3b9b\r\nx-response-time: 2\r\n\r\n{\"errors\":[{\"message\":\"Sorry, that page does not exist\",\"code\":34}]}"
],
'GET http://www.example.org/found.txt' => [
'httpstatus' => 200,
'reply' => "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nA test file."
],
'GET https://api.twitter.com/1.1/users/show.json?screen_name=TwitterAPI' => [
'httpstatus' => 200,
'reply' => "HTTP/1.1 200 OK\r\ncache-control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0\r\ncontent-disposition: attachment; filename=json.json\r\ncontent-length: 2801\r\ncontent-type: application/json;charset=utf-8\r\ndate: Sun, 06 Dec 2015 14:55:46 GMT\r\nexpires: Tue, 31 Mar 1981 05:00:00 GMT\r\nlast-modified: Sun, 06 Dec 2015 14:55:46 GMT\r\npragma: no-cache\r\nserver: tsa_b\r\nset-cookie: lang=en-gb; Path=/\r\nset-cookie: guest_id=v1%3A144941374684866365; Domain=.twitter.com; Path=/; Expires=Tue, 05-Dec-2017 14:55:46 UTC\r\nstatus: 200 OK\r\nstrict-transport-security: max-age=631138519\r\nx-access-level: read-write-directmessages\r\nx-connection-hash: 1906b689730b92318bccf65b496f74d0\r\nx-content-type-options: nosniff\r\nx-frame-options: SAMEORIGIN\r\nx-rate-limit-limit: 181\r\nx-rate-limit-remaining: 177\r\nx-rate-limit-reset: 1449414513\r\nx-response-time: 44\r\nx-transaction: 663cc05c64857ba0\r\nx-twitter-response-tags: BouncerCompliant\r\nx-xss-protection: 1; mode=block\r\n\r\n{\"id\":6253282,\"id_str\":\"6253282\",\"name\":\"Twitter API\",\"screen_name\":\"twitterapi\",\"location\":\"San Francisco, CA\",\"profile_location\":null,\"description\":\"The Real Twitter API. I tweet about API changes, service issues and happily answer questions about Twitter and our API. Don't get an answer? It's on my website.\",\"url\":\"http:\/\/t.co\/78pYTvWfJd\",\"entities\":{\"url\":{\"urls\":[{\"url\":\"http:\/\/t.co\/78pYTvWfJd\",\"expanded_url\":\"http:\/\/dev.twitter.com\",\"display_url\":\"dev.twitter.com\",\"indices\":[0,22]}]},\"description\":{\"urls\":[]}},\"protected\":false,\"followers_count\":4993679,\"friends_count\":48,\"listed_count\":13001,\"created_at\":\"Wed May 23 06:01:13 +0000 2007\",\"favourites_count\":27,\"utc_offset\":-28800,\"time_zone\":\"Pacific Time (US & Canada)\",\"geo_enabled\":true,\"verified\":true,\"statuses_count\":3553,\"lang\":\"en\",\"status\":{\"created_at\":\"Tue Nov 24 08:56:07 +0000 2015\",\"id\":669077021138493440,\"id_str\":\"669077021138493440\",\"text\":\"Additional 64-bit entity ID migration coming in Feb 2016 https:\/\/t.co\/eQIGvw1rsJ\",\"source\":\"\u003ca href=\\\"https:\/\/about.twitter.com\/products\/tweetdeck\\\" rel=\\\"nofollow\\\"\u003eTweetDeck\u003c\/a\u003e\",\"truncated\":false,\"in_reply_to_status_id\":null,\"in_reply_to_status_id_str\":null,\"in_reply_to_user_id\":null,\"in_reply_to_user_id_str\":null,\"in_reply_to_screen_name\":null,\"geo\":null,\"coordinates\":null,\"place\":null,\"contributors\":null,\"retweet_count\":67,\"favorite_count\":79,\"entities\":{\"hashtags\":[],\"symbols\":[],\"user_mentions\":[],\"urls\":[{\"url\":\"https:\/\/t.co\/eQIGvw1rsJ\",\"expanded_url\":\"https:\/\/twittercommunity.com\/t\/migration-of-twitter-core-entities-to-64-bit-ids\/56881\",\"display_url\":\"twittercommunity.com\/t\/migration-of\u2026\",\"indices\":[57,80]}]},\"favorited\":false,\"retweeted\":false,\"possibly_sensitive\":false,\"lang\":\"en\"},\"contributors_enabled\":false,\"is_translator\":false,\"is_translation_enabled\":false,\"profile_background_color\":\"C0DEED\",\"profile_background_image_url\":\"http:\/\/pbs.twimg.com\/profile_background_images\/656927849\/miyt9dpjz77sc0w3d4vj.png\",\"profile_background_image_url_https\":\"https:\/\/pbs.twimg.com\/profile_background_images\/656927849\/miyt9dpjz77sc0w3d4vj.png\",\"profile_background_tile\":true,\"profile_image_url\":\"http:\/\/pbs.twimg.com\/profile_images\/2284174872\/7df3h38zabcvjylnyfe3_normal.png\",\"profile_image_url_https\":\"https:\/\/pbs.twimg.com\/profile_images\/2284174872\/7df3h38zabcvjylnyfe3_normal.png\",\"profile_banner_url\":\"https:\/\/pbs.twimg.com\/profile_banners\/6253282\/1431474710\",\"profile_link_color\":\"0084B4\",\"profile_sidebar_border_color\":\"C0DEED\",\"profile_sidebar_fill_color\":\"DDEEF6\",\"profile_text_color\":\"333333\",\"profile_use_background_image\":true,\"has_extended_profile\":false,\"default_profile\":false,\"default_profile_image\":false,\"following\":true,\"follow_request_sent\":false,\"notifications\":false}"
],
'POST https://api.twitter.com/oauth2/token' => [
'httpstatus' => 200,
'reply' => "HTTP/1.1 200 OK\r\ncache-control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0\r\ncontent-disposition: attachment; filename=json.json\r\ncontent-length: 52\r\ncontent-type: application/json;charset=utf-8\r\ndate: Sun, 06 Dec 2015 15:53:02 GMT\r\nexpires: Tue, 31 Mar 1981 05:00:00 GMT\r\nlast-modified: Sun, 06 Dec 2015 15:53:01 GMT\r\nml: S\r\npragma: no-cache\r\nserver: tsa_b\r\nset-cookie: guest_id=v1%3A144941718194388038; Domain=.twitter.com; Path=/; Expires=Tue, 05-Dec-2017 15:53:02 UTC\r\nstatus: 200 OK\r\nstrict-transport-security: max-age=631138519\r\nx-connection-hash: 97f4d4e6a33433b477510d8c58a0b026\r\nx-content-type-options: nosniff\r\nx-frame-options: DENY\r\nx-response-time: 87\r\nx-transaction: 6a0e5e8144d7e6df\r\nx-tsa-request-body-time: 164\r\nx-twitter-response-tags: BouncerCompliant\r\nx-ua-compatible: IE=edge,chrome=1\r\nx-xss-protection: 1; mode=block\r\n\r\n{\"token_type\":\"bearer\",\"access_token\":\"VqiO0n2HrKE\"}"
]
];
/**
* Gets a mock cURL handle
* @param string $url the URL for the curl initialization
* @return string connection ID
*/
protected function _curl_init($url = null)
{
$request = [
'url' => $url,
CURLOPT_RETURNTRANSFER => false
];
$id = mt_rand();
$this->_requests[$id] = $request;
return $id;
}
/**
* Sets mock cURL parameters
* @param string $id connection ID
* @param int $option cURL option to set
* @param mixed $value Value to set for the option
* @return bool
*/
protected function _curl_setopt($id, $option, $value)
{
if (!isset($this->_requests[$id])) {
return false;
}
$this->_requests[$id][$option] = $value;
return true;
}
/**
* Executes mock cURL transfer
* @param string $id connection ID
* @return bool|string
*/
protected function _curl_exec($id)
{
if (!isset($this->_requests[$id])) {
return false;
}
$request = $this->_requests[$id];
$url = $this->_requests[$id]['url'];
$reply = self::$_mock_replies['default'];
$httpmethod = 'GET';
if (isset($request[CURLOPT_POST]) && $request[CURLOPT_POST]) {
$httpmethod = 'POST';
}
if (isset($request[CURLOPT_CUSTOMREQUEST])) {
$httpmethod = $request[CURLOPT_CUSTOMREQUEST];
}
$index = $httpmethod . ' ' . $url;
if (isset(self::$_mock_replies[$index])) {
$reply = self::$_mock_replies[$index];
}
$this->_requests[$id][CURLINFO_HTTP_CODE] = $reply['httpstatus'];
$this->_requests[$id]['reply'] = $reply['reply'];
if (! $this->_requests[$id][CURLOPT_HEADER]
&& stristr($reply['reply'], "\r\n\r\n")
) {
$reply_parts = explode("\r\n\r\n", $reply['reply'], 2);
$reply['reply'] = $reply_parts[1];
}
if ($this->_requests[$id][CURLOPT_RETURNTRANSFER]) {
return $reply['reply'];
}
return true;
}
/**
* Gets cURL error
* @param string $id connection ID
* @return string
*/
protected function _curl_error($id)
{
return '';
}
/**
* Gets cURL error
* @param string $id connection ID
* @return int
*/
protected function _curl_errno($id)
{
return 0;
}
/**
* Gets info about cURL connection
* @param string $id connection ID
* @param int $opt option to get
* @return mixed
*/
protected function _curl_getinfo($id, $opt = 0)
{
if (!isset($this->_requests[$id])) {
return false;
}
$request = $this->_requests[$id];
if (!$opt) {
return [
'url' => $request['url'],
'http_code' => $request[CURLINFO_HTTP_CODE]
];
}
if (isset($request[$opt])) {
return $request[$opt];
}
return false;
}
/**
* Gets fake time
* @return int Timestamp
*/
protected function _time()
{
return 1412345678;
}
/**
* Gets fake time
* @param bool $get_as_float
* @return int Timestamp
*/
protected function _microtime($get_as_float = false)
{
if ($get_as_float) {
return 1412345678.777;
}
return '777 1412345678';
}
}

View file

@ -0,0 +1,97 @@
<?php
namespace Codebird;
require_once ('src/codebird.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Codebird testing class
*
* @package codebird-test
*/
class CodebirdT extends Codebird
{
/**
* Returns properties
*
* @param string $property The property to get
*
* @return mixed Property
*/
public function get($property)
{
if (property_exists($this, $property)) {
return $this->$property;
}
throw new \Exception('Property ' . $property . ' is not defined.');
}
/**
* Returns static properties
*
* @param string $property The property to get
*
* @return mixed Property
*/
public function getStatic($property)
{
if (property_exists($this, $property)) {
return static::$$property;
}
throw new \Exception('Static property ' . $property . ' is not defined.');
}
/**
* Calls methods
*
* @param string $property The property to get
*
* @return mixed Property
*/
public function call($method, $params = [], &$params2 = null)
{
$methods_byref = [
'_mapFnToApiMethod',
'_mapFnInlineParams',
'_detectMethod'
];
if (in_array($method, $methods_byref)) {
return $this->$method($params, $params2);
}
if (method_exists($this, $method)) {
return call_user_func_array([$this, $method], $params);
}
throw new \Exception('Method ' . $method . ' is not defined.');
}
/**
* Calls methods
*
* @param string $property The property to get
*
* @return mixed Property
*/
public function callStatic($method, $params = [])
{
if (function_exists([self, $method])) {
return call_user_func_array([self, $method], $params);
}
throw new \Exception('Static method ' . $method . ' is not defined.');
}
/**
* Streaming callback test
*/
public static function streamingCallbackTest()
{
}
}

View file

@ -0,0 +1,40 @@
<?php
namespace Codebird;
require_once ('test/codebirdt.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Constant tests
*
* @package codebird-test
*/
class Constant_Test extends \PHPUnit_Framework_TestCase
{
/**
* Tests if constants defined
*/
public function testConstants()
{
$constants = [
'CODEBIRD_RETURNFORMAT_OBJECT',
'CODEBIRD_RETURNFORMAT_ARRAY',
'CODEBIRD_RETURNFORMAT_JSON'
];
foreach ($constants as $constant) {
$this->assertTrue(
defined($constant),
$constant
);
}
}
}

View file

@ -0,0 +1,57 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* cURL tests
*
* @package codebird-test
*/
class Curl_Test extends \PHPUnit_Framework_TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
$cb = new CodebirdM();
return $cb;
}
/**
* Tests _getCurlInitialization
*/
public function testGetCurlInitialization()
{
$cb = $this->getCB();
$id = $cb->call('_getCurlInitialization', ['https://test']);
$this->assertEquals(
[
'url' => 'https://test',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 0,
CURLOPT_HEADER => 1,
CURLOPT_SSL_VERIFYPEER => 1,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_CAINFO => substr(__DIR__, 0, -strlen(basename(__DIR__))) . 'src/cacert.pem',
CURLOPT_USERAGENT => 'codebird-php/' . $cb->getStatic('_version')
. ' +https://github.com/jublonet/codebird-php'
],
$cb->get('_requests')[$id]
);
}
}

View file

@ -0,0 +1,284 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Detection tests
*
* @package codebird-test
*/
class Detection_Test extends \PHPUnit_Framework_TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
$cb = new CodebirdM();
return $cb;
}
/**
* Tests _detectMethod
* @expectedException \Exception
* @expectedExceptionMessage Can't find HTTP method to use for "non-existent".
*/
public function testDetectMethod1()
{
$cb = $this->getCB();
$params = [];
$cb->call('_detectMethod', 'non-existent', $params);
}
/**
* Tests _detectMethod
*/
public function testDetectMethod2()
{
$cb = $this->getCB();
// forced httpmethod
$params = ['httpmethod' => 'DELETE'];
$this->assertEquals(
'DELETE',
$cb->call('_detectMethod', 'doesnt-matter', $params)
);
// normal detection
$params = [];
$this->assertEquals('GET', $cb->call('_detectMethod', 'search/tweets', $params));
$this->assertEquals('POST', $cb->call('_detectMethod', 'statuses/update', $params));
$this->assertEquals(
'PUT',
$cb->call(
'_detectMethod',
'ton/bucket/:bucket/:file?resumable=true&resumeId=:resumeId',
$params
)
);
// parameter-based detection
$this->assertEquals('GET', $cb->call('_detectMethod', 'account/settings', $params));
$params = ['test' => 12];
$this->assertEquals('POST', $cb->call('_detectMethod', 'account/settings', $params));
$httpmethods_by_param = [
'POST' => [
'campaign_id' => [
'ads/accounts/:account_id/line_items',
'ads/sandbox/accounts/:account_id/line_items'
],
'name' => [
'ads/accounts/:account_id/app_lists',
'ads/accounts/:account_id/campaigns',
'ads/accounts/:account_id/cards/app_download',
'ads/accounts/:account_id/cards/image_app_download',
'ads/accounts/:account_id/cards/image_conversation',
'ads/accounts/:account_id/cards/lead_gen',
'ads/accounts/:account_id/cards/video_app_download',
'ads/accounts/:account_id/cards/video_conversation',
'ads/accounts/:account_id/cards/website',
'ads/accounts/:account_id/tailored_audiences',
'ads/accounts/:account_id/web_event_tags',
'ads/sandbox/accounts/:account_id/app_lists',
'ads/sandbox/accounts/:account_id/campaigns',
'ads/sandbox/accounts/:account_id/cards/app_download',
'ads/sandbox/accounts/:account_id/cards/image_app_download',
'ads/sandbox/accounts/:account_id/cards/image_conversation',
'ads/sandbox/accounts/:account_id/cards/lead_gen',
'ads/sandbox/accounts/:account_id/cards/video_app_download',
'ads/sandbox/accounts/:account_id/cards/video_conversation',
'ads/sandbox/accounts/:account_id/cards/website',
'ads/sandbox/accounts/:account_id/tailored_audiences',
'ads/sandbox/accounts/:account_id/web_event_tags'
],
'tailored_audience_id' => [
'ads/accounts/:account_id/tailored_audience_changes',
'ads/sandbox/accounts/:account_id/tailored_audience_changes'
],
'targeting_value' => [
'ads/accounts/:account_id/targeting_criteria',
'ads/sandbox/accounts/:account_id/targeting_criteria'
],
'tweet_ids' => [
'ads/accounts/:account_id/promoted_tweets',
'ads/sandbox/accounts/:account_id/promoted_tweets'
],
'user_id' => [
'ads/accounts/:account_id/promoted_accounts',
'ads/sandbox/accounts/:account_id/promoted_accounts'
],
'video_media_id' => [
'ads/accounts/:account_id/videos',
'ads/sandbox/accounts/:account_id/videos'
]
],
'PUT' => [
'name' => [
'ads/accounts/:account_id/cards/image_conversation/:card_id',
'ads/accounts/:account_id/cards/video_conversation/:card_id',
'ads/accounts/:account_id/cards/website/:card_id',
'ads/sandbox/accounts/:account_id/cards/image_conversation/:card_id',
'ads/sandbox/accounts/:account_id/cards/video_conversation/:card_id',
'ads/sandbox/accounts/:account_id/cards/website/:card_id'
]
]
];
foreach ($httpmethods_by_param as $httpmethod => $methods_by_param) {
foreach ($methods_by_param as $param => $methods) {
foreach ($methods as $method) {
$params = [];
$this->assertEquals(
'GET',
$cb->call('_detectMethod', $method, $params),
$method
);
$params[$param] = '123';
$this->assertEquals(
$httpmethod,
$cb->call('_detectMethod', $method, $params),
$method
);
}
}
}
}
/**
* Tests _detectMultipart
*/
public function testDetectMultipart()
{
$cb = $this->getCB();
$this->assertFalse($cb->call('_detectMultipart', ['statuses/update']));
$this->assertTrue($cb->call('_detectMultipart', ['statuses/update_with_media']));
$this->assertTrue($cb->call('_detectMultipart', ['media/upload']));
}
/**
* Tests _detectMedia
*/
public function testDetectMedia()
{
$cb = $this->getCB();
$this->assertFalse($cb->call('_detectMedia', ['statuses/update']));
$this->assertTrue($cb->call('_detectMedia', ['media/upload']));
}
/**
* Tests _detectJsonBody
*/
public function testDetectJsonBody()
{
$cb = $this->getCB();
$this->assertFalse($cb->call('_detectJsonBody', ['statuses/update']));
$this->assertTrue($cb->call('_detectJsonBody', ['collections/entries/curate']));
}
/**
* Tests _detectBinaryBody
*/
public function testDetectBinaryBody()
{
$cb = $this->getCB();
$this->assertFalse($cb->call('_detectBinaryBody', ['statuses/update']));
$this->assertTrue($cb->call('_detectBinaryBody', ['ton/bucket/:bucket']));
$this->assertTrue($cb->call('_detectBinaryBody', ['ton/bucket/:bucket?resumable=true']));
$this->assertTrue($cb->call(
'_detectBinaryBody',
['ton/bucket/:bucket/:file?resumable=true&resumeId=:resumeId']
));
}
/**
* Tests _detectStreaming
*/
public function testDetectStreaming()
{
$cb = $this->getCB();
$this->assertFalse($cb->call('_detectStreaming', ['statuses/update']));
$this->assertEquals('public', $cb->call('_detectStreaming', ['statuses/sample']));
$this->assertEquals('public', $cb->call('_detectStreaming', ['statuses/filter']));
$this->assertEquals('public', $cb->call('_detectStreaming', ['statuses/firehose']));
$this->assertEquals('user', $cb->call('_detectStreaming', ['user']));
$this->assertEquals('site', $cb->call('_detectStreaming', ['site']));
}
/**
* Tests _getEndpoint
*/
public function testGetEndpoint()
{
$cb = $this->getCB();
$this->assertEquals(
'https://api.twitter.com/1.1/statuses/update.json',
$cb->call('_getEndpoint', ['statuses/update', 'statuses/update']),
'statuses/update'
);
$this->assertEquals(
'https://api.twitter.com/oauth/authenticate',
$cb->call('_getEndpoint', ['oauth/authenticate', 'oauth/authenticate']),
'oauth/authenticate'
);
$this->assertEquals(
'https://api.twitter.com/oauth2/token',
$cb->call('_getEndpoint', ['oauth2/token', 'oauth2/token']),
'oauth2/token'
);
$this->assertEquals(
'https://upload.twitter.com/1.1/media/upload.json',
$cb->call('_getEndpoint', ['media/upload', 'media/upload']),
'media/upload'
);
$this->assertEquals(
'https://stream.twitter.com/1.1/statuses/filter.json',
$cb->call('_getEndpoint', ['statuses/filter', 'statuses/filter']),
'statuses/filter'
);
$this->assertEquals(
'https://sitestream.twitter.com/1.1/site.json',
$cb->call('_getEndpoint', ['site', 'site']),
'site'
);
$this->assertEquals(
'https://userstream.twitter.com/1.1/user.json',
$cb->call('_getEndpoint', ['user', 'user']),
'user'
);
$this->assertEquals(
'https://ton.twitter.com/1.1/ton/bucket/ta_partner',
$cb->call('_getEndpoint', ['ton/bucket/ta_partner', 'ton/bucket/:bucket']),
'ton/bucket/:bucket'
);
$this->assertEquals(
'https://ads-api.twitter.com/0/accounts/1234/campaigns',
$cb->call(
'_getEndpoint',
['ads/accounts/1234/campaigns', 'ads/accounts/:account_id/campaigns']
),
'ads/accounts/:account_id/campaigns'
);
$this->assertEquals(
'https://ads-api-sandbox.twitter.com/0/accounts/1234/campaigns',
$cb->call(
'_getEndpoint',
['ads/sandbox/accounts/1234/campaigns', 'ads/sandbox/accounts/:account_id/campaigns']
),
'ads/sandbox/accounts/:account_id/campaigns'
);
}
}

View file

@ -0,0 +1,40 @@
<?php
namespace Codebird;
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Environment tests
*
* @package codebird-test
*/
class Environment_Test extends \PHPUnit_Framework_TestCase
{
/**
* Tests PHP version
*/
public function testPhpVersion()
{
$this->assertTrue(
version_compare('5.5', phpversion(), '<='),
'Codebird requires PHP 5.5 or above'
);
}
/**
* Tests OpenSSL module availability
*/
public function testOpenssl()
{
$this->assertTrue(function_exists('openssl_open'));
}
}

View file

@ -0,0 +1,56 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Media tests
*
* @package codebird-test
*/
class Media_Test extends \PHPUnit_Framework_TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
Codebird::setConsumerKey('123', '456');
$cb = new CodebirdM();
return $cb;
}
/**
* Tests _fetchRemoteFile
*/
public function testFetchRemoteFile()
{
$cb = $this->getCB();
$expected = $cb->call('_fetchRemoteFile', ['http://www.example.org/found.txt']);
$this->assertEquals($expected, 'A test file.');
}
/**
* Tests _fetchRemoteFile
* @expectedException \Exception
* @expectedExceptionMessage Downloading a remote media file failed.
*/
public function testFetchRemoteFile1()
{
$cb = $this->getCB();
$reply = $cb->call('_fetchRemoteFile', ['http://www.example.org/not-found.jpg']);
}
}

View file

@ -0,0 +1,130 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* OAuth tests
*
* @package codebird-test
*/
class Oauth_Test extends \PHPUnit_Framework_TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
Codebird::setConsumerKey('123', '456');
$cb = new CodebirdM();
return $cb;
}
/**
* Tests oauth_authenticate
*/
public function testOauthAuthenticate()
{
$cb = $this->getCB();
$cb->setToken('123', '456');
$this->assertEquals(
'https://api.twitter.com/oauth/authenticate?oauth_token=123',
$cb->oauth_authenticate()
);
$this->assertEquals(
'https://api.twitter.com/oauth/authenticate?oauth_token=123&force_login=1',
$cb->oauth_authenticate($force_login = true)
);
$this->assertEquals(
'https://api.twitter.com/oauth/authenticate?'
. 'oauth_token=123&force_login=1&screen_name=TwitterAPI',
$cb->oauth_authenticate($force_login = true, $screen_name = 'TwitterAPI')
);
$this->assertEquals(
'https://api.twitter.com/oauth/authenticate?'
. 'oauth_token=123&screen_name=TwitterAPI',
$cb->oauth_authenticate($force_login = false, $screen_name = 'TwitterAPI')
);
}
/**
* Tests oauth_authorize
*/
public function testOauthAuthorize()
{
$cb = $this->getCB();
$cb->setToken('123', '456');
$this->assertEquals(
'https://api.twitter.com/oauth/authorize?oauth_token=123',
$cb->oauth_authorize()
);
$this->assertEquals(
'https://api.twitter.com/oauth/authorize?oauth_token=123&force_login=1',
$cb->oauth_authorize($force_login = true)
);
$this->assertEquals(
'https://api.twitter.com/oauth/authorize?'
. 'oauth_token=123&force_login=1&screen_name=TwitterAPI',
$cb->oauth_authorize($force_login = true, $screen_name = 'TwitterAPI')
);
$this->assertEquals(
'https://api.twitter.com/oauth/authorize?'
. 'oauth_token=123&screen_name=TwitterAPI',
$cb->oauth_authorize($force_login = false, $screen_name = 'TwitterAPI')
);
}
/**
* Tests oauth2_token
*/
public function testOauth2Token()
{
$cb = $this->getCB();
$expected = new \stdClass;
$expected->token_type = 'bearer';
$expected->access_token = 'VqiO0n2HrKE';
$expected->httpstatus = '200';
$expected->rate = null;
$this->assertEquals($expected, $cb->oauth2_token());
}
/**
* Tests _getBearerAuthorization
* @expectedException \Exception
* @expectedExceptionMessage To make an app-only auth API request, consumer key or bearer token must be set.
*/
public function testGetBearerAuthorization1()
{
$cb = $this->getCB();
Codebird::setConsumerKey(null, null);
$cb->setBearerToken(null);
$cb->call('_getBearerAuthorization', []);
}
/**
* Tests _getBearerAuthorization
*/
public function testGetBearerAuthorization2()
{
$cb = $this->getCB();
$cb->setBearerToken('12345678');
$this->assertEquals('Bearer 12345678', $cb->call('_getBearerAuthorization', []));
// automatic fetching
$cb->setBearerToken(null);
$this->assertEquals('Bearer VqiO0n2HrKE', $cb->call('_getBearerAuthorization', []));
}
}

View file

@ -0,0 +1,361 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Reply parsing tests
*
* @package codebird-test
*/
class Replyparse_Test extends \PHPUnit_Framework_TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
Codebird::setConsumerKey('123', '456');
$cb = new CodebirdM();
return $cb;
}
/**
* Tests _getHttpStatusFromHeaders
*/
public function testGetHttpStatusFromHeaders()
{
$cb = $this->getCB();
$this->assertEquals(
'500',
$cb->call('_getHttpStatusFromHeaders', [['']])
);
$this->assertEquals(
'200',
$cb->call('_getHttpStatusFromHeaders', [
['HTTP/1.1 200 OK'],
['X-Some-Data: test']
])
);
$this->assertEquals(
'404',
$cb->call('_getHttpStatusFromHeaders', [
['HTTP/1.1 404 Not Found'],
['X-Some-Data: test']
])
);
}
/**
* Tests _parseBearerReply
*/
public function testParseBearerReply()
{
$cb = $this->getCB();
$cb->setBearerToken(null);
// get raw reply from mock collection
$reply = $cb->getStatic('_mock_replies')['POST https://api.twitter.com/oauth2/token'];
// check that bearer token is not yet set
$this->assertNull($cb->getStatic('_bearer_token'));
// parse it as object
$result = $cb->call(
'_parseBearerReply',
[
$reply['reply'],
$reply['httpstatus']
]
);
$expected = new \stdClass;
$expected->token_type = 'bearer';
$expected->access_token = 'VqiO0n2HrKE';
$expected->httpstatus = 200;
$expected->rate = null;
$this->assertEquals($expected, $result);
// check that bearer token was actually set
$this->assertNotNull($cb->getStatic('_bearer_token'));
// array
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
$cb->setBearerToken(null);
$result = $cb->call(
'_parseBearerReply',
[
$reply['reply'],
$reply['httpstatus']
]
);
$expected = [
'token_type' => 'bearer',
'access_token' => 'VqiO0n2HrKE',
'httpstatus' => 200,
'rate' => null
];
$this->assertEquals($expected, $result);
// check that bearer token was actually set
$this->assertNotNull($cb->getStatic('_bearer_token'));
// JSON
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_JSON);
$cb->setBearerToken(null);
$result = $cb->call(
'_parseBearerReply',
[
$reply['reply'],
$reply['httpstatus']
]
);
$expected = '{"token_type":"bearer","access_token":"VqiO0n2HrKE"}';
$this->assertEquals($expected, $result);
// check that bearer token was actually set
$this->assertNotNull($cb->getStatic('_bearer_token'));
}
/**
* Tests _getRateLimitInfo
*/
public function testGetRateLimitInfo()
{
$cb = $this->getCB();
$headers = [
'content-length' => 68,
'content-type' => 'application/json;charset=utf-8',
'date' => 'Sun, 06 Dec 2015 14:43:28 GMT'
];
$this->assertNull($cb->call('_getRateLimitInfo', [$headers]));
// set rate-limit headers
$headers['x-rate-limit-limit'] = 180;
$headers['x-rate-limit-remaining'] = 123;
$headers['x-rate-limit-reset'] = time() + 234;
$rate = $cb->call('_getRateLimitInfo', [$headers]);
$expected = new \stdClass;
$expected->limit = $headers['x-rate-limit-limit'];
$expected->remaining = $headers['x-rate-limit-remaining'];
$expected->reset = $headers['x-rate-limit-reset'];
$this->assertEquals($expected, $rate);
// array
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
$rate = $cb->call('_getRateLimitInfo', [$headers]);
$expected = [
'limit' => $headers['x-rate-limit-limit'],
'remaining' => $headers['x-rate-limit-remaining'],
'reset' => $headers['x-rate-limit-reset']
];
$this->assertEquals($expected, $rate);
}
/**
* Tests _validateSslCertificate
*/
public function testValidateSslCertificate1()
{
$cb = $this->getCB();
$cb->call('_validateSslCertificate', [0]);
}
/**
* Tests _validateSslCertificate
* @expectedException \Exception
* @expectedExceptionMessage Error 58 while validating the Twitter API certificate.
*/
public function testValidateSslCertificate2()
{
$cb = $this->getCB();
$cb->call('_validateSslCertificate', [CURLE_SSL_CERTPROBLEM]);
}
/**
* Tests _appendHttpStatusAndRate
*/
public function testAppendHttpStatusAndRate()
{
$cb = $this->getCB();
// object
$reply = new \stdClass;
$reply->somedata = 123;
$reply->moredata = '456';
$rate = new \stdClass;
$rate->field1 = 180;
$rate->field2 = 177;
$expected = new \stdClass;
$expected->somedata = 123;
$expected->moredata = '456';
$expected->httpstatus = 409;
$expected->rate = new \stdClass;
$expected->rate->field1 = 180;
$expected->rate->field2 = 177;
$this->assertEquals(
$expected,
$cb->call('_appendHttpStatusAndRate', [$reply, 409, $rate])
);
// array
$reply = (array) $reply;
$rate = (array) $rate;
$expected = (array) $expected;
$expected['rate'] = (array) $expected['rate'];
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
$this->assertEquals(
$expected,
$cb->call('_appendHttpStatusAndRate', [$reply, 409, $rate])
);
// JSON
$reply = '{"somedata":123,"moredata":"456"}';
$expected = '{"somedata":123,"moredata":"456","httpstatus":409,'
. '"rate":{"field1":180,"field2":177}}';
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_JSON);
$this->assertEquals(
$expected,
$cb->call('_appendHttpStatusAndRate', [$reply, 409, $rate])
);
}
/**
* Tests _parseApiHeaders
*/
public function testParseApiHeaders()
{
$cb = $this->getCB();
$data = $cb->getStatic('_mock_replies')['default']['reply'];
list($headers, $reply) = $cb->call('_parseApiHeaders', [$data]);
$expected_headers = [
'HTTP/1.1 404 Not Found' => '',
'content-length' => '68',
'content-type' => 'application/json;charset=utf-8',
'date' => 'Sun, 06 Dec 2015 14:43:28 GMT',
'server' => 'tsa_b',
'set-cookie' => 'guest_id=v1%3A144941300885288055; Domain=.twitter.com'
. '; Path=/; Expires=Tue, 05-Dec-2017 14:43:28 UTC',
'strict-transport-security' => 'max-age=631138519',
'x-connection-hash' => '12218aef9e9757609afb08e661fa3b9b',
'x-response-time' => '2'
];
$expected_reply = '{"errors":[{"message":"Sorry, that page does not exist","code":34}]}';
$this->assertEquals($expected_headers, $headers);
$this->assertEquals($expected_reply, $reply);
// proxy
$data = $cb->getStatic('_mock_replies')['proxy1']['reply'];
list($headers, $reply) = $cb->call('_parseApiHeaders', [$data]);
$this->assertEquals($expected_headers, $headers);
$this->assertEquals($expected_reply, $reply);
}
/**
* Tests _parseApiReplyPrefillHeaders
*/
public function testParseApiReplyPrefillHeaders()
{
$cb = $this->getCB();
$headers = [
'X-TON-Min-Chunk-Size' => '12345',
'X-TON-Max-Chunk-Size' => '23456',
'Range' => 'bytes 0-1234567/2345678'
];
// non-empty reply: no touching
$this->assertEquals(
'123',
$cb->call('_parseApiReplyPrefillHeaders', [$headers, '123'])
);
// no location header: no touching
$this->assertEquals(
'',
$cb->call('_parseApiReplyPrefillHeaders', [$headers, ''])
);
$headers['Location'] = 'https://twitter.com';
$this->assertEquals(
'{"Location":"https:\/\/twitter.com","X-TON-Min-Chunk-Size":"12345",'
. '"X-TON-Max-Chunk-Size":"23456","Range":"bytes 0-1234567\/2345678"}',
$cb->call('_parseApiReplyPrefillHeaders', [$headers, ''])
);
}
/**
* Tests _parseApiReply
*/
public function testParseApiReply1()
{
$cb = $this->getCB();
// object
$this->assertEquals(new \stdClass, $cb->call('_parseApiReply', ['[]']));
// array
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
$this->assertEquals([], $cb->call('_parseApiReply', ['[]']));
// JSON
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_JSON);
$this->assertEquals('{}', $cb->call('_parseApiReply', ['[]']));
}
/**
* Tests _parseApiReply
*/
public function testParseApiReply2()
{
$cb = $this->getCB();
$reply = '{"id_str":"6253282","profile_location":null,'
. '"status":{"created_at":"Tue Nov 24 08:56:07 +0000 2015","id":669077021138493440}}';
// object
$expected = new \stdClass;
$expected->id_str = '6253282';
$expected->profile_location = null;
$expected->status = new \stdClass;
$expected->status->created_at = 'Tue Nov 24 08:56:07 +0000 2015';
$expected->status->id = 669077021138493440;
$result = $cb->call('_parseApiReply', [$reply]);
$this->assertEquals($expected, $result);
$this->assertSame($expected->status->id, $result->status->id);
// array
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
$expected = (array) $expected;
$expected['status'] = (array) $expected['status'];
$this->assertEquals($expected, $cb->call('_parseApiReply', [$reply]));
// JSON
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_JSON);
$this->assertEquals($reply, $cb->call('_parseApiReply', [$reply]));
// query-string format
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
$this->assertEquals(
[
'oauth_token' => 'ABC',
'oauth_token_secret' => 'def',
'oauth_callback_confirmed' => 'true'
],
$cb->call(
'_parseApiReply',
['oauth_token=ABC&oauth_token_secret=def&oauth_callback_confirmed=true']
)
);
// message
$this->assertEquals(
['message' => 'This is just a message.'],
$cb->call('_parseApiReply', ['This is just a message.'])
);
}
}

View file

@ -0,0 +1,212 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Request parsing tests
*
* @package codebird-test
*/
class Requestparse_Test extends \PHPUnit_Framework_TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
Codebird::setConsumerKey('123', '456');
$cb = new CodebirdM();
$cb->setToken('234', '567');
return $cb;
}
/**
* Tests _parseApiParams
*/
public function testParseApiParams()
{
$cb = $this->getCB();
// empty list
$this->assertEquals([], $cb->call('_parseApiParams', [[]]));
// arrays
$this->assertEquals(['test' => 1], $cb->call('_parseApiParams', [[['test' => 1]]]));
$this->assertEquals(
['media[]' => '123'],
$cb->call('_parseApiParams', [[['media[]' => 123]]])
);
// urlencoded strings
$this->assertEquals(['testdata' => ''], $cb->call('_parseApiParams', [['testdata']]));
$this->assertEquals(
['param1' => '12', 'param2' => 'ab'],
$cb->call('_parseApiParams', [['param1=12&param2=ab']])
);
$this->assertEquals(
['media' => ['123', '456']],
$cb->call('_parseApiParams', [['media[]=123&media[]=456']])
);
}
/**
* Tests _stringifyNullBoolParams
*/
public function testStringifyNullBoolParams()
{
$cb = $this->getCB();
$result = $cb->call(
'_stringifyNullBoolParams',
[['a' => 123, 'b' => null, 'c' => true, 'd' => false, 'e' => 'x']]
);
$this->assertEquals('123', $result['a']);
$this->assertNull($result['b']);
$this->assertEquals('true', $result['c']);
$this->assertEquals('false', $result['d']);
}
/**
* Tests _mapFnToApiMethod
*/
public function testMapFnToApiMethod()
{
$cb = $this->getCB();
$apiparams = [
'test' => 1,
'account_id' => '1234'
];
$result = $cb->call(
'_mapFnToApiMethod',
'ads_accounts_ACCOUNT_ID_cards_appDownload',
$apiparams
);
$this->assertEquals([
'ads/accounts/1234/cards/app_download',
'ads/accounts/:account_id/cards/app_download'
], $result);
// check that inline parameter was removed from array
$this->assertArrayNotHasKey('account_id', $apiparams);
}
/**
* Tests _mapFnInsertSlashes
*/
public function testMapFnInsertSlashes()
{
$cb = $this->getCB();
$result = $cb->call(
'_mapFnInsertSlashes',
['ads_accounts_ACCOUNT_ID_cards_appDownload']
);
$this->assertEquals(
'ads/accounts/ACCOUNT/ID/cards/appDownload',
$result
);
}
/**
* Tests _mapFnRestoreParamUnderscores
*/
public function testMapFnRestoreParamUnderscores()
{
$cb = $this->getCB();
$params_underscore = [
'screen_name', 'place_id',
'account_id', 'campaign_id', 'card_id', 'line_item_id',
'tweet_id', 'web_event_tag_id'
];
$params_slash = [];
foreach ($params_underscore as $param) {
$params_slash[] = str_replace('_', '/', $param);
}
for ($i = 0; $i < count($params_underscore); $i++) {
$result = $cb->call(
'_mapFnRestoreParamUnderscores',
['ads/accounts/' . strtoupper($params_slash[$i]) . '/cards/appDownload']
);
$this->assertEquals(
'ads/accounts/' . strtoupper($params_underscore[$i]) . '/cards/appDownload',
$result
);
}
}
/**
* Tests _mapFnInlineParams
*/
public function testMapFnInlineParams()
{
$cb = $this->getCB();
// normal parameters
$apiparams = [
'test' => 1,
'account_id' => '1234'
];
$result = $cb->call(
'_mapFnInlineParams',
'ads/accounts/ACCOUNT_ID/cards/app_download',
$apiparams
);
$this->assertEquals([
'ads/accounts/1234/cards/app_download',
'ads/accounts/:account_id/cards/app_download'
],
$result
);
// check that inline parameter was removed from array
$this->assertArrayNotHasKey('account_id', $apiparams);
// special parameters (TON API)
$apiparams = [
'test' => 1,
'bucket' => 'ta_partner',
'file' => 'test_Ab.mp4',
'resumeId' => '56789'
];
$result = $cb->call(
'_mapFnInlineParams',
'ton/bucket/BUCKET/FILE?resumable=true&resumeId=RESUMEID',
$apiparams
);
$this->assertEquals([
'ton/bucket/ta_partner/test_Ab.mp4?resumable=true&resumeId=56789',
'ton/bucket/:bucket/:file?resumable=true&resumeId=:resumeId'
],
$result
);
$this->assertArrayNotHasKey('bucket', $apiparams);
$this->assertArrayNotHasKey('file', $apiparams);
$this->assertArrayNotHasKey('resumeId', $apiparams);
$this->assertEquals(['test' => 1], $apiparams);
}
/**
* Tests _json_decode
*/
public function testJsonDecode()
{
$json = '{"id": 123456789123456789, "id_str": "123456789123456789"}';
$array = [
'id' => 123456789123456789,
'id_str' => '123456789123456789'
];
$object = (object) $array;
$cb = $this->getCB();
$result = $cb->call('_json_decode', [$json]);
$this->assertEquals($object, $result);
$result = $cb->call('_json_decode', [$json, true]);
$this->assertEquals($array, $result);
}
}

View file

@ -0,0 +1,70 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Return format tests
*
* @package codebird-test
*/
class Returnformat_Test extends \PHPUnit_Framework_TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
Codebird::setConsumerKey('123', '456');
$cb = new CodebirdM();
$cb->setToken('234', '567');
return $cb;
}
/**
* Tests array return format
*/
public function testArrayFormat()
{
$cb = $this->getCB();
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
$reply = $cb->users_show(['screen_name' => 'TwitterAPI']);
$this->assertTrue(is_array($reply));
}
/**
* Tests object return format
*/
public function testObjectFormat()
{
$cb = $this->getCB();
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_OBJECT);
$reply = $cb->users_show(['screen_name' => 'TwitterAPI']);
$this->assertInstanceOf('stdClass', $reply);
}
/**
* Tests JSON return format
*/
public function testJsonFormat()
{
$cb = $this->getCB();
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_JSON);
$reply = $cb->users_show(['screen_name' => 'TwitterAPI']);
$data = json_decode($reply);
$this->assertNotFalse($data);
}
}

View file

@ -0,0 +1,253 @@
<?php
namespace Codebird;
require_once ('test/codebirdt.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Setter function tests
*
* @package codebird-test
*/
class Setter_Test extends \PHPUnit_Framework_TestCase
{
/**
* Tests setConsumerKey
*/
public function testSetConsumerKey()
{
$cb = new CodebirdT();
$cb->setConsumerKey('123', '456');
$this->assertEquals('123', $cb->getStatic('_consumer_key'));
$this->assertEquals('456', $cb->getStatic('_consumer_secret'));
}
/**
* Tests setBearerToken
*/
public function testSetBearerToken()
{
$cb = new CodebirdT();
$cb->setBearerToken('789');
$this->assertEquals('789', $cb->getStatic('_bearer_token'));
}
/**
* Tests getVersion
*/
public function testGetVersion()
{
$cb = new CodebirdT();
$version = $cb->getVersion();
$this->assertEquals($version, $cb->getStatic('_version'));
$this->assertRegexp('/^[1-9]\d*\.\d+\.\d+(-([a-z]+\.[1-9]\d*|dev))?$/', $version);
}
/**
* Tests setToken
*/
public function testSetToken()
{
$cb = new CodebirdT();
$cb->setToken('123', '456');
$this->assertEquals('123', $cb->get('_oauth_token'));
$this->assertEquals('456', $cb->get('_oauth_token_secret'));
}
/**
* Tests logout
*/
public function testLogout()
{
$cb = new CodebirdT();
$cb->setToken('123', '456');
$cb->logout();
$this->assertNull($cb->get('_oauth_token'));
$this->assertNull($cb->get('_oauth_token_secret'));
}
/**
* Tests setUseCurl
*/
public function testSetUseCurl()
{
$cb = new CodebirdT();
$cb->setUseCurl(true);
$this->assertTrue($cb->get('_use_curl'));
$cb->setUseCurl(false);
$this->assertFalse($cb->get('_use_curl'));
$cb->setUseCurl('123');
$this->assertTrue($cb->get('_use_curl'));
}
/**
* Tests setTimeout
*/
public function testSetTimeout()
{
$cb = new CodebirdT();
$cb->setTimeout(123);
$this->assertEquals(123, $cb->get('_timeouts')['request']);
$cb->setTimeout(0);
$this->assertEquals(0, $cb->get('_timeouts')['request']);
$cb->setTimeout(-123);
$this->assertEquals(0, $cb->get('_timeouts')['request']);
}
/**
* Tests setConnectionTimeout
*/
public function testSetConnectionTimeout()
{
$cb = new CodebirdT();
$cb->setConnectionTimeout(123);
$this->assertEquals(123, $cb->get('_timeouts')['connect']);
$cb->setConnectionTimeout(0);
$this->assertEquals(0, $cb->get('_timeouts')['connect']);
$cb->setConnectionTimeout(-123);
$this->assertEquals(0, $cb->get('_timeouts')['connect']);
}
/**
* Tests setConnectionTimeout
*/
public function testSetRemoteDownloadTimeout()
{
$cb = new CodebirdT();
$cb->setRemoteDownloadTimeout(123);
$this->assertEquals(123, $cb->get('_timeouts')['remote']);
$cb->setRemoteDownloadTimeout(0);
$this->assertEquals(0, $cb->get('_timeouts')['remote']);
$cb->setRemoteDownloadTimeout(-123);
$this->assertEquals(0, $cb->get('_timeouts')['remote']);
}
/**
* Tests setReturnFormat
*/
public function testSetReturnFormat()
{
$cb = new CodebirdT();
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_JSON);
$this->assertEquals($cb->get('_return_format'), CODEBIRD_RETURNFORMAT_JSON);
}
/**
* Tests setProxy
*/
public function testSetProxy()
{
$cb = new CodebirdT();
$cb->setProxy('127.0.0.1', '8888');
$this->assertEquals('127.0.0.1', $cb->get('_proxy')['host']);
$this->assertEquals('8888', $cb->get('_proxy')['port']);
$this->assertEquals(CURLPROXY_HTTP, $cb->get('_proxy')['type']);
$cb->setProxy('127.0.0.1', '8888', CURLPROXY_SOCKS5);
$this->assertEquals('127.0.0.1', $cb->get('_proxy')['host']);
$this->assertEquals('8888', $cb->get('_proxy')['port']);
$this->assertEquals(CURLPROXY_SOCKS5, $cb->get('_proxy')['type']);
}
/**
* Tests setProxy
* @expectedException \Exception
* @expectedExceptionMessage Invalid proxy type specified.
*/
public function testSetProxy2()
{
$cb = new CodebirdT();
$cb->setProxy('127.0.0.1', '8888', 1);
}
/**
* Tests setProxyAuthentication
*/
public function testSetProxyAuthentication()
{
$cb = new CodebirdT();
$cb->setProxyAuthentication('ABCDEF');
$this->assertEquals('ABCDEF', $cb->get('_proxy')['authentication']);
}
/**
* Tests setStreamingCallback
*/
public function testSetStreamingCallback1()
{
$callback = ['\Codebird\CodebirdT', 'streamingCallbackTest'];
$cb = new CodebirdT();
$cb->setStreamingCallback($callback);
$this->assertSame(
array_diff($callback, $cb->get('_streaming_callback')),
array_diff($cb->get('_streaming_callback'), $callback)
);
}
/**
* Tests setStreamingCallback
* @expectedException \Exception
* @expectedExceptionMessage This is not a proper callback.
*/
public function testSetStreamingCallback2()
{
$cb = new CodebirdT();
$cb->setStreamingCallback(['\Codebird\CodebirdTX', 'somewhere']);
}
/**
* Tests getApiMethods
*/
public function testGetApiMethods()
{
$cb = new CodebirdT();
$methods = $cb->getApiMethods();
$this->assertArrayHasKey('GET', $cb->getStatic('_api_methods'));
$this->assertArrayHasKey('POST', $cb->getStatic('_api_methods'));
$this->assertArrayHasKey('PUT', $cb->getStatic('_api_methods'));
$this->assertArrayHasKey('DELETE', $cb->getStatic('_api_methods'));
$this->assertEquals($methods, $cb->getStatic('_api_methods'));
}
/**
* Tests hasProxy
*/
public function testHasProxy()
{
$cb = new CodebirdT();
$this->assertFalse($cb->call('_hasProxy'));
$cb->setProxy('127.0.0.1', '8888');
$this->assertTrue($cb->call('_hasProxy'));
}
/**
* Tests getProxyHost
*/
public function testGetProxyHost()
{
$cb = new CodebirdT();
$this->assertNull($cb->call('_getProxyHost'));
$cb->setProxy('127.0.0.1', '8888');
$this->assertEquals('127.0.0.1', $cb->call('_getProxyHost'));
}
/**
* Tests getProxyPort
*/
public function testGetProxyPort()
{
$cb = new CodebirdT();
$this->assertNull($cb->call('_getProxyPort'));
$cb->setProxy('127.0.0.1', '8888');
$this->assertEquals('8888', $cb->call('_getProxyPort'));
}
}

View file

@ -0,0 +1,166 @@
<?php
namespace Codebird;
require_once ('test/codebirdm.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* OAuth signing tests
*
* @package codebird-test
*/
class Signing_Test extends \PHPUnit_Framework_TestCase
{
/**
* Initialise Codebird class
*
* @return \Codebird\Codebird The Codebird class
*/
protected function getCB()
{
Codebird::setConsumerKey('123', '456');
$cb = new CodebirdM();
return $cb;
}
/**
* Tests _url
*/
public function testUrl()
{
$cb = $this->getCB();
// string
$this->assertEquals(
'q%20%2B%20b%21%22%C2%A7%24%25%26%2F%28%29%3D%3F%23%2A13%2C3%C3%A4.',
$cb->call('_url', ['q + b!"§$%&/()=?#*13,3ä.'])
);
// array
$this->assertEquals(
[
'q%20%2B%20b%21%22%C2%A7%24%25%26%2F%28%29%3D%3F%23%2A13%2C3%C3%A4.',
'test123'
],
$cb->call('_url', [[
'q + b!"§$%&/()=?#*13,3ä.',
'test123'
]])
);
}
/**
* Tests _sha1
*/
public function testSha1()
{
$cb = $this->getCB();
$this->assertEquals(
'ydAlpYjrGHU7psDQ9HPgHTcwEuw=',
$cb->call('_sha1', ['q + b!"§$%&/()=?#*13,3ä.'])
);
// with access token secret
$cb->setToken('678', '789');
$this->assertEquals(
'CtivZhAHiX49ZMUuHXtKabLAuo0=',
$cb->call('_sha1', ['q + b!"§$%&/()=?#*13,3ä.'])
);
}
/**
* Tests _nonce
*/
public function testNonce1()
{
$cb = $this->getCB();
// default length
$this->assertEquals(
'4247c524',
$cb->call('_nonce', [])
);
// custom length
$this->assertEquals(
'4247c5248da',
$cb->call('_nonce', [11])
);
}
/**
* Tests _nonce
* @expectedException \Exception
* @expectedExceptionMessage Invalid nonce length.
*/
public function testNonce2()
{
$cb = $this->getCB();
// invalid length
$cb->call('_nonce', [0]);
}
/**
* Tests _getSignature
*/
public function testGetSignature()
{
$cb = $this->getCB();
$base_params = [
'oauth_consumer_key' => '123',
'oauth_nonce' => '12345678',
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => '1400000000',
'oauth_token' => '567',
'oauth_version' => '1.0',
'q' => 'Test search.'
];
$this->assertEquals(
'ZON/m9bHvciPdtyK9BlokjeiW4M=',
$cb->call('_getSignature', ['GET', 'search/tweets', $base_params])
);
}
/**
* Tests _sign
* @expectedException \Exception
* @expectedExceptionMessage To generate a signature, the consumer key must be set.
*/
public function testSign1()
{
$cb = $this->getCB();
$cb->setConsumerKey(null, null);
$params = ['q' => 'Test search.'];
$cb->call('_sign', ['GET', 'search/tweets', $params]);
}
/**
* Tests _sign
*/
public function testSign2()
{
$cb = $this->getCB();
$params = ['q' => 'Test search.'];
$this->assertEquals(
'OAuth oauth_consumer_key="123", oauth_nonce="4247c524", oauth_signature'
. '="lOLNd5l6cGB9kWACxWLNKJwSD%2FI%3D", oauth_signature_method="HMAC-SHA'
. '1", oauth_timestamp="1412345678", oauth_version="1.0"',
$cb->call('_sign', ['GET', 'search/tweets', $params])
);
// with oauth token
$cb->setToken('678', '789');
$this->assertEquals(
'OAuth oauth_consumer_key="123", oauth_nonce="4247c524", oauth_signature'
. '="XzegzFKEqs2PpUMym5T%2BwhEmTz4%3D", oauth_signature_method="HMAC-SHA'
. '1", oauth_timestamp="1412345678", oauth_token="678", oauth_version="1.0"',
$cb->call('_sign', ['GET', 'search/tweets', $params])
);
}
}

View file

@ -0,0 +1,31 @@
<?php
namespace Codebird;
require_once ('test/codebirdt.php');
/**
* A Twitter library in PHP.
*
* @package codebird-test
* @author Jublo Solutions <support@jublo.net>
* @copyright 2010-2016 Jublo Solutions <support@jublo.net>
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* @link https://github.com/jublonet/codebird-php
*/
/**
* Singleton tests
*
* @package codebird-test
*/
class Singleton_Test extends \PHPUnit_Framework_TestCase
{
/**
* Tests getInstance
*/
public function testGetInstance()
{
$cb = CodebirdT::getInstance();
$this->assertInstanceOf('\Codebird\Codebird', $cb);
}
}