Completed
Pull Request — master (#25)
by
unknown
03:51
created

AzineEmailControllerTest   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 165
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

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

6 Methods

Rating   Name   Duplication   Size   Complexity  
A testAdminEmailsDashboardAction() 0 70 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
        $crawler = $this->loginUserIfRequired($client, $listUrl);
79
80
        //Test filtering by email
81
        $crawler = $crawler->selectButton('sentEmail[save]');
82
        $form = $crawler->form();
83
        $form['sentEmail[recipients]'] = '[email protected]';
84
        $crawler = $client->submit($form);
85
86
        $this->assertEquals($crawler->filter(".sentEmail")->count(), $crawler->filter("tr:contains('[email protected]')")->count(),"Table rows only with [email protected] email are expected");
87
88
        $form['sentEmail[recipients]'] = '';
89
        $crawler = $client->submit($form);
0 ignored issues
show
Unused Code introduced by
$crawler is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
90
91
        //Test filtering by token
92
        $form['sentEmail[token]'] = 'fdasdfasfafsadf';
93
        $crawler = $client->submit($form);
94
95
        $this->assertEquals($crawler->filter(".sentEmail")->count(), $crawler->filter("tr:contains('fdasdfasfafsadf')")->count(),"Table rows only with fdasdfasfafsadf token are expected");
96
97
    }
98
99
    /**
100
     * Load the url and login if required.
101
     * @param  string  $url
102
     * @param  string  $username
103
     * @param  Client  $client
104
     * @return Crawler $crawler of the page of the url or the page after the login
105
     */
106
    private function loginUserIfRequired(Client $client, $url, $username = "dominik", $password = "lkjlkjlkjlkj")
107
    {
108
        // try to get the url
109
        $client->followRedirects();
110
        $crawler = $client->request("GET", $url);
111
112
        $this->assertEquals(200, $client->getResponse()->getStatusCode(), "Status-Code 200 expected.");
113
114
        // if redirected to a login-page, login as admin-user
115
        if ($crawler->filter("input")->count() == 5 && $crawler->filter("#username")->count() == 1 && $crawler->filter("#password")->count() == 1 ) {
116
117
            // set the password of the admin
118
            $userProvider = $this->getContainer()->get('fos_user.user_provider.username_email');
119
            $user = $userProvider->loadUserByUsername($username);
120
            $user->setPlainPassword($password);
121
            $user->addRole("ROLE_ADMIN");
122
123
            $userManager = $this->getContainer()->get('fos_user.user_manager');
124
            $userManager->updateUser($user);
125
126
            $crawler = $crawler->filter("input[type='submit']");
127
            $form = $crawler->form();
128
            $form->get('_username')->setValue($username);
129
            $form->get('_password')->setValue($password);
130
            $crawler = $client->submit($form);
131
        }
132
133
        $this->assertEquals(200, $client->getResponse()->getStatusCode(),"Login failed.");
134
        $client->followRedirects(false);
135
136
        $this->assertStringEndsWith($url, $client->getRequest()->getUri(), "Login failed or not redirected to requested url: $url vs. ".$client->getRequest()->getUri());
137
138
        return $crawler;
139
    }
140
141
    /**
142
     * @var ContainerInterface
143
     */
144
    private $container;
145
146
    /**
147
     * @return UrlGeneratorInterface
148
     */
149
    private function getRouter()
150
    {
151
        return $this->getContainer()->get('router');
152
    }
153
154
    /**
155
     * Get the current container
156
     * @return \Symfony\Component\DependencyInjection\ContainerInterface
157
     */
158
    private function getContainer()
159
    {
160
        if ($this->container == null) {
161
            $this->container = static::$kernel->getContainer();
162
        }
163
164
        return $this->container;
165
    }
166
167
    /**
168
     * @return EntityManager
169
     */
170
    private function getEntityManager()
171
    {
172
        return $this->getContainer()->get('doctrine.orm.entity_manager');
173
    }
174
175
    /**
176
     * Check if the current setup is a full application.
177
     * If not, mark the test as skipped else continue.
178
     */
179
    private function checkApplication()
180
    {
181
        try {
182
            static::$kernel = static::createKernel(array());
183
        } catch (\RuntimeException $ex) {
184
            $this->markTestSkipped("There does not seem to be a full application available (e.g. running tests on travis.org). So this test is skipped.");
185
186
            return;
187
        }
188
    }
189
190
}
191