Example #1
0
 public function testShouldSetAConfiguration()
 {
     VCR::configure()->setCassettePath('tests');
     VCR::turnOn();
     $this->assertEquals('tests', VCR::configure()->getCassettePath());
     VCR::turnOff();
 }
 /**
  * @test
  * @vcr should_create_and_delete_user_and_return_empty_array.json
  */
 public function should_create_and_delete_user_and_return_empty_array()
 {
     VCR::turnOn();
     VCR::insertCassette('should_create_user_and_return_user_id.json');
     $client = new Client();
     $client->setOption('base_url', $this->url);
     $client->authenticate($this->username, $this->password, 'http_drupal_login');
     $user = $client->api('user')->userCreate($this->test_user_params());
     $this->assertObjectHasAttribute('uid', $user);
     $this->assertNotNull($user->uid);
     VCR::eject();
     VCR::turnOff();
     VCR::turnOn();
     VCR::insertCassette('should_add_role_to_user.json');
     $client = new Client();
     $client->setOption('base_url', $this->url);
     $client->authenticate($this->username, $this->password, 'http_drupal_login');
     $results2 = $client->api('user')->userAddRole($user, 'authenticated user');
     $this->assertEquals('Role successfully added', $results2['message']);
     VCR::eject();
     VCR::turnOff();
     VCR::turnOn();
     VCR::insertCassette('should_create_and_delete_user_and_return_empty_array.json');
     $client = new Client();
     $client->setOption('base_url', $this->url);
     $client->authenticate($this->username, $this->password, 'http_drupal_login');
     $results3 = $client->api('user')->userDelete($user);
     $this->assertEmpty($results3);
     VCR::eject();
     VCR::turnOff();
 }
Example #3
0
 public function testFindNoPhotoForACategory()
 {
     VCR::insertCassette('categories.yml');
     $category = Unsplash\Category::find(2);
     $photos = $category->photos(2000);
     VCR::eject();
     $this->assertEquals(0, $photos->count());
 }
Example #4
0
 public function testFindUserLikedPhoto()
 {
     VCR::insertCassette('users.yml');
     $user = Unsplash\User::find('dechuck');
     $likes = $user->likes();
     VCR::eject();
     $this->assertNotEmpty($likes);
 }
 public function testFindCuratedBatchPhotos()
 {
     VCR::insertCassette('curated_batches.yml');
     $curatedBatch = Unsplash\CuratedBatch::find(68);
     $photos = $curatedBatch->photos();
     VCR::eject();
     $this->assertEquals(10, $photos->count());
 }
Example #6
0
 public function testFindTotalStats()
 {
     VCR::insertCassette('stats.yml');
     $totalStats = Unsplash\Stat::total();
     VCR::eject();
     $this->assertEquals($this->total['photo_downloads'], $totalStats->photo_downloads);
     $this->assertEquals($this->total['batch_downloads'], $totalStats->batch_downloads);
 }
 function testPostRequestIsUnsuccessful()
 {
     \VCR\VCR::insertCassette('gathercontent_post_projects_failure.yml');
     $subject = new HTTPClient('*****@*****.**', 'bogus-api-key');
     $response = $subject->post('https://api.gathercontent.com/projects', ['account_id' => '20225', 'name' => 'Project Name'], ['Accept: application/vnd.gathercontent.v0.5+json']);
     $this->assertNotEquals(200, $response->status);
     $this->assertEquals('Invalid credentials.', $response->body);
 }
 public function testRequest()
 {
     VCR::insertCassette('endpoint.yml');
     $res = Unsplash\Endpoint::__callStatic('get', ['categories/2', []]);
     VCR::eject();
     $body = json_decode($res->getBody());
     $this->assertEquals(2, $body->id);
 }
 public function testRequestSendThroughClient()
 {
     Unsplash\HttpClient::$connection = $this->connection;
     VCR::insertCassette('categories.yml');
     $response = (new Unsplash\HttpClient())->send("get", ['categories/2']);
     $body = json_decode($response->getBody(), true);
     VCR::eject();
     $this->assertEquals(2, $body['id']);
 }
Example #10
0
 public function testRandomPhotoWithFilters()
 {
     VCR::insertCassette('photos.yml');
     $filters = ['category' => [2, 3], 'featured' => true, 'username' => 'andy_brunner', 'query' => 'ice', 'w' => 100, 'h' => 100];
     $photo = Unsplash\Photo::random($filters);
     VCR::eject();
     $this->assertEquals('ZUaqqMxtxYk', $photo->id);
     $this->assertEquals('https://unsplash.imgix.net/photo-1428681756973-d318f055795a?q=75&fm=jpg&w=100&h=100&fit=max&s=b223d24e28ba1ced6731e98d46cd5f83', $photo->urls['custom']);
 }
Example #11
0
 public function testUnlikePhoto()
 {
     VCR::insertCassette('photos.yml');
     $photo = Unsplash\Photo::find('j0g8taxHZa0');
     $like = $photo->like();
     $unlike = $photo->unlike();
     VCR::eject();
     $this->assertTrue($unlike);
 }
Example #12
0
 public function testUpdateUser()
 {
     $this->markTestIncomplete('Due to an issue with VCR, we do not run this test.');
     $newInstagramUsername = '******' . time();
     VCR::insertCassette('users.yml');
     $user = Unsplash\User::find('dechuck');
     $user->update(['instagram_username' => $newInstagramUsername]);
     VCR::eject();
     $this->assertEquals($newInstagramUsername, $user->instagram_username);
 }
 /**
  * @test
  * @vcr should_pass_basic_auth_and_drupal_auth_with_username_and_password.json
  */
 public function should_pass_basic_auth_and_drupal_auth_with_username_and_password()
 {
     VCR::turnOn();
     VCR::insertCassette('should_pass_basic_auth_and_drupal_auth_with_username_and_password.json');
     $client = new Client();
     $client->setOption('base_url', $this->url);
     $client->authenticate($this->username, $this->password, 'http_drupal_login');
     $results = $client->api('nodes')->createNode($this->test_node_params());
     $this->assertObjectHasAttribute('nid', $results);
     VCR::eject();
     VCR::turnOff();
 }
 /**
  * {inheritDoc}
  */
 public function setMatchers()
 {
     parent::setMatchers();
     VCR::configure()->addRequestMatcher('exception', function (Request $first, Request $second) {
         $first = json_decode($first->getBody());
         $second = json_decode($second->getBody());
         $this->assertSame($first->events[0]->exceptions[0]->errorClass, $second->events[0]->exceptions[0]->errorClass);
         $this->assertSame($first->events[0]->metaData->php_version, $second->events[0]->metaData->php_version);
         return true;
     });
     VCR::configure()->enableRequestMatchers(['method', 'url', 'host', 'post_fields', 'exception']);
 }
 /**
  * {inheritDoc}
  */
 public function setMatchers()
 {
     parent::setMatchers();
     VCR::configure()->addRequestMatcher('exception', function (Request $first, Request $second) {
         $first = json_decode(gzuncompress(base64_decode($first->getBody())));
         $second = json_decode(gzuncompress(base64_decode($second->getBody())));
         $this->assertSame($first->message, $second->message);
         $this->assertSame($first->extra->php_version, $second->extra->php_version);
         return true;
     });
     VCR::configure()->enableRequestMatchers(['method', 'url', 'host', 'post_fields', 'exception']);
 }
 /**
  * {inheritDoc}
  */
 public function setMatchers()
 {
     parent::setMatchers();
     VCR::configure()->addRequestMatcher('exception', function (Request $first, Request $second) {
         $first = simplexml_load_string($first->getBody());
         $second = simplexml_load_string($second->getBody());
         $this->assertSame((string) $first->error->class, (string) $second->error->class);
         $this->assertSame((string) $first->request->params->var, (string) $second->request->params->var);
         return true;
     });
     VCR::configure()->enableRequestMatchers(['method', 'url', 'host', 'post_fields', 'exception']);
 }
 function testSaveAsDownloadsFileToTarget()
 {
     \VCR\VCR::turnOn();
     \VCR\VCR::insertCassette('gathercontent_save_file.yml');
     $file_url = 'https://gathercontent.s3.amazonaws.com/filename_hash';
     $target_filename = $this->tempDir() . '/file.jpg';
     $this->assertFileNotExists($target_filename);
     $subject = new Downloader($file_url);
     $subject->saveAs($target_filename);
     $this->assertFileExists($target_filename);
     $this->assertEquals('file-contents', file_get_contents($target_filename));
     \VCR\VCR::eject();
     \VCR\VCR::turnOff();
 }
 /**
  * Gets the URL with file_get_contents, explicitly setting follow_location 
  * in the context
  */
 public function testWithVcrFollowLocation()
 {
     \VCR\VCR::insertCassette('with_follow_location');
     $opts = array('http' => array('follow_location' => 1));
     $context = stream_context_create($opts);
     $source = file_get_contents(self::URL, false, $context);
     # Make sure contents were got
     $this->assertNotEmpty($source);
     # Make sure there's nothing before the contents
     $this->assertSame(0, strpos($source, '<!doctype html>'), 'Source starts with "' . substr($source, 0, 15) . '"');
     # Make sure we grabbed the right thing
     $this->assertContains('<title>abeger - Gravatar Profile</title>', $source);
     \VCR\VCR::eject();
 }
 /**
  * @test
  * @@vcr info_status
  */
 public function get_status()
 {
     VCR::turnOn();
     //VCR::insertCassette('authenticate');
     VCR::insertCassette('info_status');
     //Arrange
     $sauce_api = new Client();
     //Act
     $who = $sauce_api->api('provider_information')->status();
     //Assert
     $this->assertArrayHasKey('service_operational', $who);
     // To stop recording requests, eject the cassette
     VCR::eject();
     // Turn off VCR to stop intercepting requests
     VCR::turnOff();
 }
Example #20
0
 /**
  * @test
  * @@vcr show_activity
  */
 public function should_get_activity()
 {
     VCR::turnOn();
     //VCR::insertCassette('authenticate');
     VCR::insertCassette('show_activity');
     //Arrange
     $sauce_api = new Client();
     $sauce_api->authenticate($_ENV['USERNAME_KEY'], $_ENV['TOKEN_PASSWORD'], Client::AUTH_HTTP_PASSWORD);
     //Act
     $what = $sauce_api->api('current_user')->getUserActivity($_ENV['USERNAME_KEY']);
     //Assert
     $this->assertArrayHasKey('subaccounts', $what);
     // To stop recording requests, eject the cassette
     VCR::eject();
     // Turn off VCR to stop intercepting requests
     VCR::turnOff();
 }
 public function testExecuteQueryWithInvalidAPIKey()
 {
     \VCR\VCR::turnOn();
     \VCR\VCR::insertCassette('search_without_valid_api_key');
     $temp_key = getenv('TWINGLY_SEARCH_KEY');
     putenv('TWINGLY_SEARCH_KEY=wrong');
     $c = new Client();
     try {
         $q = $c->query();
         $q->pattern = 'something';
         $c->execute_query($q);
         $this->fail('Should throw AuthException.');
     } catch (AuthException $e) {
         $this->assertEquals('The API key does not exist.', $e->getMessage());
         putenv('TWINGLY_SEARCH_KEY=' . $temp_key);
     }
     \VCR\VCR::turnOff();
 }
 /**
  * {inheritDoc}
  */
 public function setMatchers()
 {
     parent::setMatchers();
     VCR::configure()->addRequestMatcher('exception', function (Request $first, Request $second) {
         $first = json_decode($first->getBody())->data->body->trace->exception;
         $second = json_decode($second->getBody())->data->body->trace->exception;
         // The below asserts will throw exceptions, however Rollbar swallows them up and PHPUnit doesn't detect
         // them. So we catch and set the exception to be rethrown when outside Rollbar.
         try {
             $this->assertSame($first->class, $second->class);
             $this->assertSame($first->message, $second->message);
         } catch (PHPUnit_Framework_ExpectationFailedException $e) {
             $this->requestsMatchedException = $e;
         }
         return true;
     });
     VCR::configure()->enableRequestMatchers(['method', 'url', 'host', 'post_fields', 'exception']);
 }
Example #23
0
 public function setUp()
 {
     // Only load env file if it exist.
     // It will use the env variable on server if there's no file
     if (file_exists(__DIR__ . '/.env')) {
         $dotenv = new Dotenv(__DIR__);
         $dotenv->load();
     }
     $this->provider = m::mock('Crew\\Unsplash\\Provider', ['clientId' => 'mock_client_id', 'clientSecret' => 'mock_secret', 'redirectUri' => 'none']);
     $this->provider->clientId = 'mock_client_id';
     $this->accessToken = new AccessToken(['access_token' => getenv('ACCESS_TOKEN')]);
     VCR::configure()->setStorage('json')->addRequestMatcher('validate_authorization', function (\VCR\Request $first, \VCR\Request $second) {
         if ($first->getHeaders()['Authorization'] == $second->getHeaders()['Authorization']) {
             return true;
         } else {
             return false;
         }
     })->enableRequestMatchers(array('method', 'url', 'host', 'query_string', 'body', 'post_fields', 'validate_authorization'));
     VCR::turnOn();
 }
 /**
  * If you have made a change and VCR is complaining that the request doesn't match,
  * delete the file in tests/fixtures/{request}.yml so that a new version can be
  * generated to match against.
  */
 public function setUp()
 {
     VCR::configure()->setCassettePath('tests/fixtures')->setMode(getenv('VCR_MODE'));
     $this->setMatchers();
 }
 public function testExecuteQueryWithInvalidAPIKey()
 {
     \VCR\VCR::turnOn();
     \VCR\VCR::insertCassette('search_for_spotify_on_sv_blogs');
     $q = $this->client->query();
     $q->pattern = 'spotify page-size:10';
     $q->language = 'sv';
     $r = $q->execute();
     $this->assertGreaterThan(0, count($r->posts));
     \VCR\VCR::turnOff();
 }
Example #26
0
if (PHP_SAPI == 'cli' && isset($argv)) {
    $source = explode('/', $argv[0]);
    $source = end($source);
}
define('TERMINUS_SCRIPT', $source);
date_default_timezone_set('UTC');
include TERMINUS_ROOT . '/php/utils.php';
include TERMINUS_ROOT . '/php/FileCache.php';
include TERMINUS_ROOT . '/php/dispatcher.php';
include TERMINUS_ROOT . '/php/class-terminus.php';
include TERMINUS_ROOT . '/php/class-terminus-command.php';
\Terminus\Utils\load_dependencies();
//Set a custom exception handler
set_exception_handler('\\Terminus\\Utils\\handle_exception');
if (isset($_SERVER['TERMINUS_HOST']) && $_SERVER['TERMINUS_HOST'] != '') {
    define('TERMINUS_HOST', $_SERVER['TERMINUS_HOST']);
} else {
    define('TERMINUS_HOST', 'dashboard.getpantheon.com');
}
define('TERMINUS_PORT', '443');
if (isset($_SERVER['VCR_CASSETTE'])) {
    \VCR\VCR::configure()->enableRequestMatchers(array('method', 'url', 'body'));
    \VCR\VCR::configure()->setMode($_SERVER['VCR_MODE']);
    \VCR\VCR::turnOn();
    \VCR\VCR::insertCassette($_SERVER['VCR_CASSETTE']);
}
Terminus::get_runner()->run();
if (isset($_SERVER['VCR_CASSETTE'])) {
    \VCR\VCR::eject();
    \VCR\VCR::turnOff();
}
Example #27
0
<?php

/**
 * Bootstrap file for unit tests
 */
define('CLI_ROOT', dirname(__DIR__) . '/..');
define('TEST_DIR', dirname(__DIR__));
define('TERMINUS_CMD', 'php ' . CLI_ROOT . '/php/boot-fs.php');
putenv('CLI_TEST_MODE=1');
require_once CLI_ROOT . '/vendor/autoload.php';
require_once CLI_ROOT . '/php/boot-fs.php';
Terminus::set_config('nocache', true);
Terminus::set_config('debug', false);
use Terminus\Session;
// Set some dummy credentials
Session::setData(json_decode('{
  "user_uuid": "0ffec038-4410-43d0-a404-46997f672d7a",
  "session": "0ffec038-4410-43d0-a404-46997f672d7a%3A68486878-dd87-11e4-b243-bc764e1113b5%3AbQR2fyNMh5PQXN6F2Ewge",
  "session_expire_time": 1739299351,
  "email": "*****@*****.**"
}'));
\VCR\VCR::configure()->enableRequestMatchers(array('method', 'url', 'body'));
# Prevent API requests from being made in CI Environment
$ci_environment = getenv('CI');
if ($ci_environment) {
    \VCR\VCR::configure()->setMode('none');
}
Example #28
0
    context('with invalid parameters', function () {
        it('fails with an invalid API key', function () {
            $expected = function () {
                (new GoogleMaps('TEAZEE_BAD_KEY', new HttpAdapter(new Client()), new GuzzleMessageFactory()))->find($this->lat, $this->lng, 1455926050);
            };
            expect($expected)->toThrow(new RuntimeException('The provided API key is invalid.'));
        });
    });
    context('when no timestamp given', function () {
        before(function () {
            VCR::turnOff();
        });
        beforeEach(function () {
            $this->now = (new DateTimeImmutable(null, new DateTimeZone('UTC')))->getTimestamp();
            $this->time = $this->teazee->find($this->lat, $this->lng)->getTimestamp();
        });
        it('uses the default timestamp', function () {
            // Note: this _could_ fail if response times are especially bad, but it's google,
            // so we'll take our chances.
            expect($this->time)->toBeGreaterThan($this->now - 1);
            expect($this->time)->toBeLessThan($this->now + 3);
        });
        after(function () {
            VCR::turnOn();
            VCR::insertCassette('google_maps');
        });
    });
    after(function () {
        VCR::eject();
    });
});
<?php

namespace {
    require_once __DIR__ . "/../vendor/autoload.php";
    \VCR\VCR::configure()->enableLibraryHooks(['curl'])->setMode('once');
    \VCR\VCR::turnOn();
    function dummyObject($properties = [])
    {
        $object = new \StdClass();
        foreach ($properties as $key => $value) {
            $object->{$key} = $value;
        }
        return $object;
    }
}
namespace Test {
    class HTTPClient
    {
        public $email = null;
        public $api_key = null;
        function get($url, $params, $headers)
        {
        }
        function post($url, $params, $headers)
        {
        }
    }
    class Request
    {
        function get($endpoint, $params = [])
        {
Example #30
0
<?php

require_once "vendor/autoload.php";
function arrayify($object)
{
    return json_decode(json_encode($object), true);
}
function var_export_compact($object)
{
    $data = var_export($object, true);
    $data = str_replace("array (", "[", $data);
    $data = str_replace(")", "]", $data);
    $data = str_replace("\n", " ", $data);
    $data = str_replace("\t", "", $data);
    $data = preg_replace('/(\\s)+/', ' ', $data);
    $data = str_replace(", ]", "]", $data);
    $data = str_replace("[ ", "[", $data);
    return $data;
}
\Thru\TutumApi\Client::configure('matthewbaggett', 'decea003584f7df33be57f547f63f2cccd8e3188');
\VCR\VCR::configure()->setMode('new_episodes')->enableLibraryHooks(array('curl', 'stream_wrapper'));