-
Notifications
You must be signed in to change notification settings - Fork 0
/
TestCase.php
300 lines (247 loc) · 8.26 KB
/
TestCase.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
<?php
namespace Brightmarch\TestingBundle;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\UserInterface;
use \ReflectionClass,
\ReflectionMethod;
abstract class TestCase extends WebTestCase
{
/** @var Container */
private $container = null;
/** @var array */
private $fixtures = [];
/** @const string */
const DATETIME_FORMAT = 'Y-m-d H:i:s';
public function tearDown()
{
parent::tearDown();
$this->container = null;
}
/**
* Returns the current time.
*
* @return DateTime
*/
public function now()
{
return date_create();
}
/**
* Creates an authenticated client against a firewall.
*
* @param Symfony\Component\Security\Core\User\UserInterface $user
* @param string $firewall
* @return Symfony\Bundle\FrameworkBundle\Client
*/
protected function authenticate(UserInterface $user, $firewall)
{
$securityKey = sprintf('_security_%s', $firewall);
$client = $this->getClient();
$client->followRedirects(false);
$session = $client->getContainer()->get('session');
$session->start();
$cookie = new Cookie($session->getName(), $session->getId());
$client->getCookieJar()->set($cookie);
$token = new UsernamePasswordToken($user, null, $firewall, $user->getRoles());
$session->set($securityKey, serialize($token));
$session->save();
return $client;
}
/**
* Creates a stateless authenticated client from a UserInterface object.
*
* @param Symfony\Component\Security\Core\User\UserInterface $user
* @return Symfony\Bundle\FrameworkBundle\Client
*/
protected function authenticateStateless(UserInterface $user)
{
return $this->getClient([
'PHP_AUTH_USER' => $user->getUsername(),
'PHP_AUTH_PW' => $user->getPassword()
]);
}
/**
* Installs the data fixtures for a test case.
*
* @param string $managerName
* @param boolean $append
* @return boolean
*/
protected function installDataFixtures($managerName, $append = false)
{
$_em = $this->get('doctrine')
->getManager($managerName);
// Reset any fixtures already managed for this entity manager.
$this->fixtures[$managerName] = [];
// Get all of the fixtures from the parameters.
$fixtures = $this->getContainer()
->getParameterBag()
->all()['fixtures'];
$_conn = $_em->getConnection();
// Purge out old data first.
if (!$append) {
$entities = array_map(function($fixture) {
return $fixture['_entity'];
}, array_reverse($fixtures));
$entities = array_unique($entities);
foreach ($entities as $entity) {
$table = $_em->getClassMetadata($entity)
->getTableName();
// DELETEs are dramatically faster than TRUNCATEs,
// at least for small tables in Postgres.
$_conn->executeUpdate("DELETE FROM $table");
}
}
// Create a converter to convert snake case to camelCase.
$converter = new CamelCaseToSnakeCaseNameConverter;
// Next, create the new fixtures.
foreach ($fixtures as $ref => $fixture) {
$refClass = new ReflectionClass($fixture['_entity']);
$entity = $refClass->newInstance();
foreach ($fixture as $field => $value) {
// _entity is a special field so it is ignored.
if ('_entity' !== $field) {
// If the value begins with a tilde, it references
// another entity that is hopefully already hydrated.
if (0 === strpos($value, '~')) {
$xref = substr($value, 1);
$value = null;
if (isset($this->fixtures[$managerName][$xref])) {
$value = $this->fixtures[$managerName][$xref];
}
}
// See if the value can be converted to a DateTime object
// because Doctrine expects an object rather than a string.
if (is_string($value)) {
$dateTime = date_create_from_format(self::DATETIME_FORMAT, $value);
if ($dateTime) {
$value = $dateTime;
}
}
// Construct the setter and call it.
$field = $converter->denormalize($field);
$setter = sprintf('set%s', ucwords($field));
$refMethod = new ReflectionMethod($entity, $setter);
$refMethod->invoke($entity, $value);
}
}
// Immediately flush the fixture entity.
$_em->persist($entity);
$_em->flush();
// And refresh it so cross relationships work.
$_em->refresh($entity);
$this->fixtures[$managerName][$ref] = $entity;
}
return true;
}
/**
* Boots a kernel and runs a console command. The output of the command is returned.
*
* @param Symfony\Component\Console\Command\Command $command
* @param array $arguments
* @return string
*/
protected function runCommand(Command $command, $arguments = [])
{
$application = new Application($this->getKernel());
$application->add($command);
$command = $application->find($command->getName());
$commandTester = new CommandTester($command);
$commandTester->execute($arguments);
return $commandTester->getDisplay();
}
/**
* Returns a newly built kernel.
*
* @return \AppKernel
*/
protected function getKernel()
{
$kernel = static::createKernel();
$kernel->boot();
return $kernel;
}
/**
* Gets the container for this kernel.
*
* @return Symfony\Component\DependencyInjection\Container
*/
protected function getContainer()
{
if (!$this->container) {
$this->container = $this->getKernel()
->getContainer();
}
return $this->container;
}
/**
* Returns a service from the container.
*
* @return mixed
*/
protected function get($service)
{
return $this->getContainer()
->get($service);
}
/**
* Gets a web client for navigating URLs.
*
* @param array $server
* @return Client
*/
protected function getClient(array $server = [])
{
$client = $this->getContainer()
->get('test.client');
$client->setServerParameters($server);
return $client;
}
/**
* Get fixture by name.
*
* @param string $fixture
* @param string $managerName
* @return mixed
*/
protected function getFixture($fixture, $managerName)
{
if ($this->hasFixture($fixture, $managerName)) {
return $this->fixtures[$managerName][$fixture];
}
return null;
}
/**
* Has fixture.
*
* @param string $fixture
* @param string $managerName
* @return boolean
*/
public function hasFixture($fixture, $managerName)
{
if (isset($this->fixtures[$managerName])) {
return isset($this->fixtures[$managerName][$fixture]);
}
return false;
}
/**
* Generates a URL based on a route.
*
* @param string $route
* @param array $parameters
* @param boolean $absolute
* @return string
*/
protected function getUrl($route, array $parameters = [], $absolute = false)
{
return $this->get('router')
->generate($route, $parameters, $absolute);
}
}