diff options
author | Jordan Nornhold <nornholdj@gmail.com> | 2015-10-10 10:10:24 -0400 |
---|---|---|
committer | Jordan Nornhold <nornholdj@gmail.com> | 2015-10-10 10:10:24 -0400 |
commit | 7c39c1e35afb32845859289e8a0cd8eaceece5f2 (patch) | |
tree | a3b7e904158fe2145673a1d54676672096675a5f /test/unit | |
parent | c2e4758d8df8cf7e20451ea3196f2dc918e245e1 (diff) | |
parent | 63022bf7bceb6aa7116159fd347be769594fa8b4 (diff) | |
download | php-sparkpost-7c39c1e35afb32845859289e8a0cd8eaceece5f2.zip php-sparkpost-7c39c1e35afb32845859289e8a0cd8eaceece5f2.tar.gz php-sparkpost-7c39c1e35afb32845859289e8a0cd8eaceece5f2.tar.bz2 |
Merge pull request #22 from SparkPost/http-adapter-update
Http adapter update
Diffstat (limited to 'test/unit')
-rw-r--r-- | test/unit/APIResourceTest.php | 267 | ||||
-rw-r--r-- | test/unit/SendGridCompatibiility/EmailTest.php | 310 | ||||
-rw-r--r-- | test/unit/SparkPostTest.php | 124 | ||||
-rw-r--r-- | test/unit/TestUtils/ClassUtils.php | 56 | ||||
-rw-r--r-- | test/unit/TransmissionTest.php | 218 | ||||
-rw-r--r-- | test/unit/bootstrap.php | 4 |
6 files changed, 492 insertions, 487 deletions
diff --git a/test/unit/APIResourceTest.php b/test/unit/APIResourceTest.php index fc85fa3..8253b1e 100644 --- a/test/unit/APIResourceTest.php +++ b/test/unit/APIResourceTest.php @@ -1,144 +1,135 @@ <?php namespace SparkPost\Test; - use SparkPost\APIResource; -use SparkPost\SparkPost; -use Guzzle\Plugin\Mock\MockPlugin; -use Guzzle\Http\Message\Response; - +use SparkPost\Test\TestUtils\ClassUtils; +use \Mockery; class APIResourceTest extends \PHPUnit_Framework_TestCase { - - private $client = null; - - /** - * Allows access to private methods - * - * This is needed to mock the GuzzleHttp\Client responses - * - * @param string $name - * @return ReflectionMethod - */ - private static function getMethod($name) { - $class = new \ReflectionClass('\SparkPost\APIResource'); - $method = $class->getMethod($name); - $method->setAccessible(true); - return $method; - } - - /** - * (non-PHPdoc) - * @before - * @see PHPUnit_Framework_TestCase::setUp() - */ - public function setUp() { - SparkPost::setConfig(array('key'=>'blah')); - $this->client = self::getMethod('getHttpClient')->invoke(null); //so we can bootstrap api responses - APIResource::$endpoint = 'someValidEndpoint'; // when using APIResource directly an endpoint needs to be set. - } - - /** - * @desc Ensures that the configuration class is not instantiable. - */ - public function testConstructorCannotBeCalled() { - $class = new \ReflectionClass('\SparkPost\Transmission'); - $this->assertFalse($class->isInstantiable()); - } - - /** - * @desc tests happy path - */ - public function testFetchWithGoodResponse() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(200, array(), '{"results":[{"test":"This is a test"}, {"test":"two"}]}')); - $this->client->addSubscriber($mock); - $this->assertEquals(array("results"=>array(array('test'=>'This is a test'), array('test'=>'two'))), APIResource::fetchResource()); - } - - /** - * @desc tests happy path - */ - public function testDeleteWithGoodResponse() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(200, array(), '{"results":[{"test":"This is a test"}]}')); - $this->client->addSubscriber($mock); - - $this->assertEquals(array("results"=>array(array('test'=>'This is a test'))), APIResource::deleteResource('someId')); - } - - /** - * @desc tests 404 bad response - * @expectedException Exception - * @expectedExceptionMessage The specified resource does not exist - */ - public function testFetchWith404Response() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(404, array())); - $this->client->addSubscriber($mock); - APIResource::fetchResource('someId'); - } - - /** - * @desc tests unknown bad response - * @expectedException Exception - * @expectedExceptionMessage Received bad response from SomeValidEndpoint API: 400 - */ - public function testFetchWithOtherBadResponse() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(400, array())); - $this->client->addSubscriber($mock); - APIResource::fetchResource('someId'); - } - - /** - * @desc tests bad response - * @expectedException Exception - * @expectedExceptionMessageRegExp /Unable to contact SomeValidEndpoint API:.* / - */ - public function testFetchForCatchAllException() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(500)); - $this->client->addSubscriber($mock); - APIResource::fetchResource('someId'); - } - - /** - * @desc tests happy path - */ - public function testSuccessfulSend() { - $body = array("result"=>array("transmission_id"=>"11668787484950529"), "status"=>array("message"=> "ok","code"=> "1000")); - $mock = new MockPlugin(); - $mock->addResponse(new Response(200, array(), json_encode($body))); - $this->client->addSubscriber($mock); - - - $this->assertEquals($body, APIResource::sendRequest(array('text'=>'awesome email'))); - } - - /** - * @desc tests bad response - * @expectedException Exception - * @expectedExceptionMessage ["This is a fake error"] - */ - public function testSendFor400Exception() { - $body = array('errors'=>array('This is a fake error')); - $mock = new MockPlugin(); - $mock->addResponse(new Response(400, array(), json_encode($body))); - $this->client->addSubscriber($mock); - APIResource::sendRequest(array('text'=>'awesome email')); - } - - - /** - * @desc tests bad response - * @expectedException Exception - * @expectedExceptionMessageRegExp /Unable to contact SomeValidEndpoint API:.* / - */ - public function testSendForCatchAllException() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(500)); - $this->client->addSubscriber($mock); - APIResource::sendRequest(array('text'=>'awesome email')); - } - + + private static $utils; + private $adapterMock; + private $resource; + + private function getExceptionMock($statusCode) { + $exception = new \Ivory\HttpAdapter\HttpAdapterException(); + $response = Mockery::mock('Ivory\HttpAdapter\Message\ResponseInterface'); + $response->shouldReceive('getStatusCode')->andReturn($statusCode); + $exception->setResponse($response); + return $exception; + } + + /** + * (non-PHPdoc) + * @before + * @see PHPUnit_Framework_TestCase::setUp() + */ + public function setUp() { + $this->sparkPostMock = Mockery::mock('SparkPost\SparkPost', function($mock) { + $mock->shouldReceive('getHttpHeaders')->andReturn([]); + }); + $this->sparkPostMock->httpAdapter = Mockery::mock(); + $this->resource = new APIResource($this->sparkPostMock); + self::$utils = new ClassUtils($this->resource); + self::$utils->setProperty($this->resource, 'sparkpost', $this->sparkPostMock); + } + + public function tearDown() + { + Mockery::close(); + } + + public function testConstructorSetsUpSparkPostObject() { + $this->sparkPostMock->newProp = 'new value'; + $this->assertEquals($this->sparkPostMock, self::$utils->getProperty($this->resource, 'sparkpost')); + } + + public function testCreate() { + $testInput = ['test'=>'body']; + $testBody = ['results'=>['my'=>'test']]; + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with(Mockery::type('string'), 'POST', Mockery::type('array'), json_encode($testInput))-> + andReturn($responseMock); + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); + + + $this->assertEquals($testBody, $this->resource->create($testInput)); + } + + public function testUpdate() { + $testInput = ['test'=>'body']; + $testBody = ['results'=>['my'=>'test']]; + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*\/test/', 'PUT', Mockery::type('array'), json_encode($testInput))-> + andReturn($responseMock); + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); + + $this->assertEquals($testBody, $this->resource->update('test', $testInput)); + } + + public function testGet() { + $testBody = ['results'=>['my'=>'test']]; + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*\/test/', 'GET', Mockery::type('array'), null)-> + andReturn($responseMock); + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody)); + + $this->assertEquals($testBody, $this->resource->get('test')); + } + + public function testDelete() { + $responseMock = Mockery::mock(); + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*\/test/', 'DELETE', Mockery::type('array'), null)-> + andReturn($responseMock); + $responseMock->shouldReceive('getBody->getContents')->andReturn(''); + + $this->assertEquals(null, $this->resource->delete('test')); + } + + public function testAdapter404Exception() { + try { + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + andThrow($this->getExceptionMock(404)); + + $this->resource->get('test'); + } + catch(\Exception $e) { + $this->assertRegExp('/.*resource does not exist.*/', $e->getMessage()); + } + } + + public function testAdapter4XXException() { + try { + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + andThrow($this->getExceptionMock(400)); + + $this->resource->get('test'); + } + catch(\Exception $e) { + $this->assertRegExp('/Received bad response.*/', $e->getMessage()); + } + } + + public function testAdapter5XXException() { + try { + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + andThrow(new \Exception('Something went wrong.')); + + $this->resource->get('test'); + } + catch(\Exception $e) { + $this->assertRegExp('/Unable to contact.*API.*/', $e->getMessage()); + } + } + } diff --git a/test/unit/SendGridCompatibiility/EmailTest.php b/test/unit/SendGridCompatibiility/EmailTest.php index c60801c..2b86d7a 100644 --- a/test/unit/SendGridCompatibiility/EmailTest.php +++ b/test/unit/SendGridCompatibiility/EmailTest.php @@ -2,160 +2,160 @@ use SparkPost\SendGridCompatibility\Email; class SendGridCompatibilityEmailTest extends \PHPUnit_Framework_TestCase { - - private $email; - - public function setup() { - $this->email = new Email(); - } - - public function testConstruct() { - $email = new Email(); - - $this->assertInstanceOf('SparkPost\SendGridCompatibility\Email', $email); - $this->assertInternalType('array', $email->model); - } - - public function testAddTo() { - $fakeEmail = 'joe.schmoe@test.com'; - $this->email->addTo($fakeEmail); - - $this->assertEquals(array(array('address'=>array('email'=>$fakeEmail))), $this->email->model['recipients']); - } - - public function testAddToWithName() { - $fakeEmail = 'joe.schmoe@test.com'; - $fakeName = 'Joe Schmoe'; - $this->email->addTo($fakeEmail, $fakeName); - - $this->assertEquals(array(array('address'=>array('email'=>$fakeEmail, 'name'=>$fakeName))), $this->email->model['recipients']); - } - - public function testSetTos() { - $tos = array(); - array_push($tos, array('address'=>array('email'=>'joe.schmoe@test.com', 'name'=>'Joe Schmoe'))); - array_push($tos, array('address'=>array('email'=>'jill.schmoe@test.com', 'name'=>'Jill Schmoe'))); - $this->email->setTos($tos); - - $this->assertEquals($tos, $this->email->model['recipients']); - } - - public function testSetFrom() { - $this->email->setFrom('test@email.com'); - - $this->assertEquals(array('email'=>'test@email.com'), $this->email->model['from']); - } - - - public function testSetFromName() { - $this->email->setFrom('test@email.com'); - $this->email->setFromName('Test Bot'); - - $this->assertEquals(array('email'=>'test@email.com', 'name'=>'Test Bot'), $this->email->model['from']); - } - - /** - * @desc Tests that setting the fromName prior to setting the From field throws an exception - * @expectedException Exception - * @expectedExceptionMessage Must set "From" prior to setting "From Name". - */ - public function testSetFromNameWithoutAddress() { - $this->email->setFromName('Test Bot'); - } - - public function testSetReplyto() { - $this->email->setReplyTo('test@email.com'); - - $this->assertEquals('test@email.com', $this->email->model['replyTo']); - } - /** - * @expectedException Exception - * @expectedExceptionMessage Adding bcc recipients is not yet supported, try adding them as a "to" address - */ - public function testAddBcc() { - $this->email->addBcc('test@email.com'); - } - - public function testSetSubject() { - $this->email->setSubject('Awesome Subject'); - - $this->assertEquals('Awesome Subject', $this->email->model['subject']); - } - - public function testSetText() { - $value = 'This is some plain/text'; - $this->email->setText($value); - - $this->assertEquals($value, $this->email->model['text']); - } - - public function testSetHtml() { - $value = '<html><body><p>This is some html</p></body></html>'; - $this->email->setHtml($value); - - $this->assertEquals($value, $this->email->model['html']); - } - - /** - * @desc test that adding a category throws an exception since we don't support tags at transmission level yet - * @expectedException Exception - * @expectedExceptionMessage Adding categories is not yet supported - */ - public function testAddCategory() { - $this->email->addCategory(''); - } - - /** - * @desc Tests that setting an attachment throws a meaningful exception - * @expectedException Exception - * @expectedExceptionMessage Adding attachments is not yet supported - */ - public function testAddAttachment() { - $this->email->addAttachment('blah'); - } - - public function testAddSubstitution() { - $this->email->addSubstitution('item', 'baseball bat'); - - $this->assertEquals(array('item'=>'baseball bat'), $this->email->model['substitutionData']); - } - - public function testAddSection() { - $this->email->addSection('item', 'baseball bat'); - - $this->assertEquals(array('item'=>'baseball bat'), $this->email->model['substitutionData']); - } - - /** - * @desc Tests that setting an attachment throws a meaningful exception - * @expectedException Exception - * @expectedExceptionMessage Adding Unique Arguments is not yet supported - */ - public function testAddUniqueArguement() { - $this->email->addUniqueArg('blah', 'someblah'); - } - - - /** - * @desc Tests that setting an unique argument throws a meaningful exception - * @expectedException Exception - * @expectedExceptionMessage Setting Unique Arguments is not yet supported - */ - public function testSetUniqueArgs() { - $this->email->setUniqueArgs(array('blah', 'andBlah')); - } - - - public function testAddHeader() { - $value = 'My Header'; - $this->email->addHeader('X-header', $value); - - $this->assertEquals(array('X-header'=>$value), $this->email->model['customHeaders']); - } - - public function testToSparkPostTransmission() { - $this->assertInternalType('array', $this->email->toSparkPostTransmission()); - } + + private $email; + + public function setup() { + $this->email = new Email(); + } + + public function testConstruct() { + $email = new Email(); + + $this->assertInstanceOf('SparkPost\SendGridCompatibility\Email', $email); + $this->assertInternalType('array', $email->model); + } + + public function testAddTo() { + $fakeEmail = 'joe.schmoe@test.com'; + $this->email->addTo($fakeEmail); + + $this->assertEquals(array(array('address'=>array('email'=>$fakeEmail))), $this->email->model['recipients']); + } + + public function testAddToWithName() { + $fakeEmail = 'joe.schmoe@test.com'; + $fakeName = 'Joe Schmoe'; + $this->email->addTo($fakeEmail, $fakeName); + + $this->assertEquals(array(array('address'=>array('email'=>$fakeEmail, 'name'=>$fakeName))), $this->email->model['recipients']); + } + + public function testSetTos() { + $tos = array(); + array_push($tos, array('address'=>array('email'=>'joe.schmoe@test.com', 'name'=>'Joe Schmoe'))); + array_push($tos, array('address'=>array('email'=>'jill.schmoe@test.com', 'name'=>'Jill Schmoe'))); + $this->email->setTos($tos); + + $this->assertEquals($tos, $this->email->model['recipients']); + } + + public function testSetFrom() { + $this->email->setFrom('test@email.com'); + + $this->assertEquals(array('email'=>'test@email.com'), $this->email->model['from']); + } + + + public function testSetFromName() { + $this->email->setFrom('test@email.com'); + $this->email->setFromName('Test Bot'); + + $this->assertEquals(array('email'=>'test@email.com', 'name'=>'Test Bot'), $this->email->model['from']); + } + + /** + * @desc Tests that setting the fromName prior to setting the From field throws an exception + * @expectedException Exception + * @expectedExceptionMessage Must set 'From' prior to setting 'From Name'. + */ + public function testSetFromNameWithoutAddress() { + $this->email->setFromName('Test Bot'); + } + + public function testSetReplyto() { + $this->email->setReplyTo('test@email.com'); + + $this->assertEquals('test@email.com', $this->email->model['replyTo']); + } + /** + * @expectedException Exception + * @expectedExceptionMessage Adding bcc recipients is not yet supported, try adding them as a 'to' address + */ + public function testAddBcc() { + $this->email->addBcc('test@email.com'); + } + + public function testSetSubject() { + $this->email->setSubject('Awesome Subject'); + + $this->assertEquals('Awesome Subject', $this->email->model['subject']); + } + + public function testSetText() { + $value = 'This is some plain/text'; + $this->email->setText($value); + + $this->assertEquals($value, $this->email->model['text']); + } + + public function testSetHtml() { + $value = '<html><body><p>This is some html</p></body></html>'; + $this->email->setHtml($value); + + $this->assertEquals($value, $this->email->model['html']); + } + + /** + * @desc test that adding a category throws an exception since we don't support tags at transmission level yet + * @expectedException Exception + * @expectedExceptionMessage Adding categories is not yet supported + */ + public function testAddCategory() { + $this->email->addCategory(''); + } + + /** + * @desc Tests that setting an attachment throws a meaningful exception + * @expectedException Exception + * @expectedExceptionMessage Adding attachments is not yet supported + */ + public function testAddAttachment() { + $this->email->addAttachment('blah'); + } + + public function testAddSubstitution() { + $this->email->addSubstitution('item', 'baseball bat'); + + $this->assertEquals(array('item'=>'baseball bat'), $this->email->model['substitutionData']); + } + + public function testAddSection() { + $this->email->addSection('item', 'baseball bat'); + + $this->assertEquals(array('item'=>'baseball bat'), $this->email->model['substitutionData']); + } + + /** + * @desc Tests that setting an attachment throws a meaningful exception + * @expectedException Exception + * @expectedExceptionMessage Adding Unique Arguments is not yet supported + */ + public function testAddUniqueArguement() { + $this->email->addUniqueArg('blah', 'someblah'); + } + + + /** + * @desc Tests that setting an unique argument throws a meaningful exception + * @expectedException Exception + * @expectedExceptionMessage Setting Unique Arguments is not yet supported + */ + public function testSetUniqueArgs() { + $this->email->setUniqueArgs(array('blah', 'andBlah')); + } + + + public function testAddHeader() { + $value = 'My Header'; + $this->email->addHeader('X-header', $value); + + $this->assertEquals(array('X-header'=>$value), $this->email->model['customHeaders']); + } + + public function testToSparkPostTransmission() { + $this->assertInternalType('array', $this->email->toSparkPostTransmission()); + } } -?>
\ No newline at end of file +?> diff --git a/test/unit/SparkPostTest.php b/test/unit/SparkPostTest.php index f40461d..101784a 100644 --- a/test/unit/SparkPostTest.php +++ b/test/unit/SparkPostTest.php @@ -2,60 +2,76 @@ namespace SparkPost\Test; use SparkPost\SparkPost; +use Ivory\HttpAdapter\CurlHttpAdapter; +use SparkPost\Test\TestUtils\ClassUtils; +use \Mockery; class SparkPostTest extends \PHPUnit_Framework_TestCase { - - /** - * @desc Ensures that the configuration class is not instantiable. - */ - public function testConstructorCannotBeCalled() { - $class = new \ReflectionClass('\SparkPost\SparkPost'); - $this->assertFalse($class->isInstantiable()); - } - - /** - * @desc Tests that an exception is thrown when a library tries to recieve the config and it has not yet been set. - * Since its a singleton this test must come before any setConfig tests. - * @expectedException Exception - * @expectedExceptionMessage No configuration has been provided - */ - public function testGetConfigEmptyException() { - SparkPost::unsetConfig(); - SparkPost::getConfig(); - } - - /** - * @desc Tests that the api key is set when setting the config - * @expectedException Exception - * @expectedExceptionMessage You must provide an API key - */ - public function testSetConfigAPIKeyNotSetException() { - SparkPost::setConfig(array('something'=>'other than an API Key')); - } - - /** - * @desc Tests that the api key is set when setting the config and that its not empty - * @expectedException Exception - * @expectedExceptionMessage You must provide an API key - */ - public function testSetConfigAPIKeyEmptyException() { - SparkPost::setConfig(array('key'=>'')); - } - - /** - * @desc Tests overridable values are set while invalid values are ignored - */ - public function testSetConfigMultipleValuesAndGetConfig() { - SparkPost::setConfig(array('key'=>'lala', 'version'=>'v8', 'port'=>1024, 'someOtherValue'=>'fakeValue')); - - $testConfig = SparkPost::getConfig(); - $this->assertEquals('lala', $testConfig['key']); - $this->assertEquals('v8', $testConfig['version']); - $this->assertEquals(1024, $testConfig['port']); - $this->assertNotContains('someOtherValue', array_keys($testConfig)); - $this->assertEquals('https', $testConfig['protocol']); - $this->assertEquals('api.sparkpost.com', $testConfig['host']); - $this->assertEquals(true, $testConfig['strictSSL']); - } + + private static $utils; + private $adapterMock; + private $resource; + + /** + * (non-PHPdoc) + * @before + * @see PHPUnit_Framework_TestCase::setUp() + */ + public function setUp() { + //setup mock for the adapter + $this->adapterMock = Mockery::mock('Ivory\HttpAdapter\HttpAdapterInterface', function($mock) { + $mock->shouldReceive('setConfiguration'); + $mock->shouldReceive('getConfiguration->getUserAgent')->andReturn('php-sparkpost/0.2.0'); + }); + + $this->resource = new SparkPost($this->adapterMock, ['key'=>'a key']); + self::$utils = new ClassUtils($this->resource); + self::$utils->setProperty($this->resource, 'httpAdapter', $this->adapterMock); + } + + public function tearDown(){ + Mockery::close(); + } + + /** + * @desc Ensures that the configuration class is not instantiable. + */ + public function testConstructorSetsUpTransmissions() { + $sparky = new SparkPost(new CurlHttpAdapter(), ['key'=>'a key']); + $this->assertEquals('SparkPost\Transmission', get_class($sparky->transmission)); + $adapter = self::$utils->getProperty($this->resource, 'httpAdapter'); + $this->assertRegExp('/php-sparkpost.*/', $adapter->getConfiguration()->getUserAgent()); + } + + /** + * @expectedException Exception + * @expectedExceptionMessageRegExp /valid Ivory\\HttpAdapter/ + */ + public function testSetBadHTTPAdapter() { + $this->resource->setHttpAdapter(new \stdClass()); + } + + /** + * @expectedException Exception + * @expectedExceptionMessageRegExp /API key/ + */ + public function testSetBadConfig() { + $this->resource->setConfig(['not'=>'a key']); + } + + + public function testGetHeaders() { + $results = $this->resource->getHttpHeaders(); + $this->assertEquals('a key', $results['Authorization']); + $this->assertEquals('application/json', $results['Content-Type']); + } + + public function testSetUnwrapped() { + $results = $this->resource->setupUnwrapped('ASweetEndpoint'); + $this->assertEquals($this->resource->ASweetEndpoint, $results); + $this->assertInstanceOf('SparkPost\APIResource', $results); + $this->assertEquals('ASweetEndpoint', $results->endpoint); + } + } -?>
\ No newline at end of file +?> diff --git a/test/unit/TestUtils/ClassUtils.php b/test/unit/TestUtils/ClassUtils.php new file mode 100644 index 0000000..26d264c --- /dev/null +++ b/test/unit/TestUtils/ClassUtils.php @@ -0,0 +1,56 @@ +<?php +namespace SparkPost\Test\TestUtils; + + +class ClassUtils { + + private $class; + + public function __construct($fqClassName) { + $this->class = new \ReflectionClass($fqClassName); + } + + /** + * Allows access to private methods + * + * This is needed to mock the GuzzleHttp\Client responses + * + * @param string $name + * @return ReflectionMethod + */ + public function getMethod($method) { + $method = $this->class->getMethod($name); + $method->setAccessible(true); + return $method; + } + + /** + * Allows access to private properties in the Transmission class + * + * This is needed to mock the GuzzleHttp\Client responses + * + * @param string $name + * @param {*} + * @return ReflectionMethod + */ + public function getProperty($instance, $property) { + $prop = $this->class->getProperty($property); + $prop->setAccessible(true); + return $prop->getValue($instance); + } + /** + * Allows access to private properties in the Transmission class + * + * This is needed to mock the GuzzleHttp\Client responses + * + * @param string $name + * @param {*} + * @return ReflectionMethod + */ + public function setProperty($instance, $property, $value) { + $prop = $this->class->getProperty($property); + $prop->setAccessible(true); + $prop->setValue($instance, $value); + } +} +?> diff --git a/test/unit/TransmissionTest.php b/test/unit/TransmissionTest.php index ca30b4a..d262ee0 100644 --- a/test/unit/TransmissionTest.php +++ b/test/unit/TransmissionTest.php @@ -1,144 +1,86 @@ <?php namespace SparkPost\Test; - use SparkPost\Transmission; -use SparkPost\SparkPost; -use Guzzle\Plugin\Mock\MockPlugin; -use Guzzle\Http\Message\Response; - +use SparkPost\Test\TestUtils\ClassUtils; +use \Mockery; class TransmissionTest extends \PHPUnit_Framework_TestCase { - - private $client = null; - - /** - * Allows access to private methods in the Transmission class - * - * This is needed to mock the GuzzleHttp\Client responses - * - * @param string $name - * @return ReflectionMethod - */ - private static function getMethod($name) { - $class = new \ReflectionClass('\SparkPost\Transmission'); - $method = $class->getMethod($name); - $method->setAccessible(true); - return $method; - } - - /** - * (non-PHPdoc) - * @before - * @see PHPUnit_Framework_TestCase::setUp() - */ - public function setUp() { - SparkPost::setConfig(array('key'=>'blah')); - $this->client = self::getMethod('getHttpClient')->invoke(null); //so we can bootstrap api responses - } - - /** - * @desc Ensures that the configuration class is not instantiable. - */ - public function testConstructorCannotBeCalled() { - $class = new \ReflectionClass('\SparkPost\Transmission'); - $this->assertFalse($class->isInstantiable()); - } - - /** - * @desc tests happy path - */ - public function testAllWithGoodResponse() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(200, array(), '{"results":[{"test":"This is a test"}, {"test":"two"}]}')); - $this->client->addSubscriber($mock); - $this->assertEquals(array("results"=>array(array('test'=>'This is a test'), array('test'=>'two'))), Transmission::all()); - } - - /** - * @desc tests happy path - */ - public function testFindWithGoodResponse() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(200, array(), '{"results":[{"test":"This is a test"}]}')); - $this->client->addSubscriber($mock); - - $this->assertEquals(array("results"=>array(array('test'=>'This is a test'))), Transmission::find('someId')); - } - - /** - * @desc tests 404 bad response - * @expectedException Exception - * @expectedExceptionMessage The specified resource does not exist - */ - public function testFindWith404Response() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(404, array())); - $this->client->addSubscriber($mock); - Transmission::find('someId'); - } - - /** - * @desc tests unknown bad response - * @expectedException Exception - * @expectedExceptionMessage Received bad response from Transmissions API: 400 - */ - public function testFindWithOtherBadResponse() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(400, array())); - $this->client->addSubscriber($mock); - Transmission::find('someId'); - } - - /** - * @desc tests bad response - * @expectedException Exception - * @expectedExceptionMessageRegExp /Unable to contact Transmissions API:.* / - */ - public function testFindForCatchAllException() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(500)); - $this->client->addSubscriber($mock); - Transmission::find('someId'); - } - - /** - * @desc tests happy path - */ - public function testSuccessfulSend() { - $body = array("result"=>array("transmission_id"=>"11668787484950529"), "status"=>array("message"=> "ok","code"=> "1000")); - $mock = new MockPlugin(); - $mock->addResponse(new Response(200, array(), json_encode($body))); - $this->client->addSubscriber($mock); - - - $this->assertEquals($body, Transmission::send(array('text'=>'awesome email'))); - } - - /** - * @desc tests bad response - * @expectedException Exception - * @expectedExceptionMessage ["This is a fake error"] - */ - public function testSendFor400Exception() { - $body = array('errors'=>array('This is a fake error')); - $mock = new MockPlugin(); - $mock->addResponse(new Response(400, array(), json_encode($body))); - $this->client->addSubscriber($mock); - Transmission::send(array('text'=>'awesome email')); - } - - - /** - * @desc tests bad response - * @expectedException Exception - * @expectedExceptionMessageRegExp /Unable to contact Transmissions API:.* / - */ - public function testSendForCatchAllException() { - $mock = new MockPlugin(); - $mock->addResponse(new Response(500)); - $this->client->addSubscriber($mock); - Transmission::send(array('text'=>'awesome email')); - } - + + private static $utils; + private $sparkPostMock; + private $resource; + + /** + * (non-PHPdoc) + * @before + * @see PHPUnit_Framework_TestCase::setUp() + */ + public function setUp() { + $this->sparkPostMock = Mockery::mock('SparkPost\SparkPost', function($mock) { + $mock->shouldReceive('getHttpHeaders')->andReturn([]); + }); + $this->sparkPostMock->httpAdapter = Mockery::mock(); + $this->resource = new Transmission($this->sparkPostMock); + self::$utils = new ClassUtils($this->resource); + } + + public function tearDown(){ + Mockery::close(); + } + + public function testSend() { + $responseMock = Mockery::mock(); + $body = ['text'=>'awesomesauce', 'content'=>['subject'=>'awesomeness']]; + $responseBody = ['results'=>'yay']; + + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*\/transmissions/', 'POST', Mockery::type('array'), Mockery::type('string'))-> + andReturn($responseMock); + + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody)); + + $this->assertEquals($responseBody, $this->resource->send($body)); + } + + public function testAllWithFilter() { + $responseMock = Mockery::mock(); + $responseBody = ['results'=>'yay']; + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*transmissions.*?campaign_id=campaign&template_id=template/', 'GET', Mockery::type('array'), null)-> + andReturn($responseMock); + + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody)); + + $this->assertEquals($responseBody, $this->resource->all('campaign', 'template')); + } + + public function testAllWithOutFilter() { + $responseMock = Mockery::mock(); + $responseBody = ['results'=>'yay']; + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*\/transmissions/', 'GET', Mockery::type('array'), null)-> + andReturn($responseMock); + + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody)); + + $this->assertEquals($responseBody, $this->resource->all()); + } + + public function testFind() { + $responseMock = Mockery::mock(); + $responseBody = ['results'=>'yay']; + $this->sparkPostMock->httpAdapter->shouldReceive('send')-> + once()-> + with('/.*\/transmissions.*\/test/', 'GET', Mockery::type('array'), null)-> + andReturn($responseMock); + + $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody)); + + $this->assertEquals($responseBody, $this->resource->find('test')); + } + } -?>
\ No newline at end of file +?> diff --git a/test/unit/bootstrap.php b/test/unit/bootstrap.php index 7e73606..0b851be 100644 --- a/test/unit/bootstrap.php +++ b/test/unit/bootstrap.php @@ -1,3 +1,3 @@ <?php - require_once dirname(__FILE__).'/../../vendor/autoload.php'; -?>
\ No newline at end of file + require_once dirname(__FILE__).'/../../vendor/autoload.php'; +?> |