Completed
Pull Request — master (#25)
by
unknown
04:49
created

AzineEmailControllerTest   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 146
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 7
dl 0
loc 146
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A testAdminEmailsDashboardAction() 0 51 2
B loginUserIfRequired() 0 34 4
A getRouter() 0 4 1
A getContainer() 0 8 2
A getEntityManager() 0 4 1
A checkApplication() 0 10 2
1
<?php
2
namespace Azine\EmailBundle\Tests\Controller;
3
use Azine\EmailBundle\DependencyInjection\AzineEmailExtension;
4
use Azine\EmailBundle\Services\AzineEmailTwigExtension;
5
use Azine\EmailBundle\Services\Pagination;
6
use Azine\EmailBundle\Tests\FindInFileUtil;
7
use Azine\EmailBundle\Services\AzineTemplateProvider;
8
use Azine\EmailBundle\Entity\SentEmail;
9
use Azine\EmailBundle\Controller\AzineEmailTemplateController;
10
use Azine\PlatformBundle\Services\EmailTemplateProvider;
11
use Symfony\Component\DependencyInjection\ContainerInterface;
12
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
13
use Symfony\Component\HttpFoundation\ParameterBag;
14
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\HttpFoundation\Response;
16
use Symfony\Component\HttpFoundation\Session\Session;
17
use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;
18
use Symfony\Component\Routing\RequestContext;
19
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
20
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
21
use Symfony\Component\DomCrawler\Crawler;
22
use Symfony\Bundle\FrameworkBundle\Client;
23
use Azine\EmailBundle\Tests\TestHelper;
24
use Doctrine\ORM\EntityManager;
25
26
class AzineEmailControllerTest extends WebTestCase
27
{
28
    public function testAdminEmailsDashboardAction()
29
    {
30
        $this->checkApplication();
31
32
        // Create a new client to browse the application
33
        $client = static::createClient();
34
        $client->followRedirects();
35
36
        $manager = $this->getEntityManager();
37
        $sentEmailRep = $manager->getRepository("Azine\EmailBundle\Entity\SentEmail");
38
39
        $sentEmails = $sentEmailRep->findAll();
40
41
        $count = count($sentEmails);
42
43
        $pagination = $this->getContainer()->get('azine.email.bundle.pagination');
44
45
        $manager = $this->getEntityManager();
46
47
        // make sure there is some data in the application
48
        if ($count < $pagination->getDefaultPageSize()) {
49
50
            $amountToAdd = $pagination->getDefaultPageSize() * 2;
51
            TestHelper::addSentEmails($manager, $amountToAdd);
52
53
            $count += $amountToAdd;
54
        }
55
56
        $listUrl = substr($this->getRouter()->generate("admin_emails_dashboard", array('_locale' => "en")), 13);
57
        $crawler = $this->loginUserIfRequired($client, $listUrl);
58
59
        $this->assertEquals($pagination->getDefaultPageSize(), $crawler->filter(".sentEmail")->count(), "emailsDashboard expected with .".$pagination->getDefaultPageSize()." sent emails");
60
61
        $numberOfPaginationLinks = floor($count / $pagination->getDefaultPageSize()) + 3;
62
        $this->assertEquals($numberOfPaginationLinks, $crawler->filter(".pagination li")->count(),$numberOfPaginationLinks . " pagination links expected");
63
64
        //click on an email web view link to get to the web page
65
        $link = $crawler->filter("tr:contains('".EmailTemplateProvider::NEWSLETTER_TEMPLATE."')")->first()->filter("td")->last()->filter("a")->first()->link();
66
        $crawler = $client->click($link);
67
68
        $this->assertEquals(1, $crawler->filter("span:contains('_az.email.hello')")->count(), " div with hello message expected.");
69
70
        $crawler = $this->loginUserIfRequired($client, $listUrl);
71
72
        //click on an email details view link to get to the details page
73
        $link = $crawler->filter("tr:contains('[email protected]')")->first()->filter("td")->last()->filter("a")->last()->link();
74
        $crawler = $client->click($link);
75
76
        $this->assertEquals(1, $crawler->filter("tr:contains('[email protected]')")->count(),"Table cell with email expected");
77
78
    }
79
80
    /**
81
     * Load the url and login if required.
82
     * @param  string  $url
83
     * @param  string  $username
84
     * @param  Client  $client
85
     * @return Crawler $crawler of the page of the url or the page after the login
86
     */
87
    private function loginUserIfRequired(Client $client, $url, $username = "dominik", $password = "lkjlkjlkjlkj")
88
    {
89
        // try to get the url
90
        $client->followRedirects();
91
        $crawler = $client->request("GET", $url);
92
93
        $this->assertEquals(200, $client->getResponse()->getStatusCode(), "Status-Code 200 expected.");
94
95
        // if redirected to a login-page, login as admin-user
96
        if ($crawler->filter("input")->count() == 5 && $crawler->filter("#username")->count() == 1 && $crawler->filter("#password")->count() == 1 ) {
97
98
            // set the password of the admin
99
            $userProvider = $this->getContainer()->get('fos_user.user_provider.username_email');
100
            $user = $userProvider->loadUserByUsername($username);
101
            $user->setPlainPassword($password);
102
            $user->addRole("ROLE_ADMIN");
103
104
            $userManager = $this->getContainer()->get('fos_user.user_manager');
105
            $userManager->updateUser($user);
106
107
            $crawler = $crawler->filter("input[type='submit']");
108
            $form = $crawler->form();
109
            $form->get('_username')->setValue($username);
110
            $form->get('_password')->setValue($password);
111
            $crawler = $client->submit($form);
112
        }
113
114
        $this->assertEquals(200, $client->getResponse()->getStatusCode(),"Login failed.");
115
        $client->followRedirects(false);
116
117
        $this->assertStringEndsWith($url, $client->getRequest()->getUri(), "Login failed or not redirected to requested url: $url vs. ".$client->getRequest()->getUri());
118
119
        return $crawler;
120
    }
121
122
    /**
123
     * @var ContainerInterface
124
     */
125
    private $container;
126
127
    /**
128
     * @return UrlGeneratorInterface
129
     */
130
    private function getRouter()
131
    {
132
        return $this->getContainer()->get('router');
133
    }
134
135
    /**
136
     * Get the current container
137
     * @return \Symfony\Component\DependencyInjection\ContainerInterface
138
     */
139
    private function getContainer()
140
    {
141
        if ($this->container == null) {
142
            $this->container = static::$kernel->getContainer();
143
        }
144
145
        return $this->container;
146
    }
147
148
    /**
149
     * @return EntityManager
150
     */
151
    private function getEntityManager()
152
    {
153
        return $this->getContainer()->get('doctrine.orm.entity_manager');
154
    }
155
156
    /**
157
     * Check if the current setup is a full application.
158
     * If not, mark the test as skipped else continue.
159
     */
160
    private function checkApplication()
161
    {
162
        try {
163
            static::$kernel = static::createKernel(array());
164
        } catch (\RuntimeException $ex) {
165
            $this->markTestSkipped("There does not seem to be a full application available (e.g. running tests on travis.org). So this test is skipped.");
166
167
            return;
168
        }
169
    }
170
171
}
172