Skip to content

Commit

Permalink
Make IntegrationTestCase::_buildRequest return an array.
Browse files Browse the repository at this point in the history
This is a breaking change to the protected method, but I feel its
necessary in order to make other things easier. For example, getting all
headers out of a Cake\Request is not possible right now. By using the
array return value we can easily access all the different aspects of the
simulated request.
  • Loading branch information
markstory committed Jun 15, 2016
1 parent 0ef9d47 commit 43f8ed3
Show file tree
Hide file tree
Showing 6 changed files with 89 additions and 47 deletions.
6 changes: 3 additions & 3 deletions src/TestSuite/IntegrationTestCase.php
Expand Up @@ -393,7 +393,7 @@ protected function _sendRequest($url, $method, $data = [])
try { try {
$request = $this->_buildRequest($url, $method, $data); $request = $this->_buildRequest($url, $method, $data);
$response = $dispatcher->execute($request); $response = $dispatcher->execute($request);
$this->_requestSession = $request->session(); $this->_requestSession = $request['session'];
$this->_response = $response; $this->_response = $response;
} catch (PHPUnit_Exception $e) { } catch (PHPUnit_Exception $e) {
throw $e; throw $e;
Expand Down Expand Up @@ -455,7 +455,7 @@ protected function _handleError($exception)
* @param string|array $url The URL * @param string|array $url The URL
* @param string $method The HTTP method * @param string $method The HTTP method
* @param array|null $data The request data. * @param array|null $data The request data.
* @return \Cake\Network\Request The built request. * @return array The request context
*/ */
protected function _buildRequest($url, $method, $data) protected function _buildRequest($url, $method, $data)
{ {
Expand Down Expand Up @@ -486,7 +486,7 @@ protected function _buildRequest($url, $method, $data)
$env['REQUEST_METHOD'] = $method; $env['REQUEST_METHOD'] = $method;
$props['environment'] = $env; $props['environment'] = $env;
$props = Hash::merge($props, $this->_request); $props = Hash::merge($props, $this->_request);
return new Request($props); return $props;
} }


/** /**
Expand Down
14 changes: 4 additions & 10 deletions src/TestSuite/MiddlewareDispatcher.php
Expand Up @@ -68,19 +68,13 @@ public function execute($request)


$server = new Server($app); $server = new Server($app);


// TODO How to handle passing all headers.
// The Request doesn't expose a way to read all headers values.
// TODO How to pass session data? PSR7 requests don't handle sessions.. // TODO How to pass session data? PSR7 requests don't handle sessions..
// TODO pass php://input stream, base, webroot // TODO pass php://input stream, base, webroot
$serverData = [
'REQUEST_URI' => $request->here,
'REQUEST_METHOD' => $request->method(),
];
$psrRequest = ServerRequestFactory::fromGlobals( $psrRequest = ServerRequestFactory::fromGlobals(
array_merge($_SERVER, $serverData), array_merge($_SERVER, $request['environment'], ['REQUEST_URI' => $request['url']]),
$request->query, $request['query'],
$request->data(), $request['post'],
$request->cookies $request['cookies']
); );
$response = $server->run($psrRequest); $response = $server->run($psrRequest);
return ResponseTransformer::toCake($response); return ResponseTransformer::toCake($response);
Expand Down
3 changes: 2 additions & 1 deletion src/TestSuite/RequestDispatcher.php
Expand Up @@ -40,11 +40,12 @@ public function __construct($test)
/** /**
* Run a request and get the response. * Run a request and get the response.
* *
* @param \Cake\Network\Request $request The request to execute. * @param array $request The request context to execute.
* @return \Cake\Network\Response The generated response. * @return \Cake\Network\Response The generated response.
*/ */
public function execute($request) public function execute($request)
{ {
$request = new Request($request);
$response = new Response(); $response = new Response();
$dispatcher = DispatcherFactory::create(); $dispatcher = DispatcherFactory::create();
$dispatcher->eventManager()->on( $dispatcher->eventManager()->on(
Expand Down
107 changes: 75 additions & 32 deletions tests/TestCase/TestSuite/IntegrationTestCaseTest.php
Expand Up @@ -66,13 +66,13 @@ public function testRequestBuilding()
$this->session(['User' => ['id' => 1, 'username' => 'mark']]); $this->session(['User' => ['id' => 1, 'username' => 'mark']]);
$request = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']); $request = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']);


$this->assertEquals('abc123', $request->header('X-CSRF-Token')); $this->assertEquals('abc123', $request['environment']['HTTP_X_CSRF_TOKEN']);
$this->assertEquals('tasks/add', $request->url); $this->assertEquals('/tasks/add', $request['url']);
$this->assertArrayHasKey('split_token', $request->cookies); $this->assertArrayHasKey('split_token', $request['cookies']);
$this->assertEquals('def345', $request->cookies['split_token']); $this->assertEquals('def345', $request['cookies']['split_token']);
$this->assertEquals(['id' => '1', 'username' => 'mark'], $request->session()->read('User')); $this->assertEquals(['id' => '1', 'username' => 'mark'], $request['session']->read('User'));
$this->assertEquals('foo', $request->env('PHP_AUTH_USER')); $this->assertEquals('foo', $request['environment']['PHP_AUTH_USER']);
$this->assertEquals('bar', $request->env('PHP_AUTH_PW')); $this->assertEquals('bar', $request['environment']['PHP_AUTH_PW']);
} }


/** /**
Expand All @@ -85,18 +85,18 @@ public function testRequestBuildingCsrfTokens()
$this->enableCsrfToken(); $this->enableCsrfToken();
$request = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']); $request = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']);


$this->assertArrayHasKey('csrfToken', $request->cookies); $this->assertArrayHasKey('csrfToken', $request['cookies']);
$this->assertArrayHasKey('_csrfToken', $request->data); $this->assertArrayHasKey('_csrfToken', $request['post']);
$this->assertSame($request->cookies['csrfToken'], $request->data['_csrfToken']); $this->assertSame($request['cookies']['csrfToken'], $request['post']['_csrfToken']);


$this->cookie('csrfToken', ''); $this->cookie('csrfToken', '');
$request = $this->_buildRequest('/tasks/add', 'POST', [ $request = $this->_buildRequest('/tasks/add', 'POST', [
'_csrfToken' => 'fale', '_csrfToken' => 'fale',
'title' => 'First post' 'title' => 'First post'
]); ]);


$this->assertSame('', $request->cookies['csrfToken']); $this->assertSame('', $request['cookies']['csrfToken']);
$this->assertSame('fale', $request->data['_csrfToken']); $this->assertSame('fale', $request['post']['_csrfToken']);
} }


/** /**
Expand All @@ -109,10 +109,14 @@ public function testEnableCsrfMultipleRequests()
$this->enableCsrfToken(); $this->enableCsrfToken();
$first = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']); $first = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']);
$second = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'Second post']); $second = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'Second post']);
$this->assertSame($first->cookies['csrfToken'], $second->data['_csrfToken'], 'Csrf token should match cookie');
$this->assertSame( $this->assertSame(
$first->data['_csrfToken'], $first['cookies']['csrfToken'],
$second->data['_csrfToken'], $second['post']['_csrfToken'],
'Csrf token should match cookie'
);
$this->assertSame(
$first['post']['_csrfToken'],
$second['post']['_csrfToken'],
'Tokens should be consistent per test method' 'Tokens should be consistent per test method'
); );
} }
Expand All @@ -128,8 +132,8 @@ public function testEnableCsrfPredeterminedCookie()
$value = 'I am a teapot'; $value = 'I am a teapot';
$this->cookie('csrfToken', $value); $this->cookie('csrfToken', $value);
$request = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']); $request = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']);
$this->assertSame($value, $request->cookies['csrfToken'], 'Csrf token should match cookie'); $this->assertSame($value, $request['cookies']['csrfToken'], 'Csrf token should match cookie');
$this->assertSame($value, $request->data['_csrfToken'], 'Tokens should match'); $this->assertSame($value, $request['post']['_csrfToken'], 'Tokens should match');
} }


/** /**
Expand All @@ -141,8 +145,8 @@ public function testRequestBuildingQueryParameters()
{ {
$request = $this->_buildRequest('/tasks/view?archived=yes', 'GET', []); $request = $this->_buildRequest('/tasks/view?archived=yes', 'GET', []);


$this->assertEquals('/tasks/view?archived=yes', $request->here()); $this->assertEquals('/tasks/view', $request['url']);
$this->assertEquals('yes', $request->query('archived')); $this->assertEquals('yes', $request['query']['archived']);
} }


/** /**
Expand All @@ -155,7 +159,7 @@ public function testCookieEncrypted()
Security::salt('abcdabcdabcdabcdabcdabcdabcdabcdabcd'); Security::salt('abcdabcdabcdabcdabcdabcdabcdabcdabcd');
$this->cookieEncrypted('KeyOfCookie', 'Encrypted with aes by default'); $this->cookieEncrypted('KeyOfCookie', 'Encrypted with aes by default');
$request = $this->_buildRequest('/tasks/view', 'GET', []); $request = $this->_buildRequest('/tasks/view', 'GET', []);
$this->assertStringStartsWith('Q2FrZQ==.', $request->cookies['KeyOfCookie']); $this->assertStringStartsWith('Q2FrZQ==.', $request['cookies']['KeyOfCookie']);
} }


/** /**
Expand Down Expand Up @@ -188,8 +192,58 @@ public function testGetHttpServer()
$this->assertNotEmpty($this->_response); $this->assertNotEmpty($this->_response);
$this->assertInstanceOf('Cake\Network\Response', $this->_response); $this->assertInstanceOf('Cake\Network\Response', $this->_response);
$this->assertEquals('This is a test', $this->_response->body()); $this->assertEquals('This is a test', $this->_response->body());
$this->assertHeader('X-Middleware', 'true');
} }


/**
* Test that the PSR7 requests get query string data
*
* @return void
*/
public function testQueryStringHttpServer()
{
$this->useHttpServer(true);

$this->configRequest(['headers' => ['Content-Type' => 'text/plain']]);
$this->get('/request_action/params_pass?q=query');
$this->assertResponseOk();
$this->assertResponseContains('"q":"query"');
$this->assertResponseContains('"contentType":"text\/plain"');
$this->assertHeader('X-Middleware', 'true');
}

/**
* Test that the PSR7 requests get cookies
*
* @return void
*/
public function testGetCookiesHttpServer()
{
$this->useHttpServer(true);

$this->configRequest(['cookies' => ['split_test' => 'abc']]);
$this->get('/request_action/cookie_pass');
$this->assertResponseOk();
$this->assertResponseContains('"split_test":"abc"');
$this->assertHeader('X-Middleware', 'true');
}

/**
* Test that the PSR7 requests get post data
*
* @return void
*/
public function testPostDataHttpServer()
{
$this->useHttpServer(true);

$this->post('/request_action/post_pass', ['title' => 'value']);
$data = json_decode($this->_response->body());
$this->assertEquals('value', $data->title);
$this->assertHeader('X-Middleware', 'true');
}


/** /**
* Test sending requests stores references to controller/view/layout. * Test sending requests stores references to controller/view/layout.
* *
Expand All @@ -216,9 +270,8 @@ public function testRequestSetsProperties()
*/ */
public function testRequestSetsPropertiesHttpServer() public function testRequestSetsPropertiesHttpServer()
{ {
$this->markTestIncomplete('not done');
DispatcherFactory::clear();
$this->useHttpServer(true); $this->useHttpServer(true);
DispatcherFactory::clear();


$this->post('/posts/index'); $this->post('/posts/index');
$this->assertInstanceOf('Cake\Controller\Controller', $this->_controller); $this->assertInstanceOf('Cake\Controller\Controller', $this->_controller);
Expand All @@ -232,16 +285,6 @@ public function testRequestSetsPropertiesHttpServer()
$this->assertEquals('value', $this->viewVariable('test')); $this->assertEquals('value', $this->viewVariable('test'));
} }


/**
* Test that the PSR7 requests get post, cookies, and other request data passed along.
*
* @return void
*/
public function testPsrRequestData()
{
$this->markTestIncomplete('not done');
}

/** /**
* Assert that the stored template doesn't change when cells are rendered. * Assert that the stored template doesn't change when cells are rendered.
* *
Expand Down
4 changes: 4 additions & 0 deletions tests/test_app/TestApp/Application.php
Expand Up @@ -34,6 +34,10 @@ public function bootstrap()
public function middleware($middleware) public function middleware($middleware)
{ {
$middleware->push(new RoutingMiddleware()); $middleware->push(new RoutingMiddleware());
$middleware->push(function ($req, $res, $next) {
$res = $next($req, $res);
return $res->withHeader('X-Middleware', 'true');
});
return $middleware; return $middleware;
} }
} }
Expand Up @@ -134,7 +134,7 @@ public function params_pass()
'params' => $this->request->params, 'params' => $this->request->params,
'query' => $this->request->query, 'query' => $this->request->query,
'url' => $this->request->url, 'url' => $this->request->url,
'contentType' => $this->request->env('CONTENT_TYPE'), 'contentType' => $this->request->contentType(),
])); ]));
return $this->response; return $this->response;
} }
Expand Down

0 comments on commit 43f8ed3

Please sign in to comment.