summaryrefslogtreecommitdiffstats
path: root/test/unit
diff options
context:
space:
mode:
authorAvi Goldman <avrahamymgoldman@gmail.com>2016-06-24 15:51:34 -0400
committerAvi Goldman <avrahamymgoldman@gmail.com>2016-06-24 15:51:34 -0400
commit55d1bdc1ac65d63df6490f588f3d6e9eb506da79 (patch)
treeb21a8ac66224692fe10b2a3cced0374d18ee7de1 /test/unit
parent1b61a81471fc46cde5a515381e9642e0c884481c (diff)
parent12f363bb1f99891fb4b105009d20c596c35c87ae (diff)
downloadphp-sparkpost-55d1bdc1ac65d63df6490f588f3d6e9eb506da79.zip
php-sparkpost-55d1bdc1ac65d63df6490f588f3d6e9eb506da79.tar.gz
php-sparkpost-55d1bdc1ac65d63df6490f588f3d6e9eb506da79.tar.bz2
merged in 2x
Diffstat (limited to 'test/unit')
-rw-r--r--test/unit/APIResourceExceptionTest.php43
-rw-r--r--test/unit/APIResourceTest.php196
-rw-r--r--test/unit/MessageEventTest.php74
-rw-r--r--test/unit/SendGridCompatibiility/EmailTest.php178
-rw-r--r--test/unit/SparkPostResponseTest.php133
-rw-r--r--test/unit/SparkPostTest.php257
-rw-r--r--test/unit/TransmissionTest.php153
7 files changed, 465 insertions, 569 deletions
diff --git a/test/unit/APIResourceExceptionTest.php b/test/unit/APIResourceExceptionTest.php
deleted file mode 100644
index 8ae80de..0000000
--- a/test/unit/APIResourceExceptionTest.php
+++ /dev/null
@@ -1,43 +0,0 @@
-<?php
-
-namespace SparkPost\Test;
-
-use SparkPost\APIResponseException;
-
-class APIResourceExceptionTest extends \PHPUnit_Framework_TestCase
-{
- private $message;
- private $code;
- private $description;
- private $exception;
-
- /**
- * (non-PHPdoc).
- *
- * @before
- *
- * @see PHPUnit_Framework_TestCase::setUp()
- */
- public function setUp()
- {
- $this->message = 'Test message';
- $this->code = 400;
- $this->description = 'Test description';
- $this->exception = new APIResponseException(null, 0, $this->message, $this->code, $this->description);
- }
-
- public function testAPIMessage()
- {
- $this->assertEquals($this->message, $this->exception->getAPIMessage());
- }
-
- public function testAPICode()
- {
- $this->assertEquals($this->code, $this->exception->getAPICode());
- }
-
- public function testAPIDescription()
- {
- $this->assertEquals($this->description, $this->exception->getAPIDescription());
- }
-}
diff --git a/test/unit/APIResourceTest.php b/test/unit/APIResourceTest.php
deleted file mode 100644
index 67c37ab..0000000
--- a/test/unit/APIResourceTest.php
+++ /dev/null
@@ -1,196 +0,0 @@
-<?php
-
-namespace SparkPost\Test;
-
-use SparkPost\APIResource;
-use SparkPost\Test\TestUtils\ClassUtils;
-use Mockery;
-
-class APIResourceTest extends \PHPUnit_Framework_TestCase
-{
- 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('getStatusCode')->andReturn(200);
- $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('getStatusCode')->andReturn(200);
- $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('getStatusCode')->andReturn(200);
- $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody));
-
- $this->assertEquals($testBody, $this->resource->get('test'));
- }
-
- public function testGetCommaSeparated()
- {
- $testBody = ['results' => ['my' => 'test']];
- $requestArray = [
- 'param1' => 'param1val',
- 'param2' => ['param2val1', 'param2val2'],
- ];
- $expectedGetParams = 'param1=param1val&param2='.urlencode('param2val1,param2val2');
-
- $responseMock = Mockery::mock();
- $this->sparkPostMock->httpAdapter->shouldReceive('send')->
- once()->
- with(matchesPattern("/.*\/test\?{$expectedGetParams}/"), 'GET', Mockery::type('array'), null)->
- andReturn($responseMock);
- $responseMock->shouldReceive('getStatusCode')->andReturn(200);
- $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody));
-
- $this->assertEquals($testBody, $this->resource->get('test', $requestArray));
- }
-
- public function testDelete()
- {
- $responseMock = Mockery::mock();
- $this->sparkPostMock->httpAdapter->shouldReceive('send')->
- once()->
- with('/.*\/test/', 'DELETE', Mockery::type('array'), null)->
- andReturn($responseMock);
- $responseMock->shouldReceive('getStatusCode')->andReturn(200);
- $responseMock->shouldReceive('getBody->getContents')->andReturn('');
-
- $this->assertEquals(null, $this->resource->delete('test'));
- }
-
- public function testAdapter404Exception()
- {
- try {
- $responseMock = Mockery::mock();
- $this->sparkPostMock->httpAdapter->shouldReceive('send')->
- once()->
- andReturn($responseMock);
- $responseMock->shouldReceive('getStatusCode')->andReturn(404);
-
- $this->resource->get('test');
- } catch (\Exception $e) {
- $this->assertRegExp('/.*resource does not exist.*/', $e->getMessage());
- }
- }
-
- public function testAdapter403Exception()
- {
- $testBody = ['errors' => [
- [
- 'message' => 'Forbidden.',
- ],
- ]];
- try {
- $responseMock = Mockery::mock();
- $this->sparkPostMock->httpAdapter->shouldReceive('send')->
- once()->
- andReturn($responseMock);
- $responseMock->shouldReceive('getStatusCode')->andReturn(403);
- $responseMock->shouldReceive('getBody')->andReturn(json_encode($testBody));
-
- $this->resource->get('test');
- } catch (\Exception $e) {
- $this->assertRegExp('/Request forbidden/', $e->getMessage());
- }
- }
-
- public function testAdapter4XXException()
- {
- try {
- $testBody = ['errors' => ['my' => 'test']];
- $responseMock = Mockery::mock();
- $this->sparkPostMock->httpAdapter->shouldReceive('send')->
- once()->
- andReturn($responseMock);
- $responseMock->shouldReceive('getStatusCode')->andReturn(400);
- $responseMock->shouldReceive('getBody')->andReturn(json_encode($testBody));
-
- $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/MessageEventTest.php b/test/unit/MessageEventTest.php
deleted file mode 100644
index 3d92412..0000000
--- a/test/unit/MessageEventTest.php
+++ /dev/null
@@ -1,74 +0,0 @@
-<?php
-
-namespace SparkPost;
-
-use Mockery;
-
-class MessageEventTest extends \PHPUnit_Framework_TestCase
-{
- private $sparkPostMock;
- private $sut;
-
- /**
- * (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->sut = new MessageEvents($this->sparkPostMock);
- }
-
- public function testDateTimeConversion()
- {
- $testBody = ['results' => ['my' => 'test']];
- $testFrom = new \DateTime('1978-08-27 04:05:02');
- $testFromStr = urlencode('1978-08-27T04:05');
- $testTo = new \DateTime('2016-04-04 19:00');
- $testToStr = urlencode('2016-04-04T19:00');
-
- $responseMock = Mockery::mock();
- $this->sparkPostMock->httpAdapter->shouldReceive('send')->
- once()->
- with("/message-events/?from={$testFromStr}&to={$testToStr}", 'GET', Mockery::type('array'), null)->
- andReturn($responseMock);
- $responseMock->shouldReceive('getStatusCode')->andReturn(200);
- $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody));
-
- $this->assertEquals($testBody, $this->sut->search(['from' => $testFrom, 'to' => $testTo]));
- }
-
- public function testDocumentation()
- {
- $testBody = ['results' => ['my' => 'test']];
- $responseMock = Mockery::mock();
- $this->sparkPostMock->httpAdapter->shouldReceive('send')->
- once()->
- with('/message-events/events/documentation', 'GET', Mockery::type('array'), null)->
- andReturn($responseMock);
- $responseMock->shouldReceive('getStatusCode')->andReturn(200);
- $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody));
-
- $this->assertEquals($testBody, $this->sut->documentation());
- }
-
- public function testSamples()
- {
- $testBody = ['results' => ['my' => 'test']];
- $responseMock = Mockery::mock();
- $this->sparkPostMock->httpAdapter->shouldReceive('send')->
- once()->
- with('/message-events/events/samples?events='.urlencode('delivery,bounce'), 'GET', Mockery::type('array'), null)->
- andReturn($responseMock);
- $responseMock->shouldReceive('getStatusCode')->andReturn(200);
- $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($testBody));
-
- $this->assertEquals($testBody, $this->sut->samples(['delivery', 'bounce']));
- }
-}
diff --git a/test/unit/SendGridCompatibiility/EmailTest.php b/test/unit/SendGridCompatibiility/EmailTest.php
deleted file mode 100644
index 2846e9e..0000000
--- a/test/unit/SendGridCompatibiility/EmailTest.php
+++ /dev/null
@@ -1,178 +0,0 @@
-<?php
-
-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());
- }
-}
diff --git a/test/unit/SparkPostResponseTest.php b/test/unit/SparkPostResponseTest.php
new file mode 100644
index 0000000..efdec1a
--- /dev/null
+++ b/test/unit/SparkPostResponseTest.php
@@ -0,0 +1,133 @@
+<?php
+
+namespace SparkPost\Test;
+
+use SparkPost\SparkPostResponse;
+use Mockery;
+
+class SparkPostResponseTest extends \PHPUnit_Framework_TestCase
+{
+ /**
+ * (non-PHPdoc).
+ *
+ * @before
+ *
+ * @see PHPUnit_Framework_TestCase::setUp()
+ */
+ public function setUp()
+ {
+ $this->returnValue = 'some_value_to_return';
+ $this->responseMock = Mockery::mock('Psr\Http\Message\ResponseInterface');
+ }
+
+ public function testGetProtocolVersion()
+ {
+ $this->responseMock->shouldReceive('getProtocolVersion')->andReturn($this->returnValue);
+ $sparkpostResponse = new SparkPostResponse($this->responseMock);
+ $this->assertEquals($this->responseMock->getProtocolVersion(), $sparkpostResponse->getProtocolVersion());
+ }
+
+ public function testWithProtocolVersion()
+ {
+ $param = 'protocol version';
+
+ $this->responseMock->shouldReceive('withProtocolVersion')->andReturn($this->returnValue);
+ $sparkpostResponse = new SparkPostResponse($this->responseMock);
+ $this->assertEquals($this->responseMock->withProtocolVersion($param), $sparkpostResponse->withProtocolVersion($param));
+ }
+
+ public function testGetHeaders()
+ {
+ $this->responseMock->shouldReceive('getHeaders')->andReturn($this->returnValue);
+ $sparkpostResponse = new SparkPostResponse($this->responseMock);
+ $this->assertEquals($this->responseMock->getHeaders(), $sparkpostResponse->getHeaders());
+ }
+
+ public function testHasHeader()
+ {
+ $param = 'header';
+
+ $this->responseMock->shouldReceive('hasHeader')->andReturn($this->returnValue);
+ $sparkpostResponse = new SparkPostResponse($this->responseMock);
+ $this->assertEquals($this->responseMock->hasHeader($param), $sparkpostResponse->hasHeader($param));
+ }
+
+ public function testGetHeader()
+ {
+ $param = 'header';
+
+ $this->responseMock->shouldReceive('getHeader')->andReturn($this->returnValue);
+ $sparkpostResponse = new SparkPostResponse($this->responseMock);
+ $this->assertEquals($this->responseMock->getHeader($param), $sparkpostResponse->getHeader($param));
+ }
+
+ public function testGetHeaderLine()
+ {
+ $param = 'header';
+
+ $this->responseMock->shouldReceive('getHeaderLine')->andReturn($this->returnValue);
+ $sparkpostResponse = new SparkPostResponse($this->responseMock);
+ $this->assertEquals($this->responseMock->getHeaderLine($param), $sparkpostResponse->getHeaderLine($param));
+ }
+
+ public function testWithHeader()
+ {
+ $param = 'header';
+ $param2 = 'value';
+
+ $this->responseMock->shouldReceive('withHeader')->andReturn($this->returnValue);
+ $sparkpostResponse = new SparkPostResponse($this->responseMock);
+ $this->assertEquals($this->responseMock->withHeader($param, $param2), $sparkpostResponse->withHeader($param, $param2));
+ }
+
+ public function testWithAddedHeader()
+ {
+ $param = 'header';
+ $param2 = 'value';
+
+ $this->responseMock->shouldReceive('withAddedHeader')->andReturn($this->returnValue);
+ $sparkpostResponse = new SparkPostResponse($this->responseMock);
+ $this->assertEquals($this->responseMock->withAddedHeader($param, $param2), $sparkpostResponse->withAddedHeader($param, $param2));
+ }
+
+ public function testWithoutHeader()
+ {
+ $param = 'header';
+
+ $this->responseMock->shouldReceive('withoutHeader')->andReturn($this->returnValue);
+ $sparkpostResponse = new SparkPostResponse($this->responseMock);
+ $this->assertEquals($this->responseMock->withoutHeader($param), $sparkpostResponse->withoutHeader($param));
+ }
+
+ public function testWithBody()
+ {
+ $param = Mockery::mock('Psr\Http\Message\StreamInterface');
+
+ $this->responseMock->shouldReceive('withBody')->andReturn($this->returnValue);
+ $sparkpostResponse = new SparkPostResponse($this->responseMock);
+ $this->assertEquals($this->responseMock->withBody($param), $sparkpostResponse->withBody($param));
+ }
+
+ public function testGetStatusCode()
+ {
+ $this->responseMock->shouldReceive('getStatusCode')->andReturn($this->returnValue);
+ $sparkpostResponse = new SparkPostResponse($this->responseMock);
+ $this->assertEquals($this->responseMock->getStatusCode(), $sparkpostResponse->getStatusCode());
+ }
+
+ public function testWithStatus()
+ {
+ $param = 'status';
+
+ $this->responseMock->shouldReceive('withStatus')->andReturn($this->returnValue);
+ $sparkpostResponse = new SparkPostResponse($this->responseMock);
+ $this->assertEquals($this->responseMock->withStatus($param), $sparkpostResponse->withStatus($param));
+ }
+
+ public function testGetReasonPhrase()
+ {
+ $this->responseMock->shouldReceive('getReasonPhrase')->andReturn($this->returnValue);
+ $sparkpostResponse = new SparkPostResponse($this->responseMock);
+ $this->assertEquals($this->responseMock->getReasonPhrase(), $sparkpostResponse->getReasonPhrase());
+ }
+}
diff --git a/test/unit/SparkPostTest.php b/test/unit/SparkPostTest.php
index 26563c3..f1c8a56 100644
--- a/test/unit/SparkPostTest.php
+++ b/test/unit/SparkPostTest.php
@@ -2,18 +2,37 @@
namespace SparkPost\Test;
-use Ivory\HttpAdapter\CurlHttpAdapter;
-use Mockery;
use SparkPost\SparkPost;
+use SparkPost\SparkPostPromise;
+use GuzzleHttp\Promise\FulfilledPromise as GuzzleFulfilledPromise;
+use GuzzleHttp\Promise\RejectedPromise as GuzzleRejectedPromise;
+use Http\Adapter\Guzzle6\Promise as GuzzleAdapterPromise;
+use Mockery;
use SparkPost\Test\TestUtils\ClassUtils;
class SparkPostTest extends \PHPUnit_Framework_TestCase
{
private static $utils;
- private $adapterMock;
+ private $clientMock;
/** @var SparkPost */
private $resource;
+ private $postTransmissionPayload = [
+ 'content' => [
+ 'from' => ['name' => 'Sparkpost Team', 'email' => 'postmaster@sendmailfor.me'],
+ 'subject' => 'First Mailing From PHP',
+ 'text' => 'Congratulations, {{name}}!! You just sent your very first mailing!',
+ ],
+ 'substitution_data' => ['name' => 'Avi'],
+ 'recipients' => [
+ ['address' => 'avi.goldman@sparkpost.com'],
+ ],
+ ];
+
+ private $getTransmissionPayload = [
+ 'campaign_id' => 'thanksgiving',
+ ];
+
/**
* (non-PHPdoc).
*
@@ -24,14 +43,10 @@ class SparkPostTest extends \PHPUnit_Framework_TestCase
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->clientMock = Mockery::mock('Http\Adapter\Guzzle6\Client');
- $this->resource = new SparkPost($this->adapterMock, ['key' => 'a key']);
+ $this->resource = new SparkPost($this->clientMock, ['key' => 'SPARKPOST_API_KEY']);
self::$utils = new ClassUtils($this->resource);
- self::$utils->setProperty($this->resource, 'httpAdapter', $this->adapterMock);
}
public function tearDown()
@@ -39,45 +54,221 @@ class SparkPostTest extends \PHPUnit_Framework_TestCase
Mockery::close();
}
- /**
- * @desc Ensures that the configuration class is not instantiable.
- */
- public function testConstructorSetsUpTransmissions()
+ public function testRequest()
+ {
+ $responseMock = Mockery::mock('Psr\Http\Message\ResponseInterface');
+ $this->resource->setOptions(['async' => false]);
+ $this->resource->httpClient->shouldReceive('sendRequest')->andReturn($responseMock);
+ $this->assertInstanceOf('SparkPost\SparkPostResponse', $this->resource->request('POST', 'transmissions', $this->postTransmissionPayload));
+
+ $promiseMock = Mockery::mock('Http\Promise\Promise');
+ $this->resource->setOptions(['async' => true]);
+ $this->resource->httpClient->shouldReceive('sendAsyncRequest')->andReturn($promiseMock);
+ $this->assertInstanceOf('SparkPost\SparkPostPromise', $this->resource->request('GET', 'transmissions', $this->getTransmissionPayload));
+ }
+
+ public function testSuccessfulSyncRequest()
+ {
+ $responseMock = Mockery::mock('Psr\Http\Message\ResponseInterface');
+ $responseBodyMock = Mockery::mock();
+
+ $responseBody = ['results' => 'yay'];
+
+ $this->resource->httpClient->shouldReceive('sendRequest')->
+ once()->
+ with(Mockery::type('GuzzleHttp\Psr7\Request'))->
+ andReturn($responseMock);
+
+ $responseMock->shouldReceive('getStatusCode')->andReturn(200);
+ $responseMock->shouldReceive('getBody')->andReturn($responseBodyMock);
+ $responseBodyMock->shouldReceive('__toString')->andReturn(json_encode($responseBody));
+
+ $response = $this->resource->syncRequest('POST', 'transmissions', $this->postTransmissionPayload);
+
+ $this->assertEquals($responseBody, $response->getBody());
+ $this->assertEquals(200, $response->getStatusCode());
+ }
+
+ public function testUnsuccessfulSyncRequest()
+ {
+ $exceptionMock = Mockery::mock('Http\Client\Exception\HttpException');
+
+ $responseBody = ['results' => 'failed'];
+
+ $this->resource->httpClient->shouldReceive('sendRequest')->
+ once()->
+ with(Mockery::type('GuzzleHttp\Psr7\Request'))->
+ andThrow($exceptionMock);
+
+ $exceptionMock->shouldReceive('getResponse->getStatusCode')->andReturn(500);
+ $exceptionMock->shouldReceive('getResponse->getBody->__toString')->andReturn(json_encode($responseBody));
+
+ try {
+ $this->resource->syncRequest('POST', 'transmissions', $this->postTransmissionPayload);
+ } catch (\Exception $e) {
+ $this->assertEquals($responseBody, $e->getBody());
+ $this->assertEquals(500, $e->getCode());
+ }
+ }
+
+ public function testSuccessfulAsyncRequestWithWait()
+ {
+ $promiseMock = Mockery::mock('Http\Promise\Promise');
+ $responseMock = Mockery::mock('Psr\Http\Message\ResponseInterface');
+ $responseBodyMock = Mockery::mock();
+
+ $responseBody = ['results' => 'yay'];
+
+ $this->resource->httpClient->shouldReceive('sendAsyncRequest')->
+ once()->
+ with(Mockery::type('GuzzleHttp\Psr7\Request'))->
+ andReturn($promiseMock);
+
+ $promiseMock->shouldReceive('wait')->andReturn($responseMock);
+
+ $responseMock->shouldReceive('getStatusCode')->andReturn(200);
+ $responseMock->shouldReceive('getBody')->andReturn($responseBodyMock);
+ $responseBodyMock->shouldReceive('__toString')->andReturn(json_encode($responseBody));
+
+ $promise = $this->resource->asyncRequest('POST', 'transmissions', $this->postTransmissionPayload);
+
+ $response = $promise->wait();
+
+ $this->assertEquals($responseBody, $response->getBody());
+ $this->assertEquals(200, $response->getStatusCode());
+ }
+
+ public function testUnsuccessfulAsyncRequestWithWait()
+ {
+ $promiseMock = Mockery::mock('Http\Promise\Promise');
+ $exceptionMock = Mockery::mock('Http\Client\Exception\HttpException');
+
+ $responseBody = ['results' => 'failed'];
+
+ $this->resource->httpClient->shouldReceive('sendAsyncRequest')->
+ once()->
+ with(Mockery::type('GuzzleHttp\Psr7\Request'))->
+ andReturn($promiseMock);
+
+ $promiseMock->shouldReceive('wait')->andThrow($exceptionMock);
+
+ $exceptionMock->shouldReceive('getResponse->getStatusCode')->andReturn(500);
+ $exceptionMock->shouldReceive('getResponse->getBody->__toString')->andReturn(json_encode($responseBody));
+
+ $promise = $this->resource->asyncRequest('POST', 'transmissions', $this->postTransmissionPayload);
+
+ try {
+ $response = $promise->wait();
+ } catch (\Exception $e) {
+ $this->assertEquals($responseBody, $e->getBody());
+ $this->assertEquals(500, $e->getCode());
+ }
+ }
+
+ public function testSuccessfulAsyncRequestWithThen()
+ {
+ $responseBody = ['results' => 'yay'];
+ $responseMock = Mockery::mock('Psr\Http\Message\ResponseInterface');
+ $responseBodyMock = Mockery::mock();
+ $responseMock->shouldReceive('getStatusCode')->andReturn(200);
+ $responseMock->shouldReceive('getBody')->andReturn($responseBodyMock);
+ $responseBodyMock->shouldReceive('__toString')->andReturn(json_encode($responseBody));
+
+ $guzzlePromise = new GuzzleFulfilledPromise($responseMock);
+
+ $promise = new SparkPostPromise(new GuzzleAdapterPromise($guzzlePromise, $this->resource->buildRequest('POST', 'transmissions', $this->postTransmissionPayload, [])));
+
+ $promise->then(function ($exception) use ($responseBody) {
+ $this->assertEquals(200, $exception->getStatusCode());
+ $this->assertEquals($responseBody, $exception->getBody());
+ }, null)->wait();
+ }
+
+ public function testUnsuccessfulAsyncRequestWithThen()
{
- $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());
+ $responseBody = ['results' => 'failed'];
+ $exceptionMock = Mockery::mock('Http\Client\Exception\HttpException');
+ $exceptionMock->shouldReceive('getResponse->getStatusCode')->andReturn(500);
+ $exceptionMock->shouldReceive('getResponse->getBody->__toString')->andReturn(json_encode($responseBody));
+
+ $guzzlePromise = new GuzzleRejectedPromise($exceptionMock);
+
+ $promise = new SparkPostPromise(new GuzzleAdapterPromise($guzzlePromise, $this->resource->buildRequest('POST', 'transmissions', $this->postTransmissionPayload, [])));
+
+ $promise->then(null, function ($exception) use ($responseBody) {
+ $this->assertEquals(500, $exception->getCode());
+ $this->assertEquals($responseBody, $exception->getBody());
+ })->wait();
}
- public function testSetConfigStringKey()
+ public function testPromise()
{
- $this->resource->setConfig('a key');
- $config = self::$utils->getProperty($this->resource, 'config');
- $this->assertEquals('a key', $config['key']);
+ $promiseMock = Mockery::mock('Http\Promise\Promise');
+
+ $this->resource->httpClient->shouldReceive('sendAsyncRequest')->
+ once()->
+ with(Mockery::type('GuzzleHttp\Psr7\Request'))->
+ andReturn($promiseMock);
+
+ $promise = $this->resource->asyncRequest('POST', 'transmissions', $this->postTransmissionPayload);
+
+ $promiseMock->shouldReceive('getState')->twice()->andReturn('pending');
+ $this->assertEquals($promiseMock->getState(), $promise->getState());
+
+ $promiseMock->shouldReceive('getState')->once()->andReturn('rejected');
+ $this->assertEquals('rejected', $promise->getState());
}
/**
* @expectedException Exception
- * @expectedExceptionMessageRegExp /API key/
*/
- public function testSetBadConfig()
+ public function testUnsupportedAsyncRequest()
+ {
+ $this->resource->setHttpClient(Mockery::mock('Http\Client\HttpClient'));
+
+ $this->resource->asyncRequest('POST', 'transmissions', $this->postTransmissionPayload);
+ }
+
+ public function testGetHttpHeaders()
+ {
+ $headers = $this->resource->getHttpHeaders([
+ 'Custom-Header' => 'testing',
+ ]);
+
+ $version = self::$utils->getProperty($this->resource, 'version');
+
+ $this->assertEquals('SPARKPOST_API_KEY', $headers['Authorization']);
+ $this->assertEquals('application/json', $headers['Content-Type']);
+ $this->assertEquals('testing', $headers['Custom-Header']);
+ $this->assertEquals('php-sparkpost/'.$version, $headers['User-Agent']);
+ }
+
+ public function testGetUrl()
{
- $this->resource->setConfig(['not' => 'a key']);
+ $url = 'https://api.sparkpost.com:443/api/v1/transmissions?key=value 1,value 2,value 3';
+ $testUrl = $this->resource->getUrl('transmissions', ['key' => ['value 1', 'value 2', 'value 3']]);
+ $this->assertEquals($url, $testUrl);
}
- public function testGetHeaders()
+ public function testSetHttpClient()
{
- $results = $this->resource->getHttpHeaders();
- $this->assertEquals('a key', $results['Authorization']);
- $this->assertEquals('application/json', $results['Content-Type']);
+ $this->resource->setHttpClient($this->clientMock);
+ $this->assertEquals($this->clientMock, self::$utils->getProperty($this->resource, 'httpClient'));
}
- public function testSetUnwrapped()
+ public function testSetOptionsStringKey()
+ {
+ $this->resource->setOptions('SPARKPOST_API_KEY');
+ $options = self::$utils->getProperty($this->resource, 'options');
+ $this->assertEquals('SPARKPOST_API_KEY', $options['key']);
+ }
+
+ /**
+ * @expectedException Exception
+ */
+ public function testSetBadOptions()
{
- $results = $this->resource->setupUnwrapped('ASweetEndpoint');
- $this->assertEquals($this->resource->ASweetEndpoint, $results);
- $this->assertInstanceOf('SparkPost\APIResource', $results);
- $this->assertEquals('ASweetEndpoint', $results->endpoint);
+ self::$utils->setProperty($this->resource, 'options', []);
+ $this->resource->setOptions(['not' => 'SPARKPOST_API_KEY']);
}
}
diff --git a/test/unit/TransmissionTest.php b/test/unit/TransmissionTest.php
index d606c53..84f16f0 100644
--- a/test/unit/TransmissionTest.php
+++ b/test/unit/TransmissionTest.php
@@ -2,16 +2,50 @@
namespace SparkPost\Test;
-use SparkPost\Transmission;
-use SparkPost\Test\TestUtils\ClassUtils;
+use SparkPost\SparkPost;
use Mockery;
+use SparkPost\Test\TestUtils\ClassUtils;
class TransmissionTest extends \PHPUnit_Framework_TestCase
{
private static $utils;
- private $sparkPostMock;
+ private $clientMock;
+ /** @var SparkPost */
private $resource;
+ private $postTransmissionPayload = [
+ 'content' => [
+ 'from' => ['name' => 'Sparkpost Team', 'email' => 'postmaster@sendmailfor.me'],
+ 'subject' => 'First Mailing From PHP',
+ 'text' => 'Congratulations, {{name}}!! You just sent your very first mailing!',
+ ],
+ 'substitution_data' => ['name' => 'Avi'],
+ 'recipients' => [
+ [
+ 'address' => [
+ 'name' => 'Vincent',
+ 'email' => 'vincent.song@sparkpost.com',
+ ],
+ ],
+ ['address' => 'test@example.com'],
+ ],
+ 'cc' => [
+ [
+ 'address' => [
+ 'email' => 'avi.goldman@sparkpost.com',
+ ],
+ ],
+ ],
+ 'bcc' => [
+ ['address' => 'Emely Giraldo <emely.giraldo@sparkpost.com>'],
+ ],
+
+ ];
+
+ private $getTransmissionPayload = [
+ 'campaign_id' => 'thanksgiving',
+ ];
+
/**
* (non-PHPdoc).
*
@@ -21,11 +55,10 @@ class TransmissionTest extends \PHPUnit_Framework_TestCase
*/
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);
+ //setup mock for the adapter
+ $this->clientMock = Mockery::mock('Http\Adapter\Guzzle6\Client');
+
+ $this->resource = new SparkPost($this->clientMock, ['key' => 'SPARKPOST_API_KEY', 'async' => false]);
self::$utils = new ClassUtils($this->resource);
}
@@ -34,81 +67,111 @@ class TransmissionTest extends \PHPUnit_Framework_TestCase
Mockery::close();
}
- public function testSend()
+ /**
+ * @expectedException Exception
+ */
+ public function testInvalidEmailFormat()
{
- $responseMock = Mockery::mock();
- $body = ['text' => 'awesomesauce', 'content' => ['subject' => 'awesomeness']];
+ $this->postTransmissionPayload['recipients'][] = [
+ 'address' => 'invalid email format',
+ ];
+
+ $response = $this->resource->transmissions->post($this->postTransmissionPayload);
+ }
+
+ public function testGet()
+ {
+ $responseMock = Mockery::mock('Psr\Http\Message\ResponseInterface');
+ $responseBodyMock = Mockery::mock();
+
$responseBody = ['results' => 'yay'];
- $this->sparkPostMock->httpAdapter->shouldReceive('send')->
+ $this->resource->httpClient->shouldReceive('sendRequest')->
once()->
- with('/.*\/transmissions/', 'POST', Mockery::type('array'), Mockery::type('string'))->
+ with(Mockery::type('GuzzleHttp\Psr7\Request'))->
andReturn($responseMock);
+
$responseMock->shouldReceive('getStatusCode')->andReturn(200);
+ $responseMock->shouldReceive('getBody')->andReturn($responseBodyMock);
+ $responseBodyMock->shouldReceive('__toString')->andReturn(json_encode($responseBody));
- $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody));
+ $response = $this->resource->transmissions->get($this->getTransmissionPayload);
- $this->assertEquals($responseBody, $this->resource->send($body));
+ $this->assertEquals($responseBody, $response->getBody());
+ $this->assertEquals(200, $response->getStatusCode());
}
- public function testSendDateTimeConversion()
+ public function testPut()
{
- $testStartTime = new \DateTime('2016-08-27 13:01:02', new \DateTimeZone('UTC'));
+ $responseMock = Mockery::mock('Psr\Http\Message\ResponseInterface');
+ $responseBodyMock = Mockery::mock();
- $responseMock = Mockery::mock();
$responseBody = ['results' => 'yay'];
- $this->sparkPostMock->httpAdapter->shouldReceive('send')->
+
+ $this->resource->httpClient->shouldReceive('sendRequest')->
once()->
- with('/.*\/transmissions/', 'POST', Mockery::type('array'), matchesPattern('/"start_time":"2016-08-27T13:01:02\+00:00"/'))->
+ with(Mockery::type('GuzzleHttp\Psr7\Request'))->
andReturn($responseMock);
+
$responseMock->shouldReceive('getStatusCode')->andReturn(200);
- $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody));
+ $responseMock->shouldReceive('getBody')->andReturn($responseBodyMock);
+ $responseBodyMock->shouldReceive('__toString')->andReturn(json_encode($responseBody));
+
+ $response = $this->resource->transmissions->put($this->getTransmissionPayload);
- $this->assertEquals($responseBody, $this->resource->send(['startTime' => $testStartTime]));
+ $this->assertEquals($responseBody, $response->getBody());
+ $this->assertEquals(200, $response->getStatusCode());
}
- public function testAllWithFilter()
+ public function testPost()
{
- $responseMock = Mockery::mock();
+ $responseMock = Mockery::mock('Psr\Http\Message\ResponseInterface');
+ $responseBodyMock = Mockery::mock();
+
$responseBody = ['results' => 'yay'];
- $this->sparkPostMock->httpAdapter->shouldReceive('send')->
+
+ $this->resource->httpClient->shouldReceive('sendRequest')->
once()->
- with('/.*transmissions.*?campaign_id=campaign&template_id=template/', 'GET', Mockery::type('array'), null)->
+ with(Mockery::type('GuzzleHttp\Psr7\Request'))->
andReturn($responseMock);
+
$responseMock->shouldReceive('getStatusCode')->andReturn(200);
+ $responseMock->shouldReceive('getBody')->andReturn($responseBodyMock);
+ $responseBodyMock->shouldReceive('__toString')->andReturn(json_encode($responseBody));
- $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody));
+ $response = $this->resource->transmissions->post($this->postTransmissionPayload);
- $this->assertEquals($responseBody, $this->resource->all('campaign', 'template'));
+ $this->assertEquals($responseBody, $response->getBody());
+ $this->assertEquals(200, $response->getStatusCode());
}
- public function testAllWithOutFilter()
+ public function testDelete()
{
- $responseMock = Mockery::mock();
+ $responseMock = Mockery::mock('Psr\Http\Message\ResponseInterface');
+ $responseBodyMock = Mockery::mock();
+
$responseBody = ['results' => 'yay'];
- $this->sparkPostMock->httpAdapter->shouldReceive('send')->
+
+ $this->resource->httpClient->shouldReceive('sendRequest')->
once()->
- with('/.*\/transmissions/', 'GET', Mockery::type('array'), null)->
+ with(Mockery::type('GuzzleHttp\Psr7\Request'))->
andReturn($responseMock);
+
$responseMock->shouldReceive('getStatusCode')->andReturn(200);
+ $responseMock->shouldReceive('getBody')->andReturn($responseBodyMock);
+ $responseBodyMock->shouldReceive('__toString')->andReturn(json_encode($responseBody));
- $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody));
+ $response = $this->resource->transmissions->delete($this->getTransmissionPayload);
- $this->assertEquals($responseBody, $this->resource->all());
+ $this->assertEquals($responseBody, $response->getBody());
+ $this->assertEquals(200, $response->getStatusCode());
}
- public function testFind()
+ public function testFormatPayload()
{
- $responseMock = Mockery::mock();
- $responseBody = ['results' => 'yay'];
- $this->sparkPostMock->httpAdapter->shouldReceive('send')->
- once()->
- with('/.*\/transmissions.*\/test/', 'GET', Mockery::type('array'), null)->
- andReturn($responseMock);
- $responseMock->shouldReceive('getStatusCode')->andReturn(200);
-
- $responseMock->shouldReceive('getBody->getContents')->andReturn(json_encode($responseBody));
+ $correctFormattedPayload = json_decode('{"content":{"from":{"name":"Sparkpost Team","email":"postmaster@sendmailfor.me"},"subject":"First Mailing From PHP","text":"Congratulations, {{name}}!! You just sent your very first mailing!","headers":{"CC":"avi.goldman@sparkpost.com"}},"substitution_data":{"name":"Avi"},"recipients":[{"address":{"name":"Vincent","email":"vincent.song@sparkpost.com"}},{"address":{"email":"test@example.com"}},{"address":{"email":"emely.giraldo@sparkpost.com","header_to":"\"Vincent\" <vincent.song@sparkpost.com>"}},{"address":{"email":"avi.goldman@sparkpost.com","header_to":"\"Vincent\" <vincent.song@sparkpost.com>"}}]}', true);
- $this->assertEquals($responseBody, $this->resource->find('test'));
+ $formattedPayload = $this->resource->transmissions->formatPayload($this->postTransmissionPayload);
+ $this->assertEquals($correctFormattedPayload, $formattedPayload);
}
}