diff options
author | Snap <snapwilliam@gmail.com> | 2015-04-16 14:51:26 -0700 |
---|---|---|
committer | Snap <snapwilliam@gmail.com> | 2015-04-16 14:51:26 -0700 |
commit | 5c7f2f17f9c471d306955df457c7cab4e5c6ed3b (patch) | |
tree | 0fe6d049f1af552af6a74d264a3f571cfdb1ee7c /includes/google-api-php-client-master/tests/general | |
parent | d0b9b771a876922afdf00b2c55d5e1388a4ea2a3 (diff) | |
download | pathery-5c7f2f17f9c471d306955df457c7cab4e5c6ed3b.tar.xz |
Google's OpenID Connect method
$google_client_id & $google_client_secret must be added to db.inc.php!
Diffstat (limited to 'includes/google-api-php-client-master/tests/general')
24 files changed, 3930 insertions, 0 deletions
diff --git a/includes/google-api-php-client-master/tests/general/ApiBatchRequestTest.php b/includes/google-api-php-client-master/tests/general/ApiBatchRequestTest.php new file mode 100644 index 0000000..6cfc3bf --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/ApiBatchRequestTest.php @@ -0,0 +1,79 @@ +<?php +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +class ApiBatchRequestTest extends BaseTest +{ + public $plus; + + public function testBatchRequestWithAuth() + { + if (!$this->checkToken()) { + return; + } + $client = $this->getClient(); + $batch = new Google_Http_Batch($client); + $this->plus = new Google_Service_Plus($client); + + $client->setUseBatch(true); + $batch->add($this->plus->people->get('me'), 'key1'); + $batch->add($this->plus->people->get('me'), 'key2'); + $batch->add($this->plus->people->get('me'), 'key3'); + + $result = $batch->execute(); + $this->assertTrue(isset($result['response-key1'])); + $this->assertTrue(isset($result['response-key2'])); + $this->assertTrue(isset($result['response-key3'])); + } + + public function testBatchRequest() + { + $client = $this->getClient(); + $batch = new Google_Http_Batch($client); + $this->plus = new Google_Service_Plus($client); + + $client->setUseBatch(true); + $batch->add($this->plus->people->get('+LarryPage'), 'key1'); + $batch->add($this->plus->people->get('+LarryPage'), 'key2'); + $batch->add($this->plus->people->get('+LarryPage'), 'key3'); + + $result = $batch->execute(); + $this->assertTrue(isset($result['response-key1'])); + $this->assertTrue(isset($result['response-key2'])); + $this->assertTrue(isset($result['response-key3'])); + } + + public function testInvalidBatchRequest() + { + $client = $this->getClient(); + $batch = new Google_Http_Batch($client); + $this->plus = new Google_Service_Plus($client); + + $client->setUseBatch(true); + $batch->add($this->plus->people->get('123456789987654321'), 'key1'); + $batch->add($this->plus->people->get('+LarryPage'), 'key2'); + + $result = $batch->execute(); + $this->assertTrue(isset($result['response-key2'])); + $this->assertInstanceOf( + 'Google_Service_Exception', + $result['response-key1'] + ); + } +} diff --git a/includes/google-api-php-client-master/tests/general/ApiCacheParserTest.php b/includes/google-api-php-client-master/tests/general/ApiCacheParserTest.php new file mode 100644 index 0000000..3f54862 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/ApiCacheParserTest.php @@ -0,0 +1,262 @@ +<?php +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +class ApiCacheParserTest extends BaseTest +{ + public function testIsResponseCacheable() + { + $client = $this->getClient(); + $resp = new Google_Http_Request('http://localhost', 'POST'); + $result = Google_Http_CacheParser::isResponseCacheable($resp); + $this->assertFalse($result); + + // The response has expired, and we don't have an etag for + // revalidation. + $resp = new Google_Http_Request('http://localhost', 'GET'); + $resp->setResponseHttpCode('200'); + $resp->setResponseHeaders( + array( + 'Cache-Control' => 'max-age=3600, must-revalidate', + 'Expires' => 'Fri, 30 Oct 1998 14:19:41 GMT', + 'Date' => 'Mon, 29 Jun 1998 02:28:12 GMT', + 'Last-Modified' => 'Mon, 29 Jun 1998 02:28:12 GMT', + ) + ); + $result = Google_Http_CacheParser::isResponseCacheable($resp); + $this->assertFalse($result); + + // Verify cacheable responses. + $resp = new Google_Http_Request('http://localhost', 'GET'); + $resp->setResponseHttpCode('200'); + $resp->setResponseHeaders( + array( + 'Cache-Control' => 'max-age=3600, must-revalidate', + 'Expires' => 'Fri, 30 Oct 2013 14:19:41 GMT', + 'Date' => 'Mon, 29 Jun 2011 02:28:12 GMT', + 'Last-Modified' => 'Mon, 29 Jun 2011 02:28:12 GMT', + 'ETag' => '3e86-410-3596fbbc', + ) + ); + $result = Google_Http_CacheParser::isResponseCacheable($resp); + $this->assertTrue($result); + + // Verify that responses to HEAD requests are cacheable. + $resp = new Google_Http_Request('http://localhost', 'HEAD'); + $resp->setResponseHttpCode('200'); + $resp->setResponseBody(null); + $resp->setResponseHeaders( + array( + 'Cache-Control' => 'max-age=3600, must-revalidate', + 'Expires' => 'Fri, 30 Oct 2013 14:19:41 GMT', + 'Date' => 'Mon, 29 Jun 2011 02:28:12 GMT', + 'Last-Modified' => 'Mon, 29 Jun 2011 02:28:12 GMT', + 'ETag' => '3e86-410-3596fbbc', + ) + ); + $result = Google_Http_CacheParser::isResponseCacheable($resp); + $this->assertTrue($result); + + // Verify that Vary: * cannot get cached. + $resp = new Google_Http_Request('http://localhost', 'GET'); + $resp->setResponseHttpCode('200'); + $resp->setResponseHeaders( + array( + 'Cache-Control' => 'max-age=3600, must-revalidate', + 'Expires' => 'Fri, 30 Oct 2013 14:19:41 GMT', + 'Date' => 'Mon, 29 Jun 2011 02:28:12 GMT', + 'Last-Modified' => 'Mon, 29 Jun 2011 02:28:12 GMT', + 'Vary' => 'foo', + 'ETag' => '3e86-410-3596fbbc', + ) + ); + $result = Google_Http_CacheParser::isResponseCacheable($resp); + $this->assertFalse($result); + + // Verify 201s cannot get cached. + $resp = new Google_Http_Request('http://localhost', 'GET'); + $resp->setResponseHttpCode('201'); + $resp->setResponseBody(null); + $resp->setResponseHeaders( + array( + 'Cache-Control' => 'max-age=3600, must-revalidate', + 'Expires' => 'Fri, 30 Oct 2013 14:19:41 GMT', + 'Last-Modified' => 'Mon, 29 Jun 2011 02:28:12 GMT', + 'ETag' => '3e86-410-3596fbbc', + ) + ); + $result = Google_Http_CacheParser::isResponseCacheable($resp); + $this->assertFalse($result); + + // Verify pragma: no-cache. + $resp = new Google_Http_Request('http://localhost', 'GET'); + $resp->setResponseHttpCode('200'); + $resp->setResponseHeaders( + array( + 'Expires' => 'Wed, 11 Jan 2012 04:03:37 GMT', + 'Date' => 'Wed, 11 Jan 2012 04:03:37 GMT', + 'Pragma' => 'no-cache', + 'Cache-Control' => 'private, max-age=0, must-revalidate, no-transform', + 'ETag' => '3e86-410-3596fbbc', + ) + ); + $result = Google_Http_CacheParser::isResponseCacheable($resp); + $this->assertFalse($result); + + // Verify Cache-Control: no-store. + $resp = new Google_Http_Request('http://localhost', 'GET'); + $resp->setResponseHttpCode('200'); + $resp->setResponseHeaders( + array( + 'Expires' => 'Wed, 11 Jan 2012 04:03:37 GMT', + 'Date' => 'Wed, 11 Jan 2012 04:03:37 GMT', + 'Cache-Control' => 'no-store', + 'ETag' => '3e86-410-3596fbbc', + ) + ); + $result = Google_Http_CacheParser::isResponseCacheable($resp); + $this->assertFalse($result); + + // Verify that authorized responses are not cacheable. + $resp = new Google_Http_Request('http://localhost', 'GET'); + $resp->setRequestHeaders(array('Authorization' => 'Bearer Token')); + $resp->setResponseHttpCode('200'); + $resp->setResponseHeaders( + array( + 'Cache-Control' => 'max-age=3600, must-revalidate', + 'Expires' => 'Fri, 30 Oct 2013 14:19:41 GMT', + 'Last-Modified' => 'Mon, 29 Jun 2011 02:28:12 GMT', + 'ETag' => '3e86-410-3596fbbc', + ) + ); + $result = Google_Http_CacheParser::isResponseCacheable($resp); + $this->assertFalse($result); + } + + public function testIsExpired() + { + $now = time(); + $future = $now + (365 * 24 * 60 * 60); + $client = $this->getClient(); + + // Expires 1 year in the future. Response is fresh. + $resp = new Google_Http_Request('http://localhost', 'GET'); + $resp->setResponseHttpCode('200'); + $resp->setResponseHeaders( + array( + 'Expires' => gmdate('D, d M Y H:i:s', $future) . ' GMT', + 'Date' => gmdate('D, d M Y H:i:s', $now) . ' GMT', + ) + ); + $this->assertFalse(Google_Http_CacheParser::isExpired($resp)); + + // The response expires soon. Response is fresh. + $resp = new Google_Http_Request('http://localhost', 'GET'); + $resp->setResponseHttpCode('200'); + $resp->setResponseHeaders( + array( + 'Expires' => gmdate('D, d M Y H:i:s', $now + 2) . ' GMT', + 'Date' => gmdate('D, d M Y H:i:s', $now) . ' GMT', + ) + ); + $this->assertFalse(Google_Http_CacheParser::isExpired($resp)); + + // Expired 1 year ago. Response is stale. + $past = $now - (365 * 24 * 60 * 60); + $resp = new Google_Http_Request('http://localhost', 'GET'); + $resp->setResponseHttpCode('200'); + $resp->setResponseHeaders( + array( + 'Expires' => gmdate('D, d M Y H:i:s', $past) . ' GMT', + 'Date' => gmdate('D, d M Y H:i:s', $now) . ' GMT', + ) + ); + $this->assertTrue(Google_Http_CacheParser::isExpired($resp)); + + // Invalid expires header. Response is stale. + $resp = new Google_Http_Request('http://localhost', 'GET'); + $resp->setResponseHttpCode('200'); + $resp->setResponseHeaders( + array( + 'Expires' => '-1', + 'Date' => gmdate('D, d M Y H:i:s', $now) . ' GMT', + ) + ); + $this->assertTrue(Google_Http_CacheParser::isExpired($resp)); + + // The response expires immediately. G+ APIs do this. Response is stale. + $resp = new Google_Http_Request('http://localhost', 'GET'); + $resp->setResponseHttpCode('200'); + $resp->setResponseHeaders( + array( + 'Expires' => gmdate('D, d M Y H:i:s', $now) . ' GMT', + 'Date' => gmdate('D, d M Y H:i:s', $now) . ' GMT', + ) + ); + $this->assertTrue(Google_Http_CacheParser::isExpired($resp)); + } + + public function testMustRevalidate() + { + $now = time(); + $client = $this->getClient(); + + // Expires 1 year in the future, and contains the must-revalidate directive. + // Don't revalidate. must-revalidate only applies to expired entries. + $future = $now + (365 * 24 * 60 * 60); + $resp = new Google_Http_Request('http://localhost', 'GET'); + $resp->setResponseHttpCode('200'); + $resp->setResponseHeaders( + array( + 'Cache-Control' => 'max-age=3600, must-revalidate', + 'Expires' => gmdate('D, d M Y H:i:s', $future) . ' GMT', + 'Date' => gmdate('D, d M Y H:i:s', $now) . ' GMT', + ) + ); + $this->assertFalse(Google_Http_CacheParser::mustRevalidate($resp)); + + // Contains the max-age=3600 directive, but was created 2 hours ago. + // Must revalidate. + $past = $now - (2 * 60 * 60); + $resp = new Google_Http_Request('http://localhost', 'GET'); + $resp->setResponseHttpCode('200'); + $resp->setResponseHeaders( + array( + 'Cache-Control' => 'max-age=3600', + 'Expires' => gmdate('D, d M Y H:i:s', $future) . ' GMT', + 'Date' => gmdate('D, d M Y H:i:s', $past) . ' GMT', + ) + ); + $this->assertTrue(Google_Http_CacheParser::mustRevalidate($resp)); + + // Contains the max-age=3600 directive, and was created 600 seconds ago. + // No need to revalidate, regardless of the expires header. + $past = $now - (600); + $resp = new Google_Http_Request('http://localhost', 'GET'); + $resp->setResponseHttpCode('200'); + $resp->setResponseHeaders( + array( + 'Cache-Control' => 'max-age=3600', + 'Expires' => gmdate('D, d M Y H:i:s', $past) . ' GMT', + 'Date' => gmdate('D, d M Y H:i:s', $past) . ' GMT', + ) + ); + $this->assertFalse(Google_Http_CacheParser::mustRevalidate($resp)); + } +} diff --git a/includes/google-api-php-client-master/tests/general/ApiClientTest.php b/includes/google-api-php-client-master/tests/general/ApiClientTest.php new file mode 100644 index 0000000..5d455c2 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/ApiClientTest.php @@ -0,0 +1,212 @@ +<?php +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +class ApiClientTest extends BaseTest +{ + public function testClient() + { + $client = new Google_Client(); + $client->setAccessType('foo'); + $client->setDeveloperKey('foo'); + $req = new Google_Http_Request('http://foo.com'); + $client->getAuth()->sign($req); + $params = $req->getQueryParams(); + $this->assertEquals('foo', $params['key']); + + $client->setAccessToken(json_encode(array('access_token' => '1'))); + $this->assertEquals("{\"access_token\":\"1\"}", $client->getAccessToken()); + } + + public function testClientConstructor() + { + $this->assertInstanceOf('Google_Client', $this->getClient()); + } + + /** + * @expectedException Google_Auth_Exception + */ + public function testPrepareInvalidScopes() + { + $client = new Google_Client(); + + $scopes = $client->prepareScopes(); + $this->assertEquals("", $scopes); + } + + public function testNoAuthIsNull() + { + $client = new Google_Client(); + + $this->assertNull($client->getAccessToken()); + } + + public function testPrepareService() + { + $client = new Google_Client(); + $client->setScopes(array("scope1", "scope2")); + $scopes = $client->prepareScopes(); + $this->assertEquals("scope1 scope2", $scopes); + + $client->setScopes(array("", "scope2")); + $scopes = $client->prepareScopes(); + $this->assertEquals(" scope2", $scopes); + + $client->setScopes("scope2"); + $client->addScope("scope3"); + $client->addScope(array("scope4", "scope5")); + $scopes = $client->prepareScopes(); + $this->assertEquals("scope2 scope3 scope4 scope5", $scopes); + + $client->setClientId('test1'); + $client->setRedirectUri('http://localhost/'); + $client->setScopes(array("http://test.com", "scope2")); + $scopes = $client->prepareScopes(); + $this->assertEquals("http://test.com scope2", $scopes); + $this->assertEquals( + '' + . 'https://accounts.google.com/o/oauth2/auth' + . '?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2F' + . '&client_id=test1' + . '&scope=http%3A%2F%2Ftest.com+scope2&access_type=online' + . '&approval_prompt=auto', + $client->createAuthUrl() + ); + + // This should not trigger a request. + $client->setDefer(true); + $dr_service = new Google_Service_Drive($client); + $this->assertInstanceOf('Google_Http_Request', $dr_service->files->listFiles()); + } + + public function testSettersGetters() + { + $client = new Google_Client(); + $client->setClientId("client1"); + $client->setClientSecret('client1secret'); + $client->setState('1'); + $client->setApprovalPrompt('force'); + $client->setAccessType('offline'); + + $client->setRedirectUri('localhost'); + $client->setApplicationName('me'); + $this->assertEquals('object', gettype($client->getAuth())); + $this->assertEquals('object', gettype($client->getCache())); + $this->assertEquals('object', gettype($client->getIo())); + + $client->setAuth(new Google_Auth_Simple($client)); + $client->setAuth(new Google_Auth_OAuth2($client)); + + try { + $client->setAccessToken(null); + die('Should have thrown an Google_Auth_Exception.'); + } catch (Google_Auth_Exception $e) { + $this->assertEquals('Could not json decode the token', $e->getMessage()); + } + + $token = json_encode(array('access_token' => 'token')); + $client->setAccessToken($token); + $this->assertEquals($token, $client->getAccessToken()); + } + + /** + * @requires extension Memcached + */ + public function testAppEngineAutoConfig() + { + $_SERVER['SERVER_SOFTWARE'] = 'Google App Engine'; + $client = new Google_Client(); + $this->assertInstanceOf('Google_Cache_Memcache', $client->getCache()); + $this->assertInstanceOf('Google_Io_Stream', $client->getIo()); + unset($_SERVER['SERVER_SOFTWARE']); + } + + public function testJsonConfig() + { + // Device config + $config = new Google_Config(); + $client = new Google_Client($config); + $device = + '{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret"'. + ':"N0aHCBT1qX1VAcF5J1pJAn6S","token_uri":"https://accounts.google.com/o/oauth2/token",'. + '"client_email":"","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","oob"],"client_x509_cert_url"'. + ':"","client_id":"123456789.apps.googleusercontent.com","auth_provider_x509_cert_url":'. + '"https://www.googleapis.com/oauth2/v1/certs"}}'; + $dObj = json_decode($device); + $client->setAuthConfig($device); + $cfg = $config->getClassConfig('Google_Auth_OAuth2'); + $this->assertEquals($cfg['client_id'], $dObj->installed->client_id); + $this->assertEquals($cfg['client_secret'], $dObj->installed->client_secret); + $this->assertEquals($cfg['redirect_uri'], $dObj->installed->redirect_uris[0]); + + // Web config + $config = new Google_Config(); + $client = new Google_Client($config); + $web = '{"web":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret"' . + ':"lpoubuib8bj-Fmke_YhhyHGgXc","token_uri":"https://accounts.google.com/o/oauth2/token"' . + ',"client_email":"123456789@developer.gserviceaccount.com","client_x509_cert_url":'. + '"https://www.googleapis.com/robot/v1/metadata/x509/123456789@developer.gserviceaccount.com"'. + ',"client_id":"123456789.apps.googleusercontent.com","auth_provider_x509_cert_url":'. + '"https://www.googleapis.com/oauth2/v1/certs"}}'; + $wObj = json_decode($web); + $client->setAuthConfig($web); + $cfg = $config->getClassConfig('Google_Auth_OAuth2'); + $this->assertEquals($cfg['client_id'], $wObj->web->client_id); + $this->assertEquals($cfg['client_secret'], $wObj->web->client_secret); + $this->assertEquals($cfg['redirect_uri'], ''); + } + + public function testIniConfig() + { + $config = new Google_Config(__DIR__ . "/testdata/test.ini"); + $this->assertEquals('My Test application', $config->getApplicationName()); + $this->assertEquals( + 'gjfiwnGinpena3', + $config->getClassConfig('Google_Auth_OAuth2', 'client_secret') + ); + $this->assertInternalType( + 'array', + $config->getClassConfig('Google_IO_Abstract') + ); + $this->assertEquals( + 100, + $config->getClassConfig('Google_IO_Abstract', 'request_timeout_seconds') + ); + } + + public function testServiceAccountJson() + { + $client = new Google_Client(); + $c = $client->loadServiceAccountJson( + __DIR__ . "/testdata/service-12345.json", + array() + ); + $this->assertInstanceOf('Google_Auth_AssertionCredentials', $c); + } + + public function testRsaServiceAccountJson() + { + $client = new Google_Client(); + $c = $client->loadServiceAccountJson( + __DIR__ . "/testdata/service-rsa-12345.json", + array() + ); + $this->assertInstanceOf('Google_Auth_AssertionCredentials', $c); + } +} diff --git a/includes/google-api-php-client-master/tests/general/ApiMediaFileUploadTest.php b/includes/google-api-php-client-master/tests/general/ApiMediaFileUploadTest.php new file mode 100644 index 0000000..e43cf76 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/ApiMediaFileUploadTest.php @@ -0,0 +1,92 @@ +<?php +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +class ApiMediaFileUploadTest extends BaseTest +{ + public function testMediaFile() + { + $client = $this->getClient(); + $request = new Google_Http_Request('http://www.example.com', 'POST'); + $media = new Google_Http_MediaFileUpload( + $client, + $request, + 'image/png', + base64_decode('data:image/png;base64,a') + ); + + $this->assertEquals(0, $media->getProgress()); + $this->assertGreaterThan(0, strlen($request->getPostBody())); + } + + public function testGetUploadType() + { + $client = $this->getClient(); + $request = new Google_Http_Request('http://www.example.com', 'POST'); + + // Test resumable upload + $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', 'a', true); + $params = array('mediaUpload' => array('value' => $media)); + $this->assertEquals('resumable', $media->getUploadType(null)); + + // Test data *only* uploads + $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', 'a', false); + $this->assertEquals('media', $media->getUploadType(null)); + + // Test multipart uploads + $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', 'a', false); + $this->assertEquals('multipart', $media->getUploadType(array('a' => 'b'))); + } + + public function testResultCode() + { + $client = $this->getClient(); + $request = new Google_Http_Request('http://www.example.com', 'POST'); + + // Test resumable upload + $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', 'a', true); + $this->assertEquals(null, $media->getHttpResultCode()); + } + + public function testProcess() + { + $client = $this->getClient(); + $data = 'foo'; + + // Test data *only* uploads. + $request = new Google_Http_Request('http://www.example.com', 'POST'); + $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', $data, false); + $this->assertEquals($data, $request->getPostBody()); + + // Test resumable (meta data) - we want to send the metadata, not the app data. + $request = new Google_Http_Request('http://www.example.com', 'POST'); + $reqData = json_encode("hello"); + $request->setPostBody($reqData); + $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', $data, true); + $this->assertEquals(json_decode($reqData), $request->getPostBody()); + + // Test multipart - we are sending encoded meta data and post data + $request = new Google_Http_Request('http://www.example.com', 'POST'); + $reqData = json_encode("hello"); + $request->setPostBody($reqData); + $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', $data, false); + $this->assertContains($reqData, $request->getPostBody()); + $this->assertContains(base64_encode($data), $request->getPostBody()); + } +} diff --git a/includes/google-api-php-client-master/tests/general/ApiModelTest.php b/includes/google-api-php-client-master/tests/general/ApiModelTest.php new file mode 100644 index 0000000..9a81e71 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/ApiModelTest.php @@ -0,0 +1,189 @@ +<?php +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +class ApiModelTest extends BaseTest +{ + private $calendarData = '{ + "kind": "calendar#event", + "etag": "\"-kteSF26GsdKQ5bfmcd4H3_-u3g/MTE0NTUyNTAxOTk0MjAwMA\"", + "id": "1234566", + "status": "confirmed", + "htmlLink": "https://www.google.com/calendar/event?eid=N", + "created": "2006-04-13T14:22:08.000Z", + "updated": "2006-04-20T09:23:39.942Z", + "summary": "Evening Jolt Q3 CTFL", + "description": "6.30 - Adminning\n9.30 - Game", + "creator": { + "email": "ian@example.com", + "displayName": "Ian Test", + "self": true + }, + "organizer": { + "email": "ian@example.com", + "displayName": "Ian Test", + "self": true + }, + "start": { + "date": "2006-04-23" + }, + "end": { + "date": "2006-04-24" + }, + "iCalUID": "5gi2ac493nnrfdfd7jhesafget8@google.com", + "sequence": 0, + "reminders": { + "useDefault": false + } + }'; + + public function testIntentionalNulls() + { + $data = json_decode($this->calendarData, true); + $event = new Google_Service_Calendar_Event($data); + $obj = json_decode(json_encode($event->toSimpleObject()), true); + $this->assertArrayHasKey('date', $obj['start']); + $this->assertArrayNotHasKey('dateTime', $obj['start']); + $date = new Google_Service_Calendar_EventDateTime(); + $date->setDate(Google_Model::NULL_VALUE); + $event->setStart($date); + $obj = json_decode(json_encode($event->toSimpleObject()), true); + $this->assertNull($obj['start']['date']); + $this->assertArrayHasKey('date', $obj['start']); + $this->assertArrayNotHasKey('dateTime', $obj['start']); + } + public function testModelMutation() + { + $data = json_decode($this->calendarData, true); + $event = new Google_Service_Calendar_Event($data); + $date = new Google_Service_Calendar_EventDateTime(); + date_default_timezone_set('UTC'); + $dateString = Date("c"); + $summary = "hello"; + $date->setDate($dateString); + $event->setStart($date); + $event->setEnd($date); + $event->setSummary($summary); + $simpleEvent = $event->toSimpleObject(); + $this->assertEquals($dateString, $simpleEvent->start->date); + $this->assertEquals($dateString, $simpleEvent->end->date); + $this->assertEquals($summary, $simpleEvent->summary); + + $event2 = new Google_Service_Calendar_Event(); + $this->assertNull($event2->getStart()); + } + + public function testVariantTypes() + { + $feature = new Google_Service_MapsEngine_Feature(); + $geometry = new Google_Service_MapsEngine_GeoJsonPoint(); + $geometry->setCoordinates(array(1, 0)); + $feature->setGeometry($geometry); + $data = json_decode(json_encode($feature->toSimpleObject()), true); + $this->assertEquals('Point', $data['geometry']['type']); + $this->assertEquals(1, $data['geometry']['coordinates'][0]); + } + + public function testOddMappingNames() + { + $creative = new Google_Service_AdExchangeBuyer_Creative(); + $creative->setAccountId('12345'); + $creative->setBuyerCreativeId('12345'); + $creative->setAdvertiserName('Hi'); + $creative->setHTMLSnippet("<p>Foo!</p>"); + $creative->setClickThroughUrl(array('http://somedomain.com')); + $creative->setWidth(100); + $creative->setHeight(100); + $data = json_decode(json_encode($creative->toSimpleObject()), true); + $this->assertEquals($data['HTMLSnippet'], "<p>Foo!</p>"); + $this->assertEquals($data['width'], 100); + $this->assertEquals($data['height'], 100); + $this->assertEquals($data['accountId'], "12345"); + } + + public function testJsonStructure() + { + $model = new Google_Model(); + $model->publicA = "This is a string"; + $model2 = new Google_Model(); + $model2->publicC = 12345; + $model2->publicD = null; + $model->publicB = $model2; + $model3 = new Google_Model(); + $model3->publicE = 54321; + $model3->publicF = null; + $model->publicG = array($model3, "hello", false); + $model->publicH = false; + $model->publicI = 0; + $string = json_encode($model->toSimpleObject()); + $data = json_decode($string, true); + $this->assertEquals(12345, $data['publicB']['publicC']); + $this->assertEquals("This is a string", $data['publicA']); + $this->assertArrayNotHasKey("publicD", $data['publicB']); + $this->assertArrayHasKey("publicE", $data['publicG'][0]); + $this->assertArrayNotHasKey("publicF", $data['publicG'][0]); + $this->assertEquals("hello", $data['publicG'][1]); + $this->assertEquals(false, $data['publicG'][2]); + $this->assertArrayNotHasKey("data", $data); + $this->assertEquals(false, $data['publicH']); + $this->assertEquals(0, $data['publicI']); + } + + public function testIssetPropertyOnModel() + { + $model = new Google_Model(); + $model['foo'] = 'bar'; + $this->assertTrue(isset($model->foo)); + } + + public function testUnsetPropertyOnModel() + { + $model = new Google_Model(); + $model['foo'] = 'bar'; + unset($model->foo); + $this->assertFalse(isset($model->foo)); + } + + public function testCollection() + { + $data = json_decode( + '{ + "kind": "calendar#events", + "id": "1234566", + "etag": "abcdef", + "totalItems": 4, + "items": [ + {"id": 1}, + {"id": 2}, + {"id": 3}, + {"id": 4} + ] + }', + true + ); + $collection = new Google_Service_Calendar_Events($data); + $this->assertEquals(4, count($collection)); + $count = 0; + foreach ($collection as $col) { + $count++; + } + $this->assertEquals(4, $count); + $this->assertEquals(1, $collection[0]->id); + } +} diff --git a/includes/google-api-php-client-master/tests/general/ApiOAuth2Test.php b/includes/google-api-php-client-master/tests/general/ApiOAuth2Test.php new file mode 100644 index 0000000..768478c --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/ApiOAuth2Test.php @@ -0,0 +1,256 @@ +<?php +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +class ApiOAuth2Test extends BaseTest +{ + + public function testSign() + { + $client = $this->getClient(); + $oauth = new Google_Auth_OAuth2($client); + + $client->setClientId('clientId1'); + $client->setClientSecret('clientSecret1'); + $client->setRedirectUri('http://localhost'); + $client->setDeveloperKey('devKey'); + $client->setAccessType('offline'); + $client->setApprovalPrompt('force'); + $client->setRequestVisibleActions('http://foo'); + + $req = new Google_Http_Request('http://localhost'); + $req = $oauth->sign($req); + + $this->assertEquals('http://localhost?key=devKey', $req->getUrl()); + + // test accessToken + $oauth->setAccessToken( + json_encode( + array( + 'access_token' => 'ACCESS_TOKEN', + 'created' => time(), + 'expires_in' => '3600' + ) + ) + ); + + $req = $oauth->sign($req); + $auth = $req->getRequestHeader('authorization'); + $this->assertEquals('Bearer ACCESS_TOKEN', $auth); + } + + public function testRevokeAccess() + { + $accessToken = "ACCESS_TOKEN"; + $refreshToken = "REFRESH_TOKEN"; + $accessToken2 = "ACCESS_TOKEN_2"; + $token = ""; + + $client = $this->getClient(); + $response = $this->getMock("Google_Http_Request", array(), array('')); + $response->expects($this->any()) + ->method('getResponseHttpCode') + ->will($this->returnValue(200)); + $io = $this->getMock("Google_IO_Stream", array(), array($client)); + $io->expects($this->any()) + ->method('makeRequest') + ->will( + $this->returnCallback( + function ($request) use (&$token, $response) { + $elements = array(); + parse_str($request->getPostBody(), $elements); + $token = isset($elements['token']) ? $elements['token'] : null; + return $response; + } + ) + ); + $client->setIo($io); + + // Test with access token. + $oauth = new Google_Auth_OAuth2($client); + $oauth->setAccessToken( + json_encode( + array( + 'access_token' => $accessToken, + 'created' => time(), + 'expires_in' => '3600' + ) + ) + ); + $this->assertTrue($oauth->revokeToken()); + $this->assertEquals($accessToken, $token); + + // Test with refresh token. + $oauth = new Google_Auth_OAuth2($client); + $oauth->setAccessToken( + json_encode( + array( + 'access_token' => $accessToken, + 'refresh_token' => $refreshToken, + 'created' => time(), + 'expires_in' => '3600' + ) + ) + ); + $this->assertTrue($oauth->revokeToken()); + $this->assertEquals($refreshToken, $token); + + // Test with passed in token. + $this->assertTrue($oauth->revokeToken($accessToken2)); + $this->assertEquals($accessToken2, $token); + } + + public function testCreateAuthUrl() + { + $client = $this->getClient(); + $oauth = new Google_Auth_OAuth2($client); + + $client->setClientId('clientId1'); + $client->setClientSecret('clientSecret1'); + $client->setRedirectUri('http://localhost'); + $client->setDeveloperKey('devKey'); + $client->setAccessType('offline'); + $client->setApprovalPrompt('force'); + $client->setRequestVisibleActions(array('http://foo')); + $client->setLoginHint("bob@example.org"); + + $authUrl = $oauth->createAuthUrl("http://googleapis.com/scope/foo"); + $expected = "https://accounts.google.com/o/oauth2/auth" + . "?response_type=code" + . "&redirect_uri=http%3A%2F%2Flocalhost" + . "&client_id=clientId1" + . "&scope=http%3A%2F%2Fgoogleapis.com%2Fscope%2Ffoo" + . "&access_type=offline" + . "&approval_prompt=force" + . "&login_hint=bob%40example.org"; + $this->assertEquals($expected, $authUrl); + + // Again with a blank login hint (should remove all traces from authUrl) + $client->setLoginHint(""); + $client->setHostedDomain("example.com"); + $client->setOpenidRealm("example.com"); + $client->setPrompt("select_account"); + $client->setIncludeGrantedScopes(true); + $authUrl = $oauth->createAuthUrl("http://googleapis.com/scope/foo"); + $expected = "https://accounts.google.com/o/oauth2/auth" + . "?response_type=code" + . "&redirect_uri=http%3A%2F%2Flocalhost" + . "&client_id=clientId1" + . "&scope=http%3A%2F%2Fgoogleapis.com%2Fscope%2Ffoo" + . "&access_type=offline" + . "&prompt=select_account" + . "&hd=example.com" + . "&openid.realm=example.com" + . "&include_granted_scopes=true"; + $this->assertEquals($expected, $authUrl); + } + + /** + * Most of the logic for ID token validation is in AuthTest - + * this is just a general check to ensure we verify a valid + * id token if one exists. + */ + public function testValidateIdToken() + { + if (!$this->checkToken()) { + return; + } + + $client = $this->getClient(); + $token = json_decode($client->getAccessToken()); + $segments = explode(".", $token->id_token); + $this->assertEquals(3, count($segments)); + // Extract the client ID in this case as it wont be set on the test client. + $data = json_decode(Google_Utils::urlSafeB64Decode($segments[1])); + $oauth = new Google_Auth_OAuth2($client); + $ticket = $oauth->verifyIdToken($token->id_token, $data->aud); + $this->assertInstanceOf( + "Google_Auth_LoginTicket", + $ticket + ); + $this->assertTrue(strlen($ticket->getUserId()) > 0); + + // TODO(ianbarber): Need to be smart about testing/disabling the + // caching for this test to make sense. Not sure how to do that + // at the moment. + $client = $this->getClient(); + $client->setIo(new Google_IO_Stream($client)); + $data = json_decode(Google_Utils::urlSafeB64Decode($segments[1])); + $oauth = new Google_Auth_OAuth2($client); + $this->assertInstanceOf( + "Google_Auth_LoginTicket", + $oauth->verifyIdToken($token->id_token, $data->aud) + ); + } + + /** + * Test for revoking token when none is opened + */ + public function testRevokeWhenNoTokenExists() + { + $client = new Google_Client(); + $this->assertFalse($client->revokeToken()); + } + + /** + * Test that the ID token is properly refreshed. + */ + public function testRefreshTokenSetsValues() + { + $client = new Google_Client(); + $response_data = json_encode( + array( + 'access_token' => "ACCESS_TOKEN", + 'id_token' => "ID_TOKEN", + 'expires_in' => "12345", + ) + ); + $response = $this->getMock("Google_Http_Request", array(), array('')); + $response->expects($this->any()) + ->method('getResponseHttpCode') + ->will($this->returnValue(200)); + $response->expects($this->any()) + ->method('getResponseBody') + ->will($this->returnValue($response_data)); + $io = $this->getMock("Google_IO_Stream", array(), array($client)); + $io->expects($this->any()) + ->method('makeRequest') + ->will( + $this->returnCallback( + function ($request) use (&$token, $response) { + $elements = $request->getPostBody(); + PHPUnit_Framework_TestCase::assertEquals( + $elements['grant_type'], + "refresh_token" + ); + PHPUnit_Framework_TestCase::assertEquals( + $elements['refresh_token'], + "REFRESH_TOKEN" + ); + return $response; + } + ) + ); + $client->setIo($io); + $oauth = new Google_Auth_OAuth2($client); + $oauth->refreshToken("REFRESH_TOKEN"); + $token = json_decode($oauth->getAccessToken(), true); + $this->assertEquals($token['id_token'], "ID_TOKEN"); + } +} diff --git a/includes/google-api-php-client-master/tests/general/AuthTest.php b/includes/google-api-php-client-master/tests/general/AuthTest.php new file mode 100644 index 0000000..9832a34 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/AuthTest.php @@ -0,0 +1,330 @@ +<?php +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +class AuthTest extends BaseTest +{ + const PRIVATE_KEY_FILE = "testdata/cert.p12"; + const PUBLIC_KEY_FILE_JSON = "testdata/cacert.json"; + const PUBLIC_KEY_FILE = "testdata/cacert.pem"; + const USER_ID = "102102479283111695822"; + + /** @var Google_Signer_P12 */ + private $signer; + + /** @var string */ + private $pem; + + /** @var Google_Verifier_Pem */ + private $verifier; + + public function setUp() + { + $this->signer = new Google_Signer_P12( + file_get_contents(__DIR__.'/'.self::PRIVATE_KEY_FILE, true), + "notasecret" + ); + $this->pem = file_get_contents(__DIR__.'/'.self::PUBLIC_KEY_FILE, true); + $this->verifier = new Google_Verifier_Pem($this->pem); + } + + public function testDirectInject() + { + $privateKeyString = <<<PK +-----BEGIN RSA PRIVATE KEY----- +MIICWwIBAAKBgQC8iqFTYTrSGxddW+Tsx6cdWbQxITdM2anRbMYcohnQpQuPG46B +HO3WbUA8suC6PXqeIi4JkDrAYbI2+TN6w1FE/fh2H7WczuDVKtosBcfsoL2C5loU +mOf+4jL1xx4EL6xy8wMntZhNgimVCO9LkWCix/Qh9mpqx2zbC3OV4QsSQQIDAQAB +AoGASAosRCClifxB/DENko9iwisxV4haiemtIlEOjYg+luNJPGAKHjlAgyrxXX/3 +sBGnlV53+r16RWHO54RmcCTLGwpC6zzVc6C4Or9KItdMDMnqBjmqiYDz3Na7tIPv +vwzn8k8Uto26HZF8d1bTdoinxHrv7w1OVkDQWnHmWkQRjBUCQQDpNw8F1qiJJoYr +tkkBmlObmSQRYD3mlEvRwu348e4dFb01oN2cfw/YNhh+Lt2TPHFz2GNn6VwJf1Yb +qRKBqo/jAkEAzvY91ReYrkBm50pi2nqJc1Hcxm5CVP7MMnHbn8wExKrRG2rCDY9Y +zOdsw7pP/x6mesdUy3tTrPYVbeWP6YPmiwJANx41Jbsa7/cz5KbbUE6qDe8+sACg +AJvx42x/k8OR9DvMER2o4rDBDOeUGFZ5NbAmXCu7KrbjcrcuobDu18h44wJAQ2s5 +x0HxjcoS+4Ni4nMKdZOUTNu8Jf3+vOwUNGD8qKhQiBLl9g7dSZqV9sipqJzudI6c +k9Cv+GcNoggnMlWycwJAHMVgaBmNc+RVCMar/gN6i5sENjN9Itu7U1V4Qj/mG6+4 +MHOXhXSKhtTe0Bqm/MssVvCmc8AraKwBMs0rkMadsA== +-----END RSA PRIVATE KEY----- +PK; + $sign = new Google_Signer_P12($privateKeyString, null); + } + + public function testCantOpenP12() + { + try { + new Google_Signer_P12( + file_get_contents(__DIR__.'/'.self::PRIVATE_KEY_FILE, true), + "badpassword" + ); + $this->fail("Should have thrown"); + } catch (Google_Auth_Exception $e) { + $this->assertContains("mac verify failure", $e->getMessage()); + } + + try { + new Google_Signer_P12( + file_get_contents(__DIR__.'/'.self::PRIVATE_KEY_FILE, true) . "foo", + "badpassword" + ); + $this->fail("Should have thrown"); + } catch (Exception $e) { + $this->assertContains("Unable to parse", $e->getMessage()); + } + } + + public function testVerifySignature() + { + $binary_data = "\x00\x01\x02\x66\x6f\x6f"; + $signature = $this->signer->sign($binary_data); + $this->assertTrue($this->verifier->verify($binary_data, $signature)); + + $empty_string = ""; + $signature = $this->signer->sign($empty_string); + $this->assertTrue($this->verifier->verify($empty_string, $signature)); + + $text = "foobar"; + $signature = $this->signer->sign($text); + $this->assertTrue($this->verifier->verify($text, $signature)); + + $this->assertFalse($this->verifier->verify($empty_string, $signature)); + } + + // Creates a signed JWT similar to the one created by google authentication. + private function makeSignedJwt($payload) + { + $header = array("typ" => "JWT", "alg" => "RS256"); + $segments = array(); + $segments[] = Google_Utils::urlSafeB64Encode(json_encode($header)); + $segments[] = Google_Utils::urlSafeB64Encode(json_encode($payload)); + $signing_input = implode(".", $segments); + + $signature = $this->signer->sign($signing_input); + $segments[] = Google_Utils::urlSafeB64Encode($signature); + + return implode(".", $segments); + } + + // Returns certificates similar to the ones used by google authentication. + private function getSignonCerts() + { + return array("keyid" => $this->pem); + } + + public function testVerifySignedJwtWithCerts() + { + $id_token = $this->makeSignedJwt( + array( + "iss" => "federated-signon@system.gserviceaccount.com", + "aud" => "client_id", + "sub" => self::USER_ID, + "iat" => time(), + "exp" => time() + 3600 + ) + ); + $certs = $this->getSignonCerts(); + $oauth2 = new Google_Auth_OAuth2($this->getClient()); + $ticket = $oauth2->verifySignedJwtWithCerts($id_token, $certs, "client_id"); + $this->assertEquals(self::USER_ID, $ticket->getUserId()); + // Check that payload and envelope got filled in. + $attributes = $ticket->getAttributes(); + $this->assertEquals("JWT", $attributes["envelope"]["typ"]); + $this->assertEquals("client_id", $attributes["payload"]["aud"]); + } + + // Checks that the id token fails to verify with the expected message. + private function checkIdTokenFailure($id_token, $msg) + { + $certs = $this->getSignonCerts(); + $oauth2 = new Google_Auth_OAuth2($this->getClient()); + try { + $oauth2->verifySignedJwtWithCerts($id_token, $certs, "client_id"); + $this->fail("Should have thrown for $id_token"); + } catch (Google_Auth_Exception $e) { + $this->assertContains($msg, $e->getMessage()); + } + } + + public function testVerifySignedJwtWithBadJwt() + { + $this->checkIdTokenFailure("foo", "Wrong number of segments"); + $this->checkIdTokenFailure("foo.bar", "Wrong number of segments"); + $this->checkIdTokenFailure( + "foo.bar.baz", + "Can't parse token envelope: foo" + ); + } + + public function testVerifySignedJwtWithBadSignature() + { + $id_token = $this->makeSignedJwt( + array( + "iss" => "federated-signon@system.gserviceaccount.com", + "aud" => "client_id", + "id" => self::USER_ID, + "iat" => time(), + "exp" => time() + 3600 + ) + ); + $id_token = $id_token . "a"; + $this->checkIdTokenFailure($id_token, "Invalid token signature"); + } + + public function testVerifySignedJwtWithNoIssueTime() + { + $id_token = $this->makeSignedJwt( + array( + "iss" => "federated-signon@system.gserviceaccount.com", + "aud" => "client_id", + "id" => self::USER_ID, + "exp" => time() + 3600 + ) + ); + $this->checkIdTokenFailure($id_token, "No issue time"); + } + + public function testVerifySignedJwtWithNoExpirationTime() + { + $id_token = $this->makeSignedJwt( + array( + "iss" => "federated-signon@system.gserviceaccount.com", + "aud" => "client_id", + "id" => self::USER_ID, + "iat" => time() + ) + ); + $this->checkIdTokenFailure($id_token, "No expiration time"); + } + + public function testVerifySignedJwtWithTooEarly() + { + $id_token = $this->makeSignedJwt( + array( + "iss" => "federated-signon@system.gserviceaccount.com", + "aud" => "client_id", + "id" => self::USER_ID, + "iat" => time() + 1800, + "exp" => time() + 3600 + ) + ); + $this->checkIdTokenFailure($id_token, "Token used too early"); + } + + public function testVerifySignedJwtWithTooLate() + { + $id_token = $this->makeSignedJwt( + array( + "iss" => "federated-signon@system.gserviceaccount.com", + "aud" => "client_id", + "id" => self::USER_ID, + "iat" => time() - 3600, + "exp" => time() - 1800 + ) + ); + $this->checkIdTokenFailure($id_token, "Token used too late"); + } + + public function testVerifySignedJwtWithLifetimeTooLong() + { + $id_token = $this->makeSignedJwt( + array( + "iss" => "federated-signon@system.gserviceaccount.com", + "aud" => "client_id", + "id" => self::USER_ID, + "iat" => time(), + "exp" => time() + 3600 * 25 + ) + ); + $this->checkIdTokenFailure($id_token, "Expiration time too far in future"); + } + + public function testVerifySignedJwtWithBadAudience() + { + $id_token = $this->makeSignedJwt( + array( + "iss" => "federated-signon@system.gserviceaccount.com", + "aud" => "wrong_client_id", + "id" => self::USER_ID, + "iat" => time(), + "exp" => time() + 3600 + ) + ); + $this->checkIdTokenFailure($id_token, "Wrong recipient"); + } + + public function testNoAuth() + { + /** @var $noAuth Google_Auth_Simple */ + $noAuth = new Google_Auth_Simple($this->getClient()); + $oldAuth = $this->getClient()->getAuth(); + $this->getClient()->setAuth($noAuth); + $this->getClient()->setDeveloperKey(null); + $req = new Google_Http_Request("http://example.com"); + + $resp = $noAuth->sign($req); + $this->assertEquals("http://example.com", $resp->getUrl()); + $this->getClient()->setAuth($oldAuth); + } + + public function testAssertionCredentials() + { + $assertion = new Google_Auth_AssertionCredentials( + 'name', + 'scope', + file_get_contents(__DIR__.'/'.self::PRIVATE_KEY_FILE, true) + ); + + $token = explode(".", $assertion->generateAssertion()); + $this->assertEquals('{"typ":"JWT","alg":"RS256"}', base64_decode($token[0])); + + $jwt = json_decode(base64_decode($token[1]), true); + $this->assertEquals('https://accounts.google.com/o/oauth2/token', $jwt['aud']); + $this->assertEquals('scope', $jwt['scope']); + $this->assertEquals('name', $jwt['iss']); + + $key = $assertion->getCacheKey(); + $this->assertTrue($key != false); + $assertion = new Google_Auth_AssertionCredentials( + 'name2', + 'scope', + file_get_contents(__DIR__.'/'.self::PRIVATE_KEY_FILE, true) + ); + $this->assertNotEquals($key, $assertion->getCacheKey()); + } + + public function testVerifySignedJWT() + { + $assertion = new Google_Auth_AssertionCredentials( + 'issuer', + 'scope', + file_get_contents(__DIR__.'/'.self::PRIVATE_KEY_FILE, true) + ); + $client = $this->getClient(); + + $this->assertInstanceOf( + 'Google_Auth_LoginTicket', + $client->verifySignedJwt( + $assertion->generateAssertion(), + __DIR__ . DIRECTORY_SEPARATOR . self::PUBLIC_KEY_FILE_JSON, + 'https://accounts.google.com/o/oauth2/token', + 'issuer' + ) + ); + } +} diff --git a/includes/google-api-php-client-master/tests/general/CacheTest.php b/includes/google-api-php-client-master/tests/general/CacheTest.php new file mode 100644 index 0000000..8a61a9a --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/CacheTest.php @@ -0,0 +1,133 @@ +<?php +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +class CacheTest extends BaseTest +{ + public function testFile() + { + $dir = sys_get_temp_dir() . '/google-api-php-client/tests'; + $client = $this->getClient(); + $client->setClassConfig( + 'Google_Cache_File', + 'directory', + $dir + ); + $cache = new Google_Cache_File($client); + $cache->set('foo', 'bar'); + $this->assertEquals($cache->get('foo'), 'bar'); + + $this->getSetDelete($cache); + } + + /** + * @requires extension Memcache + */ + public function testNull() + { + $client = $this->getClient(); + $cache = new Google_Cache_Null($client); + $client->setCache($cache); + + $cache->set('foo', 'bar'); + $cache->delete('foo'); + $this->assertEquals(false, $cache->get('foo')); + + $cache->set('foo.1', 'bar.1'); + $this->assertEquals($cache->get('foo.1'), false); + + $cache->set('foo', 'baz'); + $this->assertEquals($cache->get('foo'), false); + + $cache->set('foo', null); + $cache->delete('foo'); + $this->assertEquals($cache->get('foo'), false); + } + + /** + * @requires extension Memcache + */ + public function testMemcache() + { + $client = $this->getClient(); + if (!$client->getClassConfig('Google_Cache_Memcache', 'host')) { + $this->markTestSkipped('Test requires memcache host specified'); + } + + $cache = new Google_Cache_Memcache($client); + + $this->getSetDelete($cache); + } + + /** + * @requires extension APC + */ + public function testAPC() + { + if (!ini_get('apc.enable_cli')) { + $this->markTestSkipped('Test requires APC enabled for CLI'); + } + $client = $this->getClient(); + $cache = new Google_Cache_Apc($client); + + $this->getSetDelete($cache); + } + + public function getSetDelete($cache) + { + $cache->set('foo', 'bar'); + $cache->delete('foo'); + $this->assertEquals(false, $cache->get('foo')); + + $cache->set('foo.1', 'bar.1'); + $cache->delete('foo.1'); + $this->assertEquals($cache->get('foo.1'), false); + + $cache->set('foo', 'baz'); + $cache->delete('foo'); + $this->assertEquals($cache->get('foo'), false); + + $cache->set('foo', null); + $cache->delete('foo'); + $this->assertEquals($cache->get('foo'), false); + + $obj = new stdClass(); + $obj->foo = 'bar'; + $cache->set('foo', $obj); + $cache->delete('foo'); + $this->assertEquals($cache->get('foo'), false); + + $cache->set('foo.1', 'bar.1'); + $this->assertEquals($cache->get('foo.1'), 'bar.1'); + + $cache->set('foo', 'baz'); + $this->assertEquals($cache->get('foo'), 'baz'); + + $cache->set('foo', null); + $this->assertEquals($cache->get('foo'), null); + + $cache->set('1/2/3', 'bar'); + $this->assertEquals($cache->get('1/2/3'), 'bar'); + + $obj = new stdClass(); + $obj->foo = 'bar'; + $cache->set('foo', $obj); + $this->assertEquals($cache->get('foo'), $obj); + } +} diff --git a/includes/google-api-php-client-master/tests/general/ComputeEngineAuthTest.php b/includes/google-api-php-client-master/tests/general/ComputeEngineAuthTest.php new file mode 100644 index 0000000..5f198f9 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/ComputeEngineAuthTest.php @@ -0,0 +1,84 @@ +<?php +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +class ComputeEngineAuthTest extends BaseTest +{ + public function testTokenAcquisition() + { + $client = new Google_Client(); + + /* Mock out refresh call */ + $response_data = json_encode( + array( + 'access_token' => "ACCESS_TOKEN", + 'expires_in' => "12345" + ) + ); + $response = $this->getMock("Google_Http_Request", array(), array('')); + $response->expects($this->any()) + ->method('getResponseHttpCode') + ->will($this->returnValue(200)); + $response->expects($this->any()) + ->method('getResponseBody') + ->will($this->returnValue($response_data)); + $io = $this->getMock("Google_IO_Stream", array(), array($client)); + $client->setIo($io);$io->expects($this->any()) + ->method('makeRequest') + ->will( + $this->returnCallback( + function ($request) use ($response) { + return $response; + } + ) + ); + + /* Run method */ + $oauth = new Google_Auth_ComputeEngine($client); + $oauth->acquireAccessToken(); + $token = json_decode($oauth->getAccessToken(), true); + + /* Check results */ + $this->assertEquals($token['access_token'], "ACCESS_TOKEN"); + $this->assertEquals($token['expires_in'], "12345"); + $this->assertTrue($token['created'] > 0); + } + + public function testSign() + { + $client = new Google_Client(); + $oauth = new Google_Auth_ComputeEngine($client); + + /* Load mock access token */ + $oauth->setAccessToken( + json_encode( + array( + 'access_token' => "ACCESS_TOKEN", + 'expires_in' => "12345" + ) + ) + ); + + /* Sign a URL and verify auth header is correctly set */ + $req = new Google_Http_Request('http://localhost'); + $req = $oauth->sign($req); + $auth = $req->getRequestHeader('authorization'); + $this->assertEquals('Bearer ACCESS_TOKEN', $auth); + } +} diff --git a/includes/google-api-php-client-master/tests/general/IoTest.php b/includes/google-api-php-client-master/tests/general/IoTest.php new file mode 100644 index 0000000..212219e --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/IoTest.php @@ -0,0 +1,381 @@ +<?php +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +class IoTest extends BaseTest +{ + + public function testExecutorSelection() + { + $default = function_exists('curl_version') ? 'Google_IO_Curl' : 'Google_IO_Stream'; + $client = $this->getClient(); + $this->assertInstanceOf($default, $client->getIo()); + $config = new Google_Config(); + $config->setIoClass('Google_IO_Stream'); + $client = new Google_Client($config); + $this->assertInstanceOf('Google_IO_Stream', $client->getIo()); + } + + public function testStreamSetTimeout() + { + $io = new Google_IO_Stream($this->getClient()); + $this->timeoutChecker($io); + } + + public function testStreamParseHttpResponseBody() + { + $io = new Google_IO_Stream($this->getClient()); + $this->responseChecker($io); + } + + public function testStreamProcessEntityRequest() + { + $client = $this->getClient(); + $io = new Google_IO_Stream($client); + $this->processEntityRequest($io, $client); + } + + public function testStreamCacheHit() + { + $client = $this->getClient(); + $io = new Google_IO_Stream($client); + $this->cacheHit($io, $client); + } + + public function testStreamAuthCache() + { + $client = $this->getClient(); + $io = new Google_IO_Stream($client); + $this->authCache($io, $client); + } + + /** + * @expectedException Google_IO_Exception + */ + public function testStreamInvalidRequest() + { + $io = new Google_IO_Stream($this->getClient()); + $this->invalidRequest($io); + } + + public function testCurlSetTimeout() + { + if (!function_exists('curl_version')) { + $this->markTestSkipped('cURL not present'); + } + $io = new Google_IO_Curl($this->getClient()); + $this->timeoutChecker($io); + } + + public function testCurlParseHttpResponseBody() + { + if (!function_exists('curl_version')) { + $this->markTestSkipped('cURL not present'); + } + $io = new Google_IO_Curl($this->getClient()); + $this->responseChecker($io); + } + + public function testCurlProcessEntityRequest() + { + if (!function_exists('curl_version')) { + $this->markTestSkipped('cURL not present'); + } + $client = $this->getClient(); + $io = new Google_IO_Curl($client); + $this->processEntityRequest($io, $client); + } + + public function testCurlCacheHit() + { + if (!function_exists('curl_version')) { + $this->markTestSkipped('cURL not present'); + } + $client = $this->getClient(); + $io = new Google_IO_Curl($client); + $this->cacheHit($io, $client); + } + + public function testCurlAuthCache() + { + if (!function_exists('curl_version')) { + $this->markTestSkipped('cURL not present'); + } + $client = $this->getClient(); + $io = new Google_IO_Curl($client); + $this->authCache($io, $client); + } + + /** + * @expectedException Google_IO_Exception + */ + public function testCurlInvalidRequest() + { + if (!function_exists('curl_version')) { + $this->markTestSkipped('cURL not present'); + } + $io = new Google_IO_Curl($this->getClient()); + $this->invalidRequest($io); + } + + public function testCacheRevalidate() + { + $client = $this->getClient(); + + $req = new Google_Http_Request('/test', 'GET'); + $req->setRequestHeaders(array('Accept' => '*/*')); + $req->setResponseBody('{"a": "foo"}'); + $req->setResponseHttpCode(200); + $req->setResponseHeaders( + array( + 'cache-control' => 'private', + 'etag' => '"this-is-an-etag"', + 'expires' => '-1', + 'date' => 'Sun, 1 Jan 2012 09:00:56 GMT', + 'content-type' => 'application/json; charset=UTF-8', + ) + ); + + $io = $this->getMockBuilder('Google_IO_Abstract') + ->setConstructorArgs(array($client)) + ->setMethods( + array( + 'getCachedRequest', + 'checkMustRevalidateCachedRequest' + ) + ) + ->getMockForAbstractClass(); + + $io->expects($this->once()) + ->method('getCachedRequest') + ->will($this->returnValue($req)); + + $io->expects($this->once()) + ->method('checkMustRevalidateCachedRequest') + ->will($this->returnValue(true)); + + $io->expects($this->once()) + ->method('executeRequest') + ->will( + $this->returnValue( + array( + '{"a": "foo"}', + array( + 'te' => 'gzip', + 'connection' => 'Keep-Alive, Foo, Bar', + 'foo' => '123', + 'keep-alive' => 'timeout=30', + 'cache-control' => 'private', + 'eTag' => '"this-is-a-new-etag"', + "expires" => 'Sun, 22 Jan 2022 09:00:56 GMT', + 'date' => 'Sun, 1 Jan 2012 09:00:56 GMT', + 'content-type' => 'application/json; charset=UTF-8', + ), + 304 + ) + ) + ); + + $res = $io->makeRequest(new Google_Http_Request('/test', 'GET')); + + $this->assertEquals('{"a": "foo"}', $res->getResponseBody()); + $this->assertEquals(200, $res->getResponseHttpCode()); + $this->assertEquals( + array( + 'cache-control' => 'private', + 'etag' => '"this-is-a-new-etag"', + "expires" => 'Sun, 22 Jan 2022 09:00:56 GMT', + 'date' => 'Sun, 1 Jan 2012 09:00:56 GMT', + 'content-type' => 'application/json; charset=UTF-8', + ), + $res->getResponseHeaders() + ); + } + + // Asserting Functions + + public function timeoutChecker($io) + { + $this->assertEquals(100, $io->getTimeout()); + $io->setTimeout(120); + $this->assertEquals(120, $io->getTimeout()); + } + + public function invalidRequest($io) + { + $url = "http://localhost:1"; + $req = new Google_Http_Request($url, "GET"); + $io->makeRequest($req); + } + + public function cacheHit($io, $client) + { + $url = "http://www.googleapis.com"; + // Create a cacheable request/response. + // Should not be revalidated. + $cacheReq = new Google_Http_Request($url, "GET"); + $cacheReq->setRequestHeaders( + array("Accept" => "*/*",) + ); + $cacheReq->setResponseBody("{\"a\": \"foo\"}"); + $cacheReq->setResponseHttpCode(200); + $cacheReq->setResponseHeaders( + array( + "Cache-Control" => "private", + "ETag" => "\"this-is-an-etag\"", + "Expires" => "Sun, 22 Jan 2022 09:00:56 GMT", + "Date" => "Sun, 1 Jan 2012 09:00:56 GMT", + "Content-Type" => "application/json; charset=UTF-8", + ) + ); + + // Populate the cache. + $io->setCachedRequest($cacheReq); + + // Execute the same mock request, and expect a cache hit. + $res = $io->makeRequest(new Google_Http_Request($url, "GET")); + $this->assertEquals("{\"a\": \"foo\"}", $res->getResponseBody()); + $this->assertEquals(200, $res->getResponseHttpCode()); + } + + public function authCache($io, $client) + { + $url = "http://www.googleapis.com/protected/resource"; + + // Create a cacheable request/response, but it should not be cached. + $cacheReq = new Google_Http_Request($url, "GET"); + $cacheReq->setRequestHeaders( + array( + "Accept" => "*/*", + "Authorization" => "Bearer Foo" + ) + ); + $cacheReq->setResponseBody("{\"a\": \"foo\"}"); + $cacheReq->setResponseHttpCode(200); + $cacheReq->setResponseHeaders( + array( + "Cache-Control" => "private", + "ETag" => "\"this-is-an-etag\"", + "Expires" => "Sun, 22 Jan 2022 09:00:56 GMT", + "Date: Sun, 1 Jan 2012 09:00:56 GMT", + "Content-Type" => "application/json; charset=UTF-8", + ) + ); + + $result = $io->setCachedRequest($cacheReq); + $this->assertFalse($result); + } + + public function responseChecker($io) + { + $hasQuirk = false; + if (function_exists('curl_version')) { + $curlVer = curl_version(); + $hasQuirk = $curlVer['version_number'] < Google_IO_Curl::NO_QUIRK_VERSION; + } + + $rawHeaders = "HTTP/1.1 200 OK\r\n" + . "Expires: Sun, 22 Jan 2012 09:00:56 GMT\r\n" + . "Date: Sun, 22 Jan 2012 09:00:56 GMT\r\n" + . "Content-Type: application/json; charset=UTF-8\r\n"; + $size = strlen($rawHeaders); + $rawBody = "{}"; + + $rawResponse = "$rawHeaders\r\n$rawBody"; + list($headers, $body) = $io->parseHttpResponse($rawResponse, $size); + $this->assertEquals(3, sizeof($headers)); + $this->assertEquals(array(), json_decode($body, true)); + + // Test empty bodies. + $rawResponse = $rawHeaders . "\r\n"; + list($headers, $body) = $io->parseHttpResponse($rawResponse, $size); + $this->assertEquals(3, sizeof($headers)); + $this->assertEquals(null, json_decode($body, true)); + + // Test no content. + $rawerHeaders = "HTTP/1.1 204 No Content\r\n" + . "Date: Fri, 19 Sep 2014 15:52:14 GMT"; + list($headers, $body) = $io->parseHttpResponse($rawerHeaders, 0); + $this->assertEquals(1, sizeof($headers)); + $this->assertEquals(null, json_decode($body, true)); + + // Test transforms from proxies. + $connection_established_headers = array( + "HTTP/1.0 200 Connection established\r\n\r\n", + "HTTP/1.1 200 Connection established\r\n\r\n", + ); + foreach ($connection_established_headers as $established_header) { + $rawHeaders = "{$established_header}HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"; + $headersSize = strlen($rawHeaders); + // If we have a broken cURL version we have to simulate it to get the + // correct test result. + if ($hasQuirk && get_class($io) === 'Google_IO_Curl') { + $headersSize -= strlen($established_header); + } + $rawBody = "{}"; + + $rawResponse = "$rawHeaders\r\n$rawBody"; + list($headers, $body) = $io->parseHttpResponse($rawResponse, $headersSize); + $this->assertEquals(1, sizeof($headers)); + $this->assertEquals(array(), json_decode($body, true)); + } + } + + public function processEntityRequest($io, $client) + { + $req = new Google_Http_Request("http://localhost.com"); + $req->setRequestMethod("POST"); + + // Verify that the content-length is calculated. + $req->setPostBody("{}"); + $io->processEntityRequest($req); + $this->assertEquals(2, $req->getRequestHeader("content-length")); + + // Test an empty post body. + $req->setPostBody(""); + $io->processEntityRequest($req); + $this->assertEquals(0, $req->getRequestHeader("content-length")); + + // Test a null post body. + $req->setPostBody(null); + $io->processEntityRequest($req); + $this->assertEquals(0, $req->getRequestHeader("content-length")); + + // Set an array in the postbody, and verify that it is url-encoded. + $req->setPostBody(array("a" => "1", "b" => 2)); + $io->processEntityRequest($req); + $this->assertEquals(7, $req->getRequestHeader("content-length")); + $this->assertEquals( + Google_IO_Abstract::FORM_URLENCODED, + $req->getRequestHeader("content-type") + ); + $this->assertEquals("a=1&b=2", $req->getPostBody()); + + // Verify that the content-type isn't reset. + $payload = array("a" => "1", "b" => 2); + $req->setPostBody($payload); + $req->setRequestHeaders(array("content-type" => "multipart/form-data")); + $io->processEntityRequest($req); + $this->assertEquals( + "multipart/form-data", + $req->getRequestHeader("content-type") + ); + $this->assertEquals($payload, $req->getPostBody()); + } +} diff --git a/includes/google-api-php-client-master/tests/general/LoggerTest.php b/includes/google-api-php-client-master/tests/general/LoggerTest.php new file mode 100644 index 0000000..cfdf8d4 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/LoggerTest.php @@ -0,0 +1,445 @@ +<?php +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +class LoggerTest extends PHPUnit_Framework_TestCase +{ + private $client; + + public function setup() + { + $this->client = new Google_Client(); + } + + /** + * @dataProvider logLevelsProvider + */ + public function testPsrMethods($key) + { + $message = 'This is my log message'; + $context = array('some'=>'context'); + + $logger = $this->getLogger('log'); + $logger->expects($this->once()) + ->method('log') + ->with($key, $message, $context); + + call_user_func(array($logger, $key), $message, $context); + } + + /** + * @dataProvider invalidLevelsProvider + * @expectedException Google_Logger_Exception + * @expectedExceptionMessage Unknown LogLevel + */ + public function testSetLabelWithBadValue($level) + { + $this->getLogger()->setLevel($level); + } + + /** + * @dataProvider invalidLevelsProvider + * @expectedException Google_Logger_Exception + * @expectedExceptionMessage Unknown LogLevel + */ + public function testSetLabelWithBadValueFromConfig($level) + { + $this->client->setClassConfig('Google_Logger_Abstract', 'level', $level); + $this->getLogger(); + } + + /** + * @dataProvider filterProvider + */ + public function testShouldHandle($setLevel, $handleLevel, $expected) + { + $logger = $this->getLogger(); + $logger->setLevel($setLevel); + + $this->assertEquals($expected, $logger->shouldHandle($handleLevel)); + } + + /** + * @dataProvider filterProvider + */ + public function testShouldHandleFromConfig($config, $handleLevel, $expected) + { + $this->client->setClassConfig('Google_Logger_Abstract', 'level', $config); + $logger = $this->getLogger(); + + $this->assertEquals($expected, $logger->shouldHandle($handleLevel)); + } + + /** + * @dataProvider filterProvider + */ + public function testShouldWrite($setLevel, $logLevel, $expected) + { + $logger = $this->getLogger(); + $logger->expects($expected ? $this->once() : $this->never()) + ->method('write'); + + $logger->setLevel($setLevel); + $logger->log($logLevel, 'This is my log message'); + } + + /** + * @dataProvider filterProvider + */ + public function testShouldWriteFromConfig($config, $logLevel, $expected) + { + $this->client->setClassConfig('Google_Logger_Abstract', 'level', $config); + $logger = $this->getLogger(); + $logger->expects($expected ? $this->once() : $this->never()) + ->method('write'); + + $logger->log($logLevel, 'This is my log message'); + } + + /** + * @dataProvider formattingProvider + */ + public function testMessageFormatting( + $format, + $date_format, + $newlines, + $message, + $context, + $expected + ) { + $this->client->setClassConfig( + 'Google_Logger_Abstract', + 'log_format', + $format + ); + $this->client->setClassConfig( + 'Google_Logger_Abstract', + 'date_format', + $date_format + ); + $this->client->setClassConfig( + 'Google_Logger_Abstract', + 'allow_newlines', + $newlines + ); + + $logger = $this->getLogger(); + $logger->expects($this->once()) + ->method('write') + ->with($expected); + + $logger->log('debug', $message, $context); + } + + public function testNullLoggerNeverWrites() + { + $logger = $this->getLogger('write', 'Google_Logger_Null'); + $logger->expects($this->never()) + ->method('write'); + + $logger->log( + 'emergency', + 'Should not be written', + array('same' => 'for this') + ); + } + + public function testNullLoggerNeverHandles() + { + $logger = $this->getLogger('write', 'Google_Logger_Null'); + $this->assertFalse($logger->shouldHandle('emergency')); + $this->assertFalse($logger->shouldHandle(600)); + } + + public function testPsrNeverWrites() + { + $logger = $this->getLogger('write', 'Google_Logger_Psr'); + $logger->expects($this->never()) + ->method('write'); + + $logger->log( + 'emergency', + 'Should not be written', + array('same' => 'for this') + ); + + $logger->setLogger($this->getLogger()); + + $logger->log( + 'emergency', + 'Should not be written', + array('same' => 'for this') + ); + } + + public function testPsrNeverShouldHandleWhenNoLoggerSet() + { + $logger = $this->getLogger(null, 'Google_Logger_Psr'); + $this->assertFalse($logger->shouldHandle('emergency')); + $this->assertFalse($logger->shouldHandle(600)); + } + + public function testPsrShouldHandleWhenLoggerSet() + { + $logger = $this->getLogger(null, 'Google_Logger_Psr'); + $logger->setLogger($this->getLogger()); + + $this->assertTrue($logger->shouldHandle('emergency')); + $this->assertTrue($logger->shouldHandle(600)); + } + + /** + * @dataProvider logLevelsProvider + */ + public function testPsrDelegates($key) + { + $message = 'This is my log message'; + $context = array('some'=>'context'); + + $delegate = $this->getLogger('log'); + $delegate->expects($this->once()) + ->method('log') + ->with($key, $message, $context); + + $logger = $this->getLogger(null, 'Google_Logger_Psr'); + $logger->setLogger($delegate); + + call_user_func(array($logger, $key), $message, $context); + } + + /** + * @expectedException Google_Logger_Exception + * @expectedExceptionMessage File logger requires a filename or a valid file pointer + */ + public function testLoggerWithBadFileType() + { + $this->client->setClassConfig('Google_Logger_File', 'file', false); + $logger = $this->getLogger(null, 'Google_Logger_File'); + } + + /** + * @expectedException Google_Logger_Exception + * @expectedExceptionMessage Logger Error + */ + public function testLoggerWithBadFileValue() + { + $this->client->setClassConfig('Google_Logger_File', 'file', 'not://exist'); + + $logger = $this->getLogger(null, 'Google_Logger_File'); + $logger->log('emergency', 'will fail'); + } + + /** + * @expectedException Google_Logger_Exception + * @expectedExceptionMessage File pointer is no longer available + */ + public function testLoggerWithClosedFileReference() + { + $fp = fopen('php://memory', 'r+'); + + $this->client->setClassConfig('Google_Logger_File', 'file', $fp); + $logger = $this->getLogger(null, 'Google_Logger_File'); + + fclose($fp); + + $logger->log('emergency', 'will fail'); + } + + public function testLoggerWithFileReference() + { + $fp = fopen('php://memory', 'r+'); + + $this->client->setClassConfig('Google_Logger_File', 'file', $fp); + $this->client->setClassConfig( + 'Google_Logger_Abstract', + 'log_format', + "%level% - %message%\n" + ); + + $logger = $this->getLogger(null, 'Google_Logger_File'); + $logger->log('emergency', 'test one'); + $logger->log('alert', 'test two'); + $logger->log(500, 'test three'); + + rewind($fp); + $this->assertEquals( + "EMERGENCY - test one\nALERT - test two\nCRITICAL - test three\n", + stream_get_contents($fp) + ); + + fclose($fp); + } + + public function testLoggerWithFile() + { + $this->expectOutputString( + "EMERGENCY - test one\nALERT - test two\nCRITICAL - test three\n" + ); + + $this->client->setClassConfig( + 'Google_Logger_File', + 'file', + 'php://output' + ); + $this->client->setClassConfig( + 'Google_Logger_Abstract', + 'log_format', + "%level% - %message%\n" + ); + + $logger = $this->getLogger(null, 'Google_Logger_File'); + $logger->log('emergency', 'test one'); + $logger->log('alert', 'test two'); + $logger->log(500, 'test three'); + } + + public function formattingProvider() + { + return array( + 'no interpolation' => array( + 'this is my format', + 'd/M/Y:H:i:s O', + false, + 'you wont see this', + array('or' => 'this'), + 'this is my format', + ), + 'only message interpolation' => array( + 'my format: %message%', + 'd/M/Y:H:i:s O', + false, + 'you will see this', + array('but not' => 'this'), + 'my format: you will see this', + ), + 'message and level interpolation' => array( + '%level% - my format: %message%', + 'd/M/Y:H:i:s O', + false, + 'you will see this', + array('but not' => 'this'), + 'DEBUG - my format: you will see this', + ), + 'message, level, datetime interpolation' => array( + '[%datetime%] %level% - my format: %message%', + '\T\I\M\E', + false, + 'you will see this', + array('but not' => 'this'), + '[TIME] DEBUG - my format: you will see this', + ), + 'message, level, datetime, context interpolation' => array( + '[%datetime%] %level% - my format: %message%: %context%', + '\T\I\M\E', + false, + 'you will see this', + array('and' => 'this'), + '[TIME] DEBUG - my format: you will see this: {"and":"this"}', + ), + 'reverse JSON in context' => array( + '%context%', + 'd/M/Y:H:i:s O', + false, + 'you will not see this', + array('reverse' => json_encode(array('this' => 'is cool'))), + '{"reverse":{"this":"is cool"}}', + ), + 'remove newlines in message' => array( + '%message%', + 'd/M/Y:H:i:s O', + false, + "This \n\n\r\n is \r my \r\n newlines \r\r\r\n\n message", + array('you wont' => 'see this'), + 'This is my newlines message', + ), + 'allow newlines in message' => array( + '%message%', + 'd/M/Y:H:i:s O', + true, + "This \n\n\r\n is \r my \r\n newlines \r\r\r\n\n message", + array('you wont' => 'see this'), + "This \n\n\r\n is \r my \r\n newlines \r\r\r\n\n message", + ), + 'allow newlines in JSON' => array( + '%context%', + 'd/M/Y:H:i:s O', + true, + "wont see this", + array('you will' => 'see this'), + version_compare(PHP_VERSION, '5.4.0', '>=') ? + "{\n \"you will\": \"see this\"\n}" : + '{"you will":"see this"}' + ), + ); + } + + public function filterProvider() + { + return array( + array('debug', 'debug', true), + array(100, 'debug', true), + array('info', 'debug', false), + array('info', 'notice', true), + array('notice', 'notice', true), + array(250, 'notice', true), + array('notice', 'debug', false), + array(250, 'alert', true), + array('error', 'error', true), + array('error', 'warning', false), + array('error', 'critical', true), + array(600, 'alert', false), + array(600, 'critical', false), + array(600, 'emergency', true), + array('emergency', 'emergency', true), + ); + } + + public function invalidLevelsProvider() + { + return array( + array('100'), + array('DEBUG'), + array(100.0), + array(''), + array(0), + ); + } + + public function logLevelsProvider() + { + return array( + array('emergency', 600), + array('alert', 550), + array('critical', 500), + array('error', 400), + array('warning', 300), + array('notice', 250), + array('info', 200), + array('debug', 100), + ); + } + + private function getLogger($methods = null, $type = 'Google_Logger_Abstract') + { + return $this->getMockBuilder($type) + ->setMethods((array) $methods) + ->setConstructorArgs(array($this->client)) + ->getMockForAbstractClass(); + } +} diff --git a/includes/google-api-php-client-master/tests/general/RequestTest.php b/includes/google-api-php-client-master/tests/general/RequestTest.php new file mode 100644 index 0000000..68476cd --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/RequestTest.php @@ -0,0 +1,71 @@ +<?php +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +class RequestTest extends BaseTest +{ + public function testRequestParameters() + { + $url = 'http://localhost:8080/foo/bar?foo=a&foo=b&wowee=oh+my'; + $url2 = 'http://localhost:8080/foo/bar?foo=a&foo=b&wowee=oh+my&hi=there'; + $request = new Google_Http_Request($url); + $request->setExpectedClass("Google_Client"); + $this->assertEquals(2, count($request->getQueryParams())); + $request->setQueryParam("hi", "there"); + $this->assertEquals($url2, $request->getUrl()); + $this->assertEquals("Google_Client", $request->getExpectedClass()); + + $urlPath = "/foo/bar"; + $request = new Google_Http_Request($urlPath); + $this->assertEquals($urlPath, $request->getUrl()); + $request->setBaseComponent("http://example.com"); + $this->assertEquals("http://example.com" . $urlPath, $request->getUrl()); + + $url3a = 'http://localhost:8080/foo/bar'; + $url3b = 'foo=a&foo=b&wowee=oh+my'; + $url3c = 'foo=a&foo=b&wowee=oh+my&hi=there'; + $request = new Google_Http_Request($url3a."?".$url3b, "POST"); + $request->setQueryParam("hi", "there"); + $request->maybeMoveParametersToBody(); + $this->assertEquals($url3a, $request->getUrl()); + $this->assertEquals($url3c, $request->getPostBody()); + + $url4 = 'http://localhost:8080/upload/foo/bar?foo=a&foo=b&wowee=oh+my&hi=there'; + $request = new Google_Http_Request($url); + $this->assertEquals(2, count($request->getQueryParams())); + $request->setQueryParam("hi", "there"); + $base = $request->getBaseComponent(); + $request->setBaseComponent($base . '/upload'); + $this->assertEquals($url4, $request->getUrl()); + } + + public function testGzipSupport() + { + $url = 'http://localhost:8080/foo/bar?foo=a&foo=b&wowee=oh+my'; + $request = new Google_Http_Request($url); + $request->enableGzip(); + $this->assertStringEndsWith(Google_Http_Request::GZIP_UA, $request->getUserAgent()); + $this->assertArrayHasKey('accept-encoding', $request->getRequestHeaders()); + $this->assertTrue($request->canGzip()); + $request->disableGzip(); + $this->assertStringEndsNotWith(Google_Http_Request::GZIP_UA, $request->getUserAgent()); + $this->assertArrayNotHasKey('accept-encoding', $request->getRequestHeaders()); + $this->assertFalse($request->canGzip()); + } +} diff --git a/includes/google-api-php-client-master/tests/general/RestTest.php b/includes/google-api-php-client-master/tests/general/RestTest.php new file mode 100644 index 0000000..caed129 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/RestTest.php @@ -0,0 +1,161 @@ +<?php +/* + * Copyright 2011 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class RestTest extends BaseTest +{ + /** + * @var Google_Http_REST $rest + */ + private $rest; + + public function setUp() + { + $this->rest = new Google_Http_REST(); + } + + public function testDecodeResponse() + { + $url = 'http://localhost'; + $client = $this->getClient(); + $response = new Google_Http_Request($url); + $response->setResponseHttpCode(204); + $decoded = $this->rest->decodeHttpResponse($response, $client); + $this->assertEquals(null, $decoded); + + + foreach (array(200, 201) as $code) { + $headers = array('foo', 'bar'); + $response = new Google_Http_Request($url, 'GET', $headers); + $response->setResponseBody('{"a": 1}'); + + $response->setResponseHttpCode($code); + $decoded = $this->rest->decodeHttpResponse($response, $client); + $this->assertEquals(array("a" => 1), $decoded); + } + + $response = new Google_Http_Request($url); + $response->setResponseHttpCode(500); + + $error = ""; + try { + $this->rest->decodeHttpResponse($response, $client); + } catch (Exception $e) { + $error = $e->getMessage(); + + } + $this->assertEquals(trim($error), "Error calling GET http://localhost: (500)"); + } + + + public function testDecodeEmptyResponse() + { + $url = 'http://localhost'; + + $response = new Google_Http_Request($url, 'GET', array()); + $response->setResponseBody('{}'); + + $response->setResponseHttpCode(200); + $decoded = $this->rest->decodeHttpResponse($response); + $this->assertEquals(array(), $decoded); + } + + public function testCreateRequestUri() + { + $basePath = "http://localhost"; + $restPath = "/plus/{u}"; + + // Test Path + $params = array(); + $params['u']['type'] = 'string'; + $params['u']['location'] = 'path'; + $params['u']['value'] = 'me'; + $value = $this->rest->createRequestUri($basePath, $restPath, $params); + $this->assertEquals("http://localhost/plus/me", $value); + + // Test Query + $params = array(); + $params['u']['type'] = 'string'; + $params['u']['location'] = 'query'; + $params['u']['value'] = 'me'; + $value = $this->rest->createRequestUri($basePath, '/plus', $params); + $this->assertEquals("http://localhost/plus?u=me", $value); + + // Test Booleans + $params = array(); + $params['u']['type'] = 'boolean'; + $params['u']['location'] = 'path'; + $params['u']['value'] = '1'; + $value = $this->rest->createRequestUri($basePath, $restPath, $params); + $this->assertEquals("http://localhost/plus/true", $value); + + $params['u']['location'] = 'query'; + $value = $this->rest->createRequestUri($basePath, '/plus', $params); + $this->assertEquals("http://localhost/plus?u=true", $value); + + // Test encoding + $params = array(); + $params['u']['type'] = 'string'; + $params['u']['location'] = 'query'; + $params['u']['value'] = '@me/'; + $value = $this->rest->createRequestUri($basePath, '/plus', $params); + $this->assertEquals("http://localhost/plus?u=%40me%2F", $value); + } + + /** + * @expectedException Google_Service_Exception + */ + public function testBadErrorFormatting() + { + $request = new Google_Http_Request("/a/b"); + $request->setResponseHttpCode(500); + $request->setResponseBody( + '{ + "error": { + "code": 500, + "message": null + } + }' + ); + Google_Http_Rest::decodeHttpResponse($request); + } + + /** + * @expectedException Google_Service_Exception + */ + public function tesProperErrorFormatting() + { + $request = new Google_Http_Request("/a/b"); + $request->setResponseHttpCode(401); + $request->setResponseBody( + '{ + error: { + errors: [ + { + "domain": "global", + "reason": "authError", + "message": "Invalid Credentials", + "locationType": "header", + "location": "Authorization", + } + ], + "code": 401, + "message": "Invalid Credentials" + }' + ); + Google_Http_Rest::decodeHttpResponse($request); + } +} diff --git a/includes/google-api-php-client-master/tests/general/ServiceTest.php b/includes/google-api-php-client-master/tests/general/ServiceTest.php new file mode 100644 index 0000000..306c4a2 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/ServiceTest.php @@ -0,0 +1,106 @@ +<?php +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +class TestModel extends Google_Model +{ + public function mapTypes($array) + { + return parent::mapTypes($array); + } + + public function isAssociativeArray($array) + { + return parent::isAssociativeArray($array); + } +} + +class ServiceTest extends PHPUnit_Framework_TestCase +{ + public function testModel() + { + $model = new TestModel(); + + $model->mapTypes( + array( + 'name' => 'asdf', + 'gender' => 'z', + ) + ); + $this->assertEquals('asdf', $model->name); + $this->assertEquals('z', $model->gender); + $model->mapTypes( + array( + '__infoType' => 'Google_Model', + '__infoDataType' => 'map', + 'info' => array ( + 'location' => 'mars', + 'timezone' => 'mst', + ), + 'name' => 'asdf', + 'gender' => 'z', + ) + ); + $this->assertEquals('asdf', $model->name); + $this->assertEquals('z', $model->gender); + + $this->assertEquals(false, $model->isAssociativeArray("")); + $this->assertEquals(false, $model->isAssociativeArray(false)); + $this->assertEquals(false, $model->isAssociativeArray(null)); + $this->assertEquals(false, $model->isAssociativeArray(array())); + $this->assertEquals(false, $model->isAssociativeArray(array(1, 2))); + $this->assertEquals(false, $model->isAssociativeArray(array(1 => 2))); + + $this->assertEquals(true, $model->isAssociativeArray(array('test' => 'a'))); + $this->assertEquals(true, $model->isAssociativeArray(array("a", "b" => 2))); + } + + /** + * @dataProvider serviceProvider + */ + public function testIncludes($class) + { + $this->assertTrue( + class_exists($class), + sprintf('Failed asserting class %s exists.', $class) + ); + } + + public function serviceProvider() + { + $classes = array(); + $path = dirname(dirname(dirname(__FILE__))) . '/src/Google/Service'; + foreach (glob($path . "/*.php") as $file) { + $classes[] = array('Google_Service_' . basename($file, '.php')); + } + + return $classes; + } + + public function testStrLen() + { + $this->assertEquals(0, Google_Utils::getStrLen(null)); + $this->assertEquals(0, Google_Utils::getStrLen(false)); + $this->assertEquals(0, Google_Utils::getStrLen("")); + + $this->assertEquals(1, Google_Utils::getStrLen(" ")); + $this->assertEquals(2, Google_Utils::getStrLen(" 1")); + $this->assertEquals(7, Google_Utils::getStrLen("0a\\n\n\r\n")); + } +} diff --git a/includes/google-api-php-client-master/tests/general/TaskTest.php b/includes/google-api-php-client-master/tests/general/TaskTest.php new file mode 100644 index 0000000..4aca138 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/TaskTest.php @@ -0,0 +1,765 @@ +<?php +/* + * Copyright 2014 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class TaskTest extends PHPUnit_Framework_TestCase +{ + private $client; + + private $mockedCallsCount = 0; + private $currentMockedCall = 0; + private $mockedCalls = array(); + + protected function setUp() + { + $this->client = new Google_Client(); + } + + /** + * @dataProvider defaultRestErrorProvider + * @expectedException Google_Service_Exception + */ + public function testRestRetryOffByDefault($errorCode, $errorBody = '{}') + { + $this->setNextResponse($errorCode, $errorBody)->makeRequest(); + } + + /** + * @dataProvider defaultRestErrorProvider + * @expectedException Google_Service_Exception + */ + public function testOneRestRetryWithError($errorCode, $errorBody = '{}') + { + $this->setTaskConfig(array('retries' => 1)); + $this->setNextResponses(2, $errorCode, $errorBody)->makeRequest(); + } + + /** + * @dataProvider defaultRestErrorProvider + * @expectedException Google_Service_Exception + */ + public function testMultipleRestRetriesWithErrors( + $errorCode, + $errorBody = '{}' + ) { + $this->setTaskConfig(array('retries' => 5)); + $this->setNextResponses(6, $errorCode, $errorBody)->makeRequest(); + } + + /** + * @dataProvider defaultRestErrorProvider + */ + public function testOneRestRetryWithSuccess($errorCode, $errorBody = '{}') + { + $this->setTaskConfig(array('retries' => 1)); + $result = $this->setNextResponse($errorCode, $errorBody) + ->setNextResponse(200, '{"success": true}') + ->makeRequest(); + + $this->assertEquals(array("success" => true), $result); + } + + /** + * @dataProvider defaultRestErrorProvider + */ + public function testMultipleRestRetriesWithSuccess( + $errorCode, + $errorBody = '{}' + ) { + $this->setTaskConfig(array('retries' => 5)); + $result = $this->setNextResponses(2, $errorCode, $errorBody) + ->setNextResponse(200, '{"success": true}') + ->makeRequest(); + + $this->assertEquals(array("success" => true), $result); + } + + /** + * @dataProvider defaultRestErrorProvider + * @expectedException Google_Service_Exception + */ + public function testCustomRestRetryMapReplacesDefaults( + $errorCode, + $errorBody = '{}' + ) { + $this->client->setClassConfig( + 'Google_Service_Exception', + array('retry_map' => array()) + ); + + $this->setTaskConfig(array('retries' => 5)); + $this->setNextResponse($errorCode, $errorBody)->makeRequest(); + } + + public function testCustomRestRetryMapAddsNewHandlers() + { + $this->client->setClassConfig( + 'Google_Service_Exception', + array('retry_map' => array('403' => Google_Config::TASK_RETRY_ALWAYS)) + ); + + $this->setTaskConfig(array('retries' => 5)); + $result = $this->setNextResponses(2, 403) + ->setNextResponse(200, '{"success": true}') + ->makeRequest(); + + $this->assertEquals(array("success" => true), $result); + } + + /** + * @expectedException Google_Service_Exception + * @dataProvider customLimitsProvider + */ + public function testCustomRestRetryMapWithCustomLimits($limit) + { + $this->client->setClassConfig( + 'Google_Service_Exception', + array('retry_map' => array('403' => $limit)) + ); + + $this->setTaskConfig(array('retries' => 5)); + $this->setNextResponses($limit + 1, 403)->makeRequest(); + } + + /** + * @dataProvider timeoutProvider + */ + public function testRestTimeouts($config, $minTime) + { + $this->setTaskConfig($config); + $this->setNextResponses($config['retries'], 500) + ->setNextResponse(200, '{"success": true}'); + + $this->assertTaskTimeGreaterThanOrEqual( + $minTime, + array($this, 'makeRequest'), + $config['initial_delay'] / 10 + ); + } + + /** + * @requires extension curl + * @dataProvider defaultCurlErrorProvider + * @expectedException Google_IO_Exception + */ + public function testCurlRetryOffByDefault($errorCode, $errorMessage = '') + { + $this->setNextResponseThrows($errorMessage, $errorCode)->makeRequest(); + } + + /** + * @requires extension curl + * @dataProvider defaultCurlErrorProvider + * @expectedException Google_IO_Exception + */ + public function testOneCurlRetryWithError($errorCode, $errorMessage = '') + { + $this->setTaskConfig(array('retries' => 1)); + $this->setNextResponsesThrow(2, $errorMessage, $errorCode)->makeRequest(); + } + + /** + * @requires extension curl + * @dataProvider defaultCurlErrorProvider + * @expectedException Google_IO_Exception + */ + public function testMultipleCurlRetriesWithErrors( + $errorCode, + $errorMessage = '' + ) { + $this->setTaskConfig(array('retries' => 5)); + $this->setNextResponsesThrow(6, $errorMessage, $errorCode)->makeRequest(); + } + + /** + * @requires extension curl + * @dataProvider defaultCurlErrorProvider + */ + public function testOneCurlRetryWithSuccess($errorCode, $errorMessage = '') + { + $this->setTaskConfig(array('retries' => 1)); + $result = $this->setNextResponseThrows($errorMessage, $errorCode) + ->setNextResponse(200, '{"success": true}') + ->makeRequest(); + + $this->assertEquals(array("success" => true), $result); + } + + /** + * @requires extension curl + * @dataProvider defaultCurlErrorProvider + */ + public function testMultipleCurlRetriesWithSuccess( + $errorCode, + $errorMessage = '' + ) { + $this->setTaskConfig(array('retries' => 5)); + $result = $this->setNextResponsesThrow(2, $errorMessage, $errorCode) + ->setNextResponse(200, '{"success": true}') + ->makeRequest(); + + $this->assertEquals(array("success" => true), $result); + } + + /** + * @requires extension curl + * @dataProvider defaultCurlErrorProvider + * @expectedException Google_IO_Exception + */ + public function testCustomCurlRetryMapReplacesDefaults( + $errorCode, + $errorMessage = '' + ) { + $this->client->setClassConfig( + 'Google_IO_Exception', + array('retry_map' => array()) + ); + + $this->setTaskConfig(array('retries' => 5)); + $this->setNextResponseThrows($errorMessage, $errorCode)->makeRequest(); + } + + /** + * @requires extension curl + */ + public function testCustomCurlRetryMapAddsNewHandlers() + { + $this->client->setClassConfig( + 'Google_IO_Exception', + array('retry_map' => array( + CURLE_COULDNT_RESOLVE_PROXY => Google_Config::TASK_RETRY_ALWAYS + )) + ); + + $this->setTaskConfig(array('retries' => 5)); + $result = $this->setNextResponsesThrow(2, '', CURLE_COULDNT_RESOLVE_PROXY) + ->setNextResponse(200, '{"success": true}') + ->makeRequest(); + + $this->assertEquals(array("success" => true), $result); + } + + /** + * @requires extension curl + * @expectedException Google_IO_Exception + * @dataProvider customLimitsProvider + */ + public function testCustomCurlRetryMapWithCustomLimits($limit) + { + $this->client->setClassConfig( + 'Google_IO_Exception', + array('retry_map' => array( + CURLE_COULDNT_RESOLVE_PROXY => $limit + )) + ); + + $this->setTaskConfig(array('retries' => 5)); + $this->setNextResponsesThrow($limit + 1, '', CURLE_COULDNT_RESOLVE_PROXY) + ->makeRequest(); + } + + /** + * @requires extension curl + * @dataProvider timeoutProvider + */ + public function testCurlTimeouts($config, $minTime) + { + $this->setTaskConfig($config); + $this->setNextResponsesThrow($config['retries'], '', CURLE_GOT_NOTHING) + ->setNextResponse(200, '{"success": true}'); + + $this->assertTaskTimeGreaterThanOrEqual( + $minTime, + array($this, 'makeRequest'), + $config['initial_delay'] / 10 + ); + } + + /** + * @dataProvider badTaskConfigProvider + */ + public function testBadTaskConfig($config, $message) + { + $this->setExpectedException('Google_Task_Exception', $message); + $this->setTaskConfig($config); + + new Google_Task_Runner( + $this->client, + '', + array($this, 'testBadTaskConfig') + ); + } + + /** + * @expectedException Google_Task_Exception + * @expectedExceptionMessage must be a valid callable + */ + public function testBadTaskCallback() + { + new Google_Task_Runner($this->client, '', 5); + } + + /** + * @expectedException Google_IO_Exception + */ + public function testTaskRetryOffByDefault() + { + $this->setNextTaskAllowedRetries(Google_Config::TASK_RETRY_ALWAYS) + ->runTask(); + } + + /** + * @expectedException Google_IO_Exception + */ + public function testOneTaskRetryWithError() + { + $this->setTaskConfig(array('retries' => 1)); + $this->setNextTasksAllowedRetries(2, Google_Config::TASK_RETRY_ALWAYS) + ->runTask(); + } + + /** + * @expectedException Google_IO_Exception + */ + public function testMultipleTaskRetriesWithErrors() + { + $this->setTaskConfig(array('retries' => 5)); + $this->setNextTasksAllowedRetries(6, Google_Config::TASK_RETRY_ALWAYS) + ->runTask(); + } + + public function testOneTaskRetryWithSuccess() + { + $this->setTaskConfig(array('retries' => 1)); + $result = $this->setNextTaskAllowedRetries(Google_Config::TASK_RETRY_ALWAYS) + ->setNextTaskReturnValue('success') + ->runTask(); + + $this->assertEquals('success', $result); + } + + public function testMultipleTaskRetriesWithSuccess() + { + $this->setTaskConfig(array('retries' => 5)); + $result = $this->setNextTasksAllowedRetries(2, Google_Config::TASK_RETRY_ALWAYS) + ->setNextTaskReturnValue('success') + ->runTask(); + + $this->assertEquals('success', $result); + } + + /** + * @expectedException Google_IO_Exception + * @dataProvider customLimitsProvider + */ + public function testTaskRetryWithCustomLimits($limit) + { + $this->setTaskConfig(array('retries' => 5)); + $this->setNextTasksAllowedRetries($limit + 1, $limit) + ->runTask(); + } + + /** + * @dataProvider timeoutProvider + */ + public function testTaskTimeouts($config, $minTime) + { + $this->setTaskConfig($config); + $this->setNextTasksAllowedRetries($config['retries'], $config['retries'] + 1) + ->setNextTaskReturnValue('success'); + + $this->assertTaskTimeGreaterThanOrEqual( + $minTime, + array($this, 'runTask'), + $config['initial_delay'] / 10 + ); + } + + public function testTaskWithManualRetries() + { + $this->setTaskConfig(array('retries' => 2)); + $this->setNextTasksAllowedRetries(2, Google_Config::TASK_RETRY_ALWAYS); + + $task = new Google_Task_Runner( + $this->client, + '', + array($this, 'runNextTask') + ); + + $this->assertTrue($task->canAttmpt()); + $this->assertTrue($task->attempt()); + + $this->assertTrue($task->canAttmpt()); + $this->assertTrue($task->attempt()); + + $this->assertTrue($task->canAttmpt()); + $this->assertTrue($task->attempt()); + + $this->assertFalse($task->canAttmpt()); + $this->assertFalse($task->attempt()); + } + + /** + * Provider for backoff configurations and expected minimum runtimes. + * + * @return array + */ + public function timeoutProvider() + { + $config = array('initial_delay' => .001, 'max_delay' => .01); + + return array( + array(array_merge($config, array('retries' => 1)), .001), + array(array_merge($config, array('retries' => 2)), .0015), + array(array_merge($config, array('retries' => 3)), .00225), + array(array_merge($config, array('retries' => 4)), .00375), + array(array_merge($config, array('retries' => 5)), .005625) + ); + } + + /** + * Provider for custom retry limits. + * + * @return array + */ + public function customLimitsProvider() + { + return array( + array(Google_Config::TASK_RETRY_NEVER), + array(Google_Config::TASK_RETRY_ONCE), + ); + } + + /** + * Provider for invalid task configurations. + * + * @return array + */ + public function badTaskConfigProvider() + { + return array( + array(array('initial_delay' => -1), 'must not be negative'), + array(array('max_delay' => 0), 'must be greater than 0'), + array(array('factor' => 0), 'must be greater than 0'), + array(array('jitter' => 0), 'must be greater than 0'), + array(array('retries' => -1), 'must not be negative') + ); + } + + /** + * Provider for the default REST errors. + * + * @return array + */ + public function defaultRestErrorProvider() + { + return array( + array(500), + array(503), + array(403, '{"error":{"errors":[{"reason":"rateLimitExceeded"}]}}'), + array(403, '{"error":{"errors":[{"reason":"userRateLimitExceeded"}]}}'), + ); + } + + /** + * Provider for the default cURL errors. + * + * @return array + */ + public function defaultCurlErrorProvider() + { + return array( + array(6), // CURLE_COULDNT_RESOLVE_HOST + array(7), // CURLE_COULDNT_CONNECT + array(28), // CURLE_OPERATION_TIMEOUTED + array(35), // CURLE_SSL_CONNECT_ERROR + array(52), // CURLE_GOT_NOTHING + ); + } + + /** + * Assert the minimum amount of time required to run a task. + * + * NOTE: Intentionally crude for brevity. + * + * @param float $expected The expected minimum execution time + * @param callable $callback The task to time + * @param float $delta Allowable relative error + * + * @throws PHPUnit_Framework_ExpectationFailedException + */ + public static function assertTaskTimeGreaterThanOrEqual( + $expected, + $callback, + $delta = 0.0 + ) { + $time = microtime(true); + + call_user_func($callback); + + self::assertThat( + microtime(true) - $time, + self::logicalOr( + self::greaterThan($expected), + self::equalTo($expected, $delta) + ) + ); + } + + /** + * Sets the task runner configurations. + * + * @param array $config The task runner configurations + */ + private function setTaskConfig(array $config) + { + $config += array( + 'initial_delay' => .0001, + 'max_delay' => .001, + 'factor' => 2, + 'jitter' => .5, + 'retries' => 1 + ); + $this->client->setClassConfig('Google_Task_Runner', $config); + } + + /** + * Sets the next responses. + * + * @param integer $count The number of responses + * @param string $code The response code + * @param string $body The response body + * @param array $headers The response headers + * + * @return TaskTest + */ + private function setNextResponses( + $count, + $code = '200', + $body = '{}', + array $headers = array() + ) { + while ($count-- > 0) { + $this->setNextResponse($code, $body, $headers); + } + + return $this; + } + + /** + * Sets the next response. + * + * @param string $code The response code + * @param string $body The response body + * @param array $headers The response headers + * + * @return TaskTest + */ + private function setNextResponse( + $code = '200', + $body = '{}', + array $headers = array() + ) { + $this->mockedCalls[$this->mockedCallsCount++] = array( + 'code' => (string) $code, + 'headers' => $headers, + 'body' => is_string($body) ? $body : json_encode($body) + ); + + return $this; + } + + /** + * Forces the next responses to throw an IO exception. + * + * @param integer $count The number of responses + * @param string $message The exception messages + * @param string $code The exception code + * + * @return TaskTest + */ + private function setNextResponsesThrow($count, $message, $code) + { + while ($count-- > 0) { + $this->setNextResponseThrows($message, $code); + } + + return $this; + } + + /** + * Forces the next response to throw an IO exception. + * + * @param string $message The exception messages + * @param string $code The exception code + * + * @return TaskTest + */ + private function setNextResponseThrows($message, $code) + { + $map = $this->client->getClassConfig('Google_IO_Exception', 'retry_map'); + $this->mockedCalls[$this->mockedCallsCount++] = new Google_IO_Exception( + $message, + $code, + null, + $map + ); + + return $this; + } + + /** + * Runs the defined request. + * + * @return array + */ + private function makeRequest() + { + $request = new Google_Http_Request('/test'); + + $io = $this->getMockBuilder('Google_IO_Abstract') + ->disableOriginalConstructor() + ->setMethods(array('makeRequest')) + ->getMockForAbstractClass(); + + $io->expects($this->exactly($this->mockedCallsCount)) + ->method('makeRequest') + ->will($this->returnCallback(array($this, 'getNextMockedCall'))); + + $this->client->setIo($io); + + return Google_Http_REST::execute($this->client, $request); + } + + /** + * Gets the next mocked response. + * + * @param Google_Http_Request $request The mocked request + * + * @return Google_Http_Request + */ + public function getNextMockedCall($request) + { + $current = $this->mockedCalls[$this->currentMockedCall++]; + + if ($current instanceof Exception) { + throw $current; + } + + $request->setResponseHttpCode($current['code']); + $request->setResponseHeaders($current['headers']); + $request->setResponseBody($current['body']); + + return $request; + } + + /** + * Sets the next task return value. + * + * @param mixed $value The next return value + * + * @return TaskTest + */ + private function setNextTaskReturnValue($value) + { + $this->mockedCalls[$this->mockedCallsCount++] = $value; + return $this; + } + + /** + * Sets the next exception `allowedRetries()` return value. + * + * @param boolean $allowedRetries The next `allowedRetries()` return value. + * + * @return TaskTest + */ + private function setNextTaskAllowedRetries($allowedRetries) + { + $this->mockedCalls[$this->mockedCallsCount++] = $allowedRetries; + return $this; + } + + /** + * Sets multiple exception `allowedRetries()` return value. + * + * @param integer $count The number of `allowedRetries()` return values. + * @param boolean $allowedRetries The `allowedRetries()` return value. + * + * @return TaskTest + */ + private function setNextTasksAllowedRetries($count, $allowedRetries) + { + while ($count-- > 0) { + $this->setNextTaskAllowedRetries($allowedRetries); + } + + return $this; + } + + /** + * Runs the defined task. + * + * @return mixed + */ + private function runTask() + { + $task = new Google_Task_Runner( + $this->client, + '', + array($this, 'runNextTask') + ); + + $exception = $this->getMockBuilder('Google_IO_Exception') + ->disableOriginalConstructor() + ->setMethods(array('allowedRetries')) + ->getMock(); + $exceptionCount = 0; + $exceptionCalls = array(); + + for ($i = 0; $i < $this->mockedCallsCount; $i++) { + if (is_int($this->mockedCalls[$i])) { + $exceptionCalls[$exceptionCount++] = $this->mockedCalls[$i]; + $this->mockedCalls[$i] = $exception; + } + } + + $exception->expects($this->exactly($exceptionCount)) + ->method('allowedRetries') + ->will( + new PHPUnit_Framework_MockObject_Stub_ConsecutiveCalls( + $exceptionCalls + ) + ); + + return $task->run(); + } + + /** + * Gets the next task return value. + * + * @return mixed + */ + public function runNextTask() + { + $current = $this->mockedCalls[$this->currentMockedCall++]; + + if ($current instanceof Exception) { + throw $current; + } + + return $current; + } +} diff --git a/includes/google-api-php-client-master/tests/general/URITemplateTest.php b/includes/google-api-php-client-master/tests/general/URITemplateTest.php new file mode 100644 index 0000000..a525f12 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/URITemplateTest.php @@ -0,0 +1,296 @@ +<?php +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +class URITemplateTest extends BaseTest +{ + public function testLevelOne() + { + $var = "value"; + $hello = "Hello World!"; + + $urit = new Google_Utils_URITemplate(); + $this->assertEquals( + "value", + $urit->parse("{var}", array("var" => $var)) + ); + $this->assertEquals( + "Hello%20World%21", + $urit->parse("{hello}", array("hello" => $hello)) + ); + } + + public function testLevelTwo() + { + $var = "value"; + $hello = "Hello World!"; + $path = "/foo/bar"; + + $urit = new Google_Utils_URITemplate(); + $this->assertEquals( + "value", + $urit->parse("{+var}", array("var" => $var)) + ); + $this->assertEquals( + "Hello%20World!", + $urit->parse("{+hello}", array("hello" => $hello)) + ); + $this->assertEquals( + "/foo/bar/here", + $urit->parse("{+path}/here", array("path" => $path)) + ); + $this->assertEquals( + "here?ref=/foo/bar", + $urit->parse("here?ref={+path}", array("path" => $path)) + ); + $this->assertEquals( + "X#value", + $urit->parse("X{#var}", array("var" => $var)) + ); + $this->assertEquals( + "X#Hello%20World!", + $urit->parse("X{#hello}", array("hello" => $hello)) + ); + } + + public function testLevelThree() + { + $var = "value"; + $hello = "Hello World!"; + $empty = ''; + $path = "/foo/bar"; + $x = "1024"; + $y = "768"; + + $urit = new Google_Utils_URITemplate(); + $this->assertEquals( + "map?1024,768", + $urit->parse("map?{x,y}", array("x" => $x, "y" => $y)) + ); + $this->assertEquals( + "1024,Hello%20World%21,768", + $urit->parse("{x,hello,y}", array("x" => $x, "y" => $y, "hello" => $hello)) + ); + + $this->assertEquals( + "1024,Hello%20World!,768", + $urit->parse("{+x,hello,y}", array("x" => $x, "y" => $y, "hello" => $hello)) + ); + $this->assertEquals( + "/foo/bar,1024/here", + $urit->parse("{+path,x}/here", array("x" => $x, "path" => $path)) + ); + + $this->assertEquals( + "#1024,Hello%20World!,768", + $urit->parse("{#x,hello,y}", array("x" => $x, "y" => $y, "hello" => $hello)) + ); + $this->assertEquals( + "#/foo/bar,1024/here", + $urit->parse("{#path,x}/here", array("x" => $x, "path" => $path)) + ); + + $this->assertEquals( + "X.value", + $urit->parse("X{.var}", array("var" => $var)) + ); + $this->assertEquals( + "X.1024.768", + $urit->parse("X{.x,y}", array("x" => $x, "y" => $y)) + ); + + $this->assertEquals( + "X.value", + $urit->parse("X{.var}", array("var" => $var)) + ); + $this->assertEquals( + "X.1024.768", + $urit->parse("X{.x,y}", array("x" => $x, "y" => $y)) + ); + + $this->assertEquals( + "/value", + $urit->parse("{/var}", array("var" => $var)) + ); + $this->assertEquals( + "/value/1024/here", + $urit->parse("{/var,x}/here", array("x" => $x, "var" => $var)) + ); + + $this->assertEquals( + ";x=1024;y=768", + $urit->parse("{;x,y}", array("x" => $x, "y" => $y)) + ); + $this->assertEquals( + ";x=1024;y=768;empty", + $urit->parse("{;x,y,empty}", array("x" => $x, "y" => $y, "empty" => $empty)) + ); + + $this->assertEquals( + "?x=1024&y=768", + $urit->parse("{?x,y}", array("x" => $x, "y" => $y)) + ); + $this->assertEquals( + "?x=1024&y=768&empty=", + $urit->parse("{?x,y,empty}", array("x" => $x, "y" => $y, "empty" => $empty)) + ); + + $this->assertEquals( + "?fixed=yes&x=1024", + $urit->parse("?fixed=yes{&x}", array("x" => $x, "y" => $y)) + ); + $this->assertEquals( + "&x=1024&y=768&empty=", + $urit->parse("{&x,y,empty}", array("x" => $x, "y" => $y, "empty" => $empty)) + ); + } + + public function testLevelFour() + { + $values = array( + 'var' => "value", + 'hello' => "Hello World!", + 'path' => "/foo/bar", + 'list' => array("red", "green", "blue"), + 'keys' => array("semi" => ";", "dot" => ".", "comma" => ","), + ); + + $tests = array( + "{var:3}" => "val", + "{var:30}" => "value", + "{list}" => "red,green,blue", + "{list*}" => "red,green,blue", + "{keys}" => "semi,%3B,dot,.,comma,%2C", + "{keys*}" => "semi=%3B,dot=.,comma=%2C", + "{+path:6}/here" => "/foo/b/here", + "{+list}" => "red,green,blue", + "{+list*}" => "red,green,blue", + "{+keys}" => "semi,;,dot,.,comma,,", + "{+keys*}" => "semi=;,dot=.,comma=,", + "{#path:6}/here" => "#/foo/b/here", + "{#list}" => "#red,green,blue", + "{#list*}" => "#red,green,blue", + "{#keys}" => "#semi,;,dot,.,comma,,", + "{#keys*}" => "#semi=;,dot=.,comma=,", + "X{.var:3}" => "X.val", + "X{.list}" => "X.red,green,blue", + "X{.list*}" => "X.red.green.blue", + "X{.keys}" => "X.semi,%3B,dot,.,comma,%2C", + "X{.keys*}" => "X.semi=%3B.dot=..comma=%2C", + "{/var:1,var}" => "/v/value", + "{/list}" => "/red,green,blue", + "{/list*}" => "/red/green/blue", + "{/list*,path:4}" => "/red/green/blue/%2Ffoo", + "{/keys}" => "/semi,%3B,dot,.,comma,%2C", + "{/keys*}" => "/semi=%3B/dot=./comma=%2C", + "{;hello:5}" => ";hello=Hello", + "{;list}" => ";list=red,green,blue", + "{;list*}" => ";list=red;list=green;list=blue", + "{;keys}" => ";keys=semi,%3B,dot,.,comma,%2C", + "{;keys*}" => ";semi=%3B;dot=.;comma=%2C", + "{?var:3}" => "?var=val", + "{?list}" => "?list=red,green,blue", + "{?list*}" => "?list=red&list=green&list=blue", + "{?keys}" => "?keys=semi,%3B,dot,.,comma,%2C", + "{?keys*}" => "?semi=%3B&dot=.&comma=%2C", + "{&var:3}" => "&var=val", + "{&list}" => "&list=red,green,blue", + "{&list*}" => "&list=red&list=green&list=blue", + "{&keys}" => "&keys=semi,%3B,dot,.,comma,%2C", + "{&keys*}" => "&semi=%3B&dot=.&comma=%2C", + "find{?list*}" => "find?list=red&list=green&list=blue", + "www{.list*}" => "www.red.green.blue" + + ); + + $urit = new Google_Utils_URITemplate(); + + foreach ($tests as $input => $output) { + $this->assertEquals($output, $urit->parse($input, $values), $input . " failed"); + } + } + + public function testMultipleAnnotations() + { + $var = "value"; + $hello = "Hello World!"; + $urit = new Google_Utils_URITemplate(); + $this->assertEquals( + "http://www.google.com/Hello%20World!?var=value", + $urit->parse( + "http://www.google.com/{+hello}{?var}", + array("var" => $var, "hello" => $hello) + ) + ); + $params = array( + "playerId" => "me", + "leaderboardId" => "CgkIhcG1jYEbEAIQAw", + "timeSpan" => "ALL_TIME", + "other" => "irrelevant" + ); + $this->assertEquals( + "players/me/leaderboards/CgkIhcG1jYEbEAIQAw/scores/ALL_TIME", + $urit->parse( + "players/{playerId}/leaderboards/{leaderboardId}/scores/{timeSpan}", + $params + ) + ); + } + + /** + * This test test against the JSON files defined in + * https://github.com/uri-templates/uritemplate-test + * + * We don't ship these tests with it, so they'll just silently + * skip unless provided - this is mainly for use when + * making specific URI template changes and wanting + * to do a full regression check. + */ + public function testAgainstStandardTests() + { + $location = "../../uritemplate-test/*.json"; + + $urit = new Google_Utils_URITemplate(); + foreach (glob($location) as $file) { + $test = json_decode(file_get_contents($file), true); + foreach ($test as $title => $testsets) { + foreach ($testsets['testcases'] as $cases) { + $input = $cases[0]; + $output = $cases[1]; + if ($output == false) { + continue; // skipping negative tests for now + } else if (is_array($output)) { + $response = $urit->parse($input, $testsets['variables']); + $this->assertContains( + $response, + $output, + $input . " failed from " . $title + ); + } else { + $this->assertEquals( + $output, + $urit->parse($input, $testsets['variables']), + $input . " failed." + ); + } + } + } + } + } +} diff --git a/includes/google-api-php-client-master/tests/general/testdata/cacert.json b/includes/google-api-php-client-master/tests/general/testdata/cacert.json new file mode 100644 index 0000000..3de7c44 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/testdata/cacert.json @@ -0,0 +1 @@ +{"a": "-----BEGIN CERTIFICATE-----\nMIICrDCCAlagAwIBAgIJAIhhwVyFHrVfMA0GCSqGSIb3DQEBBQUAMG8xCzAJBgNV\nBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX\naWRnaXRzIFB0eSBMdGQxCjAIBgNVBAsTAWExCjAIBgNVBAMTAWIxEDAOBgkqhkiG\n9w0BCQEWAWMwHhcNMTIwMjE5MDExMzQxWhcNMTUwMjE4MDExMzQxWjBvMQswCQYD\nVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQg\nV2lkZ2l0cyBQdHkgTHRkMQowCAYDVQQLEwFhMQowCAYDVQQDEwFiMRAwDgYJKoZI\nhvcNAQkBFgFjMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM4Aozh3TMZYcPx7MHln\nD8MtyVUjzo6OdT32JwRHzHHNMMm88lNVfLYIT9C/jgXlDqG0h5wSClMvTQbdihNd\nFOkCAwEAAaOB1DCB0TAdBgNVHQ4EFgQUv0Ahb7HD9TLfdtLeaatjFj91NqYwgaEG\nA1UdIwSBmTCBloAUv0Ahb7HD9TLfdtLeaatjFj91Nqahc6RxMG8xCzAJBgNVBAYT\nAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRn\naXRzIFB0eSBMdGQxCjAIBgNVBAsTAWExCjAIBgNVBAMTAWIxEDAOBgkqhkiG9w0B\nCQEWAWOCCQCIYcFchR61XzAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA0EA\nKAbxbWHsaVPnYc0YqG/Pn4HbcI1+xnVQSt3hdzq+yC0lP9H7hBMCVSykhhBkZ5XQ\nHA2t6LHuYsjcCO+LBX/4fA==\n-----END CERTIFICATE-----"}
\ No newline at end of file diff --git a/includes/google-api-php-client-master/tests/general/testdata/cacert.pem b/includes/google-api-php-client-master/tests/general/testdata/cacert.pem new file mode 100644 index 0000000..c95977b --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/testdata/cacert.pem @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE----- +MIICrDCCAlagAwIBAgIJAIhhwVyFHrVfMA0GCSqGSIb3DQEBBQUAMG8xCzAJBgNV +BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX +aWRnaXRzIFB0eSBMdGQxCjAIBgNVBAsTAWExCjAIBgNVBAMTAWIxEDAOBgkqhkiG +9w0BCQEWAWMwHhcNMTIwMjE5MDExMzQxWhcNMTUwMjE4MDExMzQxWjBvMQswCQYD +VQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQg +V2lkZ2l0cyBQdHkgTHRkMQowCAYDVQQLEwFhMQowCAYDVQQDEwFiMRAwDgYJKoZI +hvcNAQkBFgFjMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM4Aozh3TMZYcPx7MHln +D8MtyVUjzo6OdT32JwRHzHHNMMm88lNVfLYIT9C/jgXlDqG0h5wSClMvTQbdihNd +FOkCAwEAAaOB1DCB0TAdBgNVHQ4EFgQUv0Ahb7HD9TLfdtLeaatjFj91NqYwgaEG +A1UdIwSBmTCBloAUv0Ahb7HD9TLfdtLeaatjFj91Nqahc6RxMG8xCzAJBgNVBAYT +AkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRn +aXRzIFB0eSBMdGQxCjAIBgNVBAsTAWExCjAIBgNVBAMTAWIxEDAOBgkqhkiG9w0B +CQEWAWOCCQCIYcFchR61XzAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA0EA +KAbxbWHsaVPnYc0YqG/Pn4HbcI1+xnVQSt3hdzq+yC0lP9H7hBMCVSykhhBkZ5XQ +HA2t6LHuYsjcCO+LBX/4fA== +-----END CERTIFICATE-----
\ No newline at end of file diff --git a/includes/google-api-php-client-master/tests/general/testdata/cert.p12 b/includes/google-api-php-client-master/tests/general/testdata/cert.p12 Binary files differnew file mode 100644 index 0000000..acea8f6 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/testdata/cert.p12 diff --git a/includes/google-api-php-client-master/tests/general/testdata/privkey.pem b/includes/google-api-php-client-master/tests/general/testdata/privkey.pem new file mode 100644 index 0000000..0a4d3a0 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/testdata/privkey.pem @@ -0,0 +1,9 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIBOwIBAAJBAM4Aozh3TMZYcPx7MHlnD8MtyVUjzo6OdT32JwRHzHHNMMm88lNV +fLYIT9C/jgXlDqG0h5wSClMvTQbdihNdFOkCAwEAAQJBAJuMo7KpcpF6iqY7Jtkk +1yQb2KCvTvMZ4rGMwt1akaeDW2noyqCeO675gFBtlizgcRsybealQVQgGX4E5VqF +UJkCIQDzJZZi2jloDXcyyy2rEa4mj4RnrnIYsDMJ55XMWJ9c9wIhANjkY97FSRX3 +WSdRFqXd3Pc4URUho+rCcPibafMOwAUfAiAa58ngXm2DyhmqkTkYePhgY/kuz+ro +OHctXWcCGbxouQIgLC5qAakieC0Ipi+oc2U8a8e3DJzrrRiqtpnB/VcV2nUCIQC2 +DXrpyt6jjVIzs4jI5Cl3QGLL6TZ8FqpyonU/1ARuhA== +-----END RSA PRIVATE KEY-----
\ No newline at end of file diff --git a/includes/google-api-php-client-master/tests/general/testdata/service-12345.json b/includes/google-api-php-client-master/tests/general/testdata/service-12345.json new file mode 100644 index 0000000..4160d93 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/testdata/service-12345.json @@ -0,0 +1,7 @@ +{ + "private_key_id": "1936f241be592afc6f3a6d309f75cbf5229d3e75", + "private_key": "-----BEGIN PRIVATE KEY-----\nMIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALatQBvyVfVxdKFT\n3jMHUk0hSEs9Z3WaEw1q+597Fo+f2j5xOIzzzHKX4twWtSYWpSNTaVsFBX7cYpKu\nxYD8oiFnb/Djmud36h4yZsinmoTAi8tn7ldHMi3VICt05IKNRYPU14AQ/FANBvzZ\nxPUxVmf2Q8qZ1/HhXRGE0GLhJGMtAgMBAAECgYAB1BogLXzOyCPyuXQv7pLUUtD2\nb9bpRnGKYNfD8Od46JC2r0txnb8eJocOzOtjRjbA88TKNHKpomsaLMWtVNoKlzMX\n4DdWk0we4knIa2ZNc3rHYQIHVTESYUa3fH/I/t2XBmbiwyYdegfXl7OmxHb9kekk\nQ1HBKq2SA2LRHWydwQJBAPIdT6s1KvUVsdW7JVu3MxMSlSc2dyQV9ay44wuxYaVV\nfvV7BM/J+/oHSh4GU2Os+kqRHOuouHm2TQ3gsQlBsqcCQQDBJ0iDoYZozVQB36eE\nlPAzoK6H+U21rx5EErFNYu97OKWn+z8kwbGtBU8CSJhkY/OQGmpg6MpoJO/Md03Y\nxVoLAkAFeZg1nOwtwqHU3XiIzGnBQqhQzLCBBmYZ08x+lTJKFNbcIj4HnN+v1b5d\nU3NLS7wVN5bZ1WTmi7LOX4hhVzT9AkBBbQQECleT8lENXWvJ3gVLB5d22Xx4GTxA\nRLCoDOYfr/103Ab0dWOwvsaXeG2eO7kJy9jSwKenBTPw50yIK7knAkBC2J/z6X7l\nB/dDRTxdd0gCG7JIy9N3cUgHBmDH2eycmPncWGJ+aZrK1p9NmAytP+Ksi4AGMJX5\nH5cT1I/UOEn1\n-----END PRIVATE KEY-----\n", + "client_email": "12345-is5nq94smihmoa2k0567jab6u6vj278c@developer.gserviceaccount.com", + "client_id": "12345-is5nq94smihmoa2k0567jab6u6vj278c.apps.googleusercontent.com", + "type": "service_account" +}
\ No newline at end of file diff --git a/includes/google-api-php-client-master/tests/general/testdata/service-rsa-12345.json b/includes/google-api-php-client-master/tests/general/testdata/service-rsa-12345.json new file mode 100644 index 0000000..a6a2df0 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/testdata/service-rsa-12345.json @@ -0,0 +1,7 @@ +{ + "private_key_id": "1936f241be592afc6f3a6d309f75cbf5229d3e75", + "private_key": "-----BEGIN RSA PRIVATE KEY-----MIIBOwIBAAJBAM4Aozh3TMZYcPx7MHlnD8MtyVUjzo6OdT32JwRHzHHNMMm88lNVfLYIT9C/jgXlDqG0h5wSClMvTQbdihNdFOkCAwEAAQJBAJuMo7KpcpF6iqY7Jtkk1yQb2KCvTvMZ4rGMwt1akaeDW2noyqCeO675gFBtlizgcRsybealQVQgGX4E5VqFUJkCIQDzJZZi2jloDXcyyy2rEa4mj4RnrnIYsDMJ55XMWJ9c9wIhANjkY97FSRX3WSdRFqXd3Pc4URUho+rCcPibafMOwAUfAiAa58ngXm2DyhmqkTkYePhgY/kuz+roOHctXWcCGbxouQIgLC5qAakieC0Ipi+oc2U8a8e3DJzrrRiqtpnB/VcV2nUCIQC2DXrpyt6jjVIzs4jI5Cl3QGLL6TZ8FqpyonU/1ARuhA==-----END RSA PRIVATE KEY-----", + "client_email": "12345-is5nq94smihmoa2k0567jab6u6vj278c@developer.gserviceaccount.com", + "client_id": "12345-is5nq94smihmoa2k0567jab6u6vj278c.apps.googleusercontent.com", + "type": "service_account" +}
\ No newline at end of file diff --git a/includes/google-api-php-client-master/tests/general/testdata/test.ini b/includes/google-api-php-client-master/tests/general/testdata/test.ini new file mode 100644 index 0000000..1f55277 --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/testdata/test.ini @@ -0,0 +1,7 @@ +; Test.ini file +application_name = My Test application +auth_class = Google_Auth_OAuth2 +[classes] +Google_Auth_OAuth2[client_id] = 12345.apps.googleusercontent.com +Google_Auth_OAuth2[client_secret] = gjfiwnGinpena3 +Google_Auth_OAuth2[redirect_uri] = http://example.com
\ No newline at end of file diff --git a/includes/google-api-php-client-master/tests/general/testdata/test_public_key.pem b/includes/google-api-php-client-master/tests/general/testdata/test_public_key.pem new file mode 100644 index 0000000..ebca23e --- /dev/null +++ b/includes/google-api-php-client-master/tests/general/testdata/test_public_key.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDQjCCAiqgAwIBAgIJAMJ1Z12ZdGgLMA0GCSqGSIb3DQEBBQUAMB8xHTAbBgNV +BAMTFHRlc3Qtc2VydmljZS1hY2NvdW50MB4XDTExMDgyMzIwNTczNFoXDTIxMDgy +MDIwNTczNFowHzEdMBsGA1UEAxMUdGVzdC1zZXJ2aWNlLWFjY291bnQwggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDpbFTjUXd02HFluI2G0kGKp1J5K2F8 +cYr7hKXHcsmKo6S/5g8AEYnnV1fEbiopoGt7UWV4T0LA99K0gqQ7QmvZKvFHXlgR +XJH1aO+ZipVs3ycZOcjBMcw4hspFSi4IyQta64gASFUT5NaxRVGhzAuPlzH09dZQ +RJ0NL54HccGNzEDaLx5usB8t2aRHbE4zRWJlNIsjgWnfVoiXwOv5oRhyfFMIaTu1 +eIp3XP1QAv5cuYS2U4ZJ+J7Gzg6E7t4PWqK7rGjnc5BJsVIoiL77K/xKUWABNgHz +b6JuiEp3LX9f2H5+CKo/IJFWoyIYWdZiu69LZivife9sTXmDnOcZkisRAgMBAAGj +gYAwfjAdBgNVHQ4EFgQU0RkXlevVO2zuTFP/ksFUbNkpm+kwTwYDVR0jBEgwRoAU +0RkXlevVO2zuTFP/ksFUbNkpm+mhI6QhMB8xHTAbBgNVBAMTFHRlc3Qtc2Vydmlj +ZS1hY2NvdW50ggkAwnVnXZl0aAswDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUF +AAOCAQEAT+3VKautn+uV7ZQWbfx6xrGaDZ5wVK9FWOTVKsjdXyp11jtoVkDONLz5 +3J7wgppZWabPargIZUHe9/P6j7QTgNV2na2thGHtVRIRyDECnVrvhCn/IDpMeJjj +IAuysmSITHGEwb4AvRC5HdqfWzBqAvRhjJ2crcHZpx5/KkYZgJz9ylGJCynxpbHU +1aRu4qpkQNB4t4z5EzNOSLkFw9vEtm0hNX76CsNJFd0XDEKDQI2Lsc0WfDzQ1ZQH +UVzIoTmQDkYGylQOBVyxZoGI6fuSo8c2I1BKvsdBGhSPjePNvaKUbmLSwUsranhX +2Y1kn7xbDTUHymZ0+g5rDM9kWmhZfg== +-----END CERTIFICATE----- |