Skip to content

Commit 5c7859c

Browse files
committed
feature #481 Add more tests to blog post (yceruto)
This PR was merged into the master branch. Discussion ---------- Add more tests to blog post * Testing new blog post * Testing show blog post (admin) * Testing add a comment to post * Changing some `PostFixtures` methods to static for reusability * Simplify and reordering some tests Commits ------- 2700136 Add more tests
2 parents e0fa00c + 2700136 commit 5c7859c

File tree

7 files changed

+310
-165
lines changed

7 files changed

+310
-165
lines changed

src/AppBundle/DataFixtures/ORM/PostFixtures.php

Lines changed: 3 additions & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,12 @@
1313

1414
use AppBundle\Entity\Comment;
1515
use AppBundle\Entity\Post;
16-
use AppBundle\Entity\Tag;
1716
use Doctrine\Common\DataFixtures\AbstractFixture;
1817
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
1918
use Doctrine\Common\Persistence\ObjectManager;
2019
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
2120
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
21+
use Tests\FixturesTrait;
2222

2323
/**
2424
* Defines the sample blog posts to load in the database before running the unit
@@ -35,6 +35,7 @@
3535
class PostFixtures extends AbstractFixture implements DependentFixtureInterface, ContainerAwareInterface
3636
{
3737
use ContainerAwareTrait;
38+
use FixturesTrait;
3839

3940
/**
4041
* {@inheritdoc}
@@ -100,124 +101,11 @@ private function getRandomTags($numTags = 0)
100101
return $tags;
101102
}
102103

103-
$indexes = (array) array_rand(TagFixtures::$names, $numTags);
104+
$indexes = (array) array_rand($this->getTagNames(), $numTags);
104105
foreach ($indexes as $index) {
105106
$tags[] = $this->getReference('tag-'.$index);
106107
}
107108

108109
return $tags;
109110
}
110-
111-
private function getPostContent()
112-
{
113-
return <<<'MARKDOWN'
114-
Lorem ipsum dolor sit amet consectetur adipisicing elit, sed do eiusmod tempor
115-
incididunt ut labore et **dolore magna aliqua**: Duis aute irure dolor in
116-
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
117-
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
118-
deserunt mollit anim id est laborum.
119-
120-
* Ut enim ad minim veniam
121-
* Quis nostrud exercitation *ullamco laboris*
122-
* Nisi ut aliquip ex ea commodo consequat
123-
124-
Praesent id fermentum lorem. Ut est lorem, fringilla at accumsan nec, euismod at
125-
nunc. Aenean mattis sollicitudin mattis. Nullam pulvinar vestibulum bibendum.
126-
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos
127-
himenaeos. Fusce nulla purus, gravida ac interdum ut, blandit eget ex. Duis a
128-
luctus dolor.
129-
130-
Integer auctor massa maximus nulla scelerisque accumsan. *Aliquam ac malesuada*
131-
ex. Pellentesque tortor magna, vulputate eu vulputate ut, venenatis ac lectus.
132-
Praesent ut lacinia sem. Mauris a lectus eget felis mollis feugiat. Quisque
133-
efficitur, mi ut semper pulvinar, urna urna blandit massa, eget tincidunt augue
134-
nulla vitae est.
135-
136-
Ut posuere aliquet tincidunt. Aliquam erat volutpat. **Class aptent taciti**
137-
sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi
138-
arcu orci, gravida eget aliquam eu, suscipit et ante. Morbi vulputate metus vel
139-
ipsum finibus, ut dapibus massa feugiat. Vestibulum vel lobortis libero. Sed
140-
tincidunt tellus et viverra scelerisque. Pellentesque tincidunt cursus felis.
141-
Sed in egestas erat.
142-
143-
Aliquam pulvinar interdum massa, vel ullamcorper ante consectetur eu. Vestibulum
144-
lacinia ac enim vel placerat. Integer pulvinar magna nec dui malesuada, nec
145-
congue nisl dictum. Donec mollis nisl tortor, at congue erat consequat a. Nam
146-
tempus elit porta, blandit elit vel, viverra lorem. Sed sit amet tellus
147-
tincidunt, faucibus nisl in, aliquet libero.
148-
MARKDOWN;
149-
}
150-
151-
private function getPhrases()
152-
{
153-
return [
154-
'Lorem ipsum dolor sit amet consectetur adipiscing elit',
155-
'Pellentesque vitae velit ex',
156-
'Mauris dapibus risus quis suscipit vulputate',
157-
'Eros diam egestas libero eu vulputate risus',
158-
'In hac habitasse platea dictumst',
159-
'Morbi tempus commodo mattis',
160-
'Ut suscipit posuere justo at vulputate',
161-
'Ut eleifend mauris et risus ultrices egestas',
162-
'Aliquam sodales odio id eleifend tristique',
163-
'Urna nisl sollicitudin id varius orci quam id turpis',
164-
'Nulla porta lobortis ligula vel egestas',
165-
'Curabitur aliquam euismod dolor non ornare',
166-
'Sed varius a risus eget aliquam',
167-
'Nunc viverra elit ac laoreet suscipit',
168-
'Pellentesque et sapien pulvinar consectetur',
169-
'Ubi est barbatus nix',
170-
'Abnobas sunt hilotaes de placidus vita',
171-
'Ubi est audax amicitia',
172-
'Eposs sunt solems de superbus fortis',
173-
'Vae humani generis',
174-
'Diatrias tolerare tanquam noster caesium',
175-
'Teres talis saepe tractare de camerarius flavum sensorem',
176-
'Silva de secundus galatae demitto quadra',
177-
'Sunt accentores vitare salvus flavum parses',
178-
'Potus sensim ad ferox abnoba',
179-
'Sunt seculaes transferre talis camerarius fluctuies',
180-
'Era brevis ratione est',
181-
'Sunt torquises imitari velox mirabilis medicinaes',
182-
'Mineralis persuadere omnes finises desiderium',
183-
'Bassus fatalis classiss virtualiter transferre de flavum',
184-
];
185-
}
186-
187-
private function getRandomPostTitles()
188-
{
189-
$phrases = $this->getPhrases();
190-
191-
// this ensures that the first title is always 'Lorem Ipsum...'
192-
$loremIpsumPhrase = array_shift($phrases);
193-
shuffle($phrases);
194-
array_unshift($phrases, $loremIpsumPhrase);
195-
196-
return $phrases;
197-
}
198-
199-
private function getRandomPostSummary($maxLength = 255)
200-
{
201-
$phrases = $this->getPhrases();
202-
203-
$numPhrases = mt_rand(6, 12);
204-
shuffle($phrases);
205-
$phrases = array_slice($phrases, 0, $numPhrases - 1);
206-
207-
while (strlen($summary = implode('. ', $phrases).'.') > $maxLength) {
208-
array_pop($phrases);
209-
}
210-
211-
return $summary;
212-
}
213-
214-
private function getRandomCommentContent()
215-
{
216-
$phrases = $this->getPhrases();
217-
218-
$numPhrases = mt_rand(2, 15);
219-
shuffle($phrases);
220-
221-
return implode(' ', array_slice($phrases, 0, $numPhrases - 1));
222-
}
223111
}

src/AppBundle/DataFixtures/ORM/TagFixtures.php

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use AppBundle\Entity\Tag;
1515
use Doctrine\Common\DataFixtures\AbstractFixture;
1616
use Doctrine\Common\Persistence\ObjectManager;
17+
use Tests\FixturesTrait;
1718

1819
/**
1920
* Defines the sample blog tags to load in the database before running the unit
@@ -27,24 +28,14 @@
2728
*/
2829
class TagFixtures extends AbstractFixture
2930
{
30-
public static $names = [
31-
'lorem',
32-
'ipsum',
33-
'consectetur',
34-
'adipiscing',
35-
'incididunt',
36-
'labore',
37-
'voluptate',
38-
'dolore',
39-
'pariatur',
40-
];
31+
use FixturesTrait;
4132

4233
/**
4334
* {@inheritdoc}
4435
*/
4536
public function load(ObjectManager $manager)
4637
{
47-
foreach (self::$names as $index => $name) {
38+
foreach ($this->getTagNames() as $index => $name) {
4839
$tag = new Tag();
4940
$tag->setName($name);
5041

tests/AppBundle/Controller/Admin/BlogControllerTest.php

Lines changed: 57 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
use AppBundle\Entity\Post;
1515
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
1616
use Symfony\Component\HttpFoundation\Response;
17+
use Tests\ControllerTestTrait;
18+
use Tests\FixturesTrait;
1719

1820
/**
1921
* Functional test for the controllers defined inside the BlogController used
@@ -32,37 +34,26 @@
3234
*/
3335
class BlogControllerTest extends WebTestCase
3436
{
37+
use ControllerTestTrait;
38+
use FixturesTrait;
39+
3540
/**
3641
* @dataProvider getUrlsForRegularUsers
3742
*/
38-
public function testRegularUsers($httpMethod, $url, $statusCode)
43+
public function testAccessDeniedForRegularUsers($httpMethod, $url)
3944
{
40-
$client = static::createClient([], [
41-
'PHP_AUTH_USER' => 'john_user',
42-
'PHP_AUTH_PW' => 'kitten',
43-
]);
45+
$client = $this->getUserClient();
4446

4547
$client->request($httpMethod, $url);
46-
$this->assertSame($statusCode, $client->getResponse()->getStatusCode());
48+
$this->assertSame(Response::HTTP_FORBIDDEN, $client->getResponse()->getStatusCode());
4749
}
4850

4951
public function getUrlsForRegularUsers()
5052
{
51-
yield ['GET', '/en/admin/post/', Response::HTTP_FORBIDDEN];
52-
yield ['GET', '/en/admin/post/1', Response::HTTP_FORBIDDEN];
53-
yield ['GET', '/en/admin/post/1/edit', Response::HTTP_FORBIDDEN];
54-
yield ['POST', '/en/admin/post/1/delete', Response::HTTP_FORBIDDEN];
55-
}
56-
57-
/**
58-
* @return \Symfony\Bundle\FrameworkBundle\Client
59-
*/
60-
private function getAdminClient()
61-
{
62-
return static::createClient([], [
63-
'PHP_AUTH_USER' => 'jane_admin',
64-
'PHP_AUTH_PW' => 'kitten',
65-
]);
53+
yield ['GET', '/en/admin/post/'];
54+
yield ['GET', '/en/admin/post/1'];
55+
yield ['GET', '/en/admin/post/1/edit'];
56+
yield ['POST', '/en/admin/post/1/delete'];
6657
}
6758

6859
public function testAdminBackendHomePage()
@@ -80,21 +71,42 @@ public function testAdminBackendHomePage()
8071
}
8172

8273
/**
83-
* This test changes the database contents by deleting a blog post. However,
74+
* This test changes the database contents by creating a new blog post. However,
8475
* thanks to the DAMADoctrineTestBundle and its PHPUnit listener, all changes
8576
* to the database are rolled back when this test completes. This means that
8677
* all the application tests begin with the same database contents.
8778
*/
88-
public function testAdminDeletePost()
79+
public function testAdminNewPost()
8980
{
81+
$postTitle = 'Blog Post Title '.mt_rand();
82+
$postSummary = $this->getRandomPostSummary();
83+
$postContent = $this->getPostContent();
84+
9085
$client = $this->getAdminClient();
91-
$crawler = $client->request('GET', '/en/admin/post/1');
92-
$client->submit($crawler->filter('#delete-form')->form());
86+
$crawler = $client->request('GET', '/en/admin/post/new');
87+
$form = $crawler->selectButton('Create post')->form([
88+
'post[title]' => $postTitle,
89+
'post[summary]' => $postSummary,
90+
'post[content]' => $postContent,
91+
]);
92+
$client->submit($form);
9393

9494
$this->assertSame(Response::HTTP_FOUND, $client->getResponse()->getStatusCode());
9595

96-
$post = $client->getContainer()->get('doctrine')->getRepository(Post::class)->find(1);
97-
$this->assertNull($post);
96+
$post = $client->getContainer()->get('doctrine')->getRepository(Post::class)->findOneBy([
97+
'title' => $postTitle,
98+
]);
99+
$this->assertNotNull($post);
100+
$this->assertSame($postSummary, $post->getSummary());
101+
$this->assertSame($postContent, $post->getContent());
102+
}
103+
104+
public function testAdminShowPost()
105+
{
106+
$client = $this->getAdminClient();
107+
$client->request('GET', '/en/admin/post/1');
108+
109+
$this->assertSame(Response::HTTP_OK, $client->getResponse()->getStatusCode());
98110
}
99111

100112
/**
@@ -120,4 +132,22 @@ public function testAdminEditPost()
120132
$post = $client->getContainer()->get('doctrine')->getRepository(Post::class)->find(1);
121133
$this->assertSame($newBlogPostTitle, $post->getTitle());
122134
}
135+
136+
/**
137+
* This test changes the database contents by deleting a blog post. However,
138+
* thanks to the DAMADoctrineTestBundle and its PHPUnit listener, all changes
139+
* to the database are rolled back when this test completes. This means that
140+
* all the application tests begin with the same database contents.
141+
*/
142+
public function testAdminDeletePost()
143+
{
144+
$client = $this->getAdminClient();
145+
$crawler = $client->request('GET', '/en/admin/post/1');
146+
$client->submit($crawler->filter('#delete-form')->form());
147+
148+
$this->assertSame(Response::HTTP_FOUND, $client->getResponse()->getStatusCode());
149+
150+
$post = $client->getContainer()->get('doctrine')->getRepository(Post::class)->find(1);
151+
$this->assertNull($post);
152+
}
123153
}

tests/AppBundle/Controller/BlogControllerTest.php

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@
1313

1414
use AppBundle\Entity\Post;
1515
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
16+
use Symfony\Component\HttpFoundation\Response;
17+
use Tests\ControllerTestTrait;
18+
use Tests\FixturesTrait;
1619

1720
/**
1821
* Functional test for the controllers defined inside BlogController.
@@ -26,9 +29,12 @@
2629
*/
2730
class BlogControllerTest extends WebTestCase
2831
{
32+
use ControllerTestTrait;
33+
use FixturesTrait;
34+
2935
public function testIndex()
3036
{
31-
$client = static::createClient();
37+
$client = $this->getAnonymousClient();
3238
$crawler = $client->request('GET', '/en/blog/');
3339

3440
$this->assertCount(
@@ -40,7 +46,7 @@ public function testIndex()
4046

4147
public function testRss()
4248
{
43-
$client = static::createClient();
49+
$client = $this->getAnonymousClient();
4450
$crawler = $client->request('GET', '/en/blog/rss.xml');
4551

4652
$this->assertSame(
@@ -54,4 +60,35 @@ public function testRss()
5460
'The xml file displays the right number of posts.'
5561
);
5662
}
63+
64+
/**
65+
* This test changes the database contents by creating a new comment. However,
66+
* thanks to the DAMADoctrineTestBundle and its PHPUnit listener, all changes
67+
* to the database are rolled back when this test completes. This means that
68+
* all the application tests begin with the same database contents.
69+
*/
70+
public function testNewComment()
71+
{
72+
$client = $this->getUserClient();
73+
74+
/** @var Post $post */
75+
$post = $client->getContainer()->get('doctrine')->getRepository(Post::class)->find(1);
76+
$commentContent = $this->getRandomCommentContent();
77+
$commentsCount = $post->getComments()->count();
78+
79+
$crawler = $client->request('GET', '/en/blog/posts/'.$post->getSlug());
80+
$form = $crawler->selectButton('Publish comment')->form([
81+
'comment[content]' => $commentContent,
82+
]);
83+
$client->submit($form);
84+
85+
$this->assertSame(Response::HTTP_FOUND, $client->getResponse()->getStatusCode());
86+
87+
$post = $client->getContainer()->get('doctrine')->getRepository(Post::class)->find(1);
88+
// The first one is the last inserted (See descending order of comments association).
89+
$comment = $post->getComments()->first();
90+
91+
$this->assertSame($commentsCount + 1, $post->getComments()->count());
92+
$this->assertSame($commentContent, $comment->getContent());
93+
}
5794
}

0 commit comments

Comments
 (0)