Completed
Pull Request — master (#6)
by Robbie
02:39 queued 13s
created

CwpControllerExtensionTest   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 132
Duplicated Lines 32.58 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 43
loc 132
rs 10
wmc 7

6 Methods

Rating   Name   Duplication   Size   Complexity  
A testRequiresLoginForLiveWhenEnabled() 0 14 2
A testRedirectsSSLToDomain() 14 14 1
A testRequiresLoginForNonTest() 0 6 1
A testRequiresLoginForTest() 0 12 2
A testRedirectsSSLToCurrentDomain() 13 13 1
A setUp() 0 18 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace CWP\Core\Tests;
4
5
use CWP\Core\Extension\CwpControllerExtension;
6
use Exception;
7
use SilverStripe\Control\Controller;
8
use SilverStripe\Control\Director;
9
use SilverStripe\Control\HTTPRequest;
10
use SilverStripe\Control\Middleware\CanonicalURLMiddleware;
11
use SilverStripe\Control\Session;
12
use SilverStripe\Core\Config\Config;
13
use SilverStripe\Core\Injector\Injector;
14
use SilverStripe\Core\Kernel;
15
use SilverStripe\Dev\SapphireTest;
16
17
/**
18
 * Tests for the CWP Core controller extension. Note that tests here will use configuration to mock the
19
 * responses from {@link Director} method calls.
20
 */
21
class CwpControllerExtensionTest extends SapphireTest
22
{
23
    /**
24
     * @var Controller
25
     */
26
    protected $controller;
27
28
    /**
29
     * @var CanonicalURLMiddleware
30
     */
31
    protected $middlewareMock;
32
33
    protected function setUp()
34
    {
35
        parent::setUp();
36
37
        $this->logOut();
38
39
        $this->controller = new Controller();
40
41
        $request = new HTTPRequest('GET', '/');
42
        $request->setSession(new Session([]));
43
44
        $this->controller->setRequest($request);
45
46
        $this->middlewareMock = $this->getMockBuilder(CanonicalURLMiddleware::class)
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getMockBuilder(Si...tForceSSL'))->getMock() of type PHPUnit_Framework_MockObject_MockObject is incompatible with the declared type SilverStripe\Control\Mid...\CanonicalURLMiddleware of property $middlewareMock.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
47
            ->setMethods(['setForceSSL'])
48
            ->getMock();
49
50
        Injector::inst()->registerService($this->middlewareMock, CanonicalURLMiddleware::class);
51
    }
52
53 View Code Duplication
    public function testRedirectsSSLToDomain()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
54
    {
55
        Config::modify()->set(Director::class, 'alternate_base_url', 'http://nothttps.local');
56
57
        // Expecting this to call forceSSL to forcedomain.org.
58
        $this->middlewareMock->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not exist on SilverStripe\Control\Mid...\CanonicalURLMiddleware. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

58
        $this->middlewareMock->/** @scrutinizer ignore-call */ 
59
                               expects($this->once())

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
59
            ->method('setForceSSL')
60
            ->with(true)
61
            ->will($this->returnSelf());
62
63
        Config::modify()->set(CwpControllerExtension::class, 'ssl_redirection_enabled', true);
64
        Config::modify()->set(CwpControllerExtension::class, 'ssl_redirection_force_domain', 'forcedomain.org');
65
66
        $this->controller->handleRequest($this->controller->getRequest());
67
    }
68
69 View Code Duplication
    public function testRedirectsSSLToCurrentDomain()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
70
    {
71
        Config::modify()->set(Director::class, 'alternate_base_url', 'http://nothttps.local');
72
73
        // Expecting this to call forceSSL to current domain.
74
        $this->middlewareMock->expects($this->once())
75
            ->method('setForceSSL')
76
            ->will($this->returnSelf());
77
78
        Config::modify()->set(CwpControllerExtension::class, 'ssl_redirection_enabled', true);
79
        Config::modify()->set(CwpControllerExtension::class, 'ssl_redirection_force_domain', false);
80
81
        $this->controller->handleRequest($this->controller->getRequest());
82
    }
83
84
    public function testRequiresLoginForTest()
85
    {
86
        Injector::inst()->get(Kernel::class)->setEnvironment('test');
87
88
        try {
89
            $this->controller->handleRequest($this->controller->getRequest());
90
        } catch (Exception $e) {
91
            $this->assertEquals($e->getResponse()->getStatusCode(), '401', 'Forces BasicAuth on test');
0 ignored issues
show
Bug introduced by
The method getResponse() does not exist on Exception. It seems like you code against a sub-type of Exception such as SilverStripe\Control\HTTPResponse_Exception or Embed\Exceptions\InvalidUrlException. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

91
            $this->assertEquals($e->/** @scrutinizer ignore-call */ getResponse()->getStatusCode(), '401', 'Forces BasicAuth on test');
Loading history...
92
93
            // We need to pop manually, since throwing an SS_HTTPResponse_Exception in onBeforeInit hijacks
94
            // the normal Controller control flow and confuses TestRunner (as they share global controller stack).
95
            $this->controller->popCurrent();
96
        }
97
    }
98
99
    public function testRequiresLoginForNonTest()
100
    {
101
        Injector::inst()->get(Kernel::class)->setEnvironment('live');
102
103
        $response = $this->controller->handleRequest($this->controller->getRequest());
104
        $this->assertEquals($response->getStatusCode(), '200', 'Does not force BasicAuth on live');
105
    }
106
107
    public function testRequiresLoginForLiveWhenEnabled()
108
    {
109
        Config::modify()->set(CwpControllerExtension::class, 'live_basicauth_enabled', true);
110
111
        Injector::inst()->get(Kernel::class)->setEnvironment('live');
112
113
        try {
114
            $this->controller->handleRequest($this->controller->getRequest());
115
        } catch (Exception $e) {
116
            $this->assertEquals($e->getResponse()->getStatusCode(), '401', 'Forces BasicAuth on live (optionally)');
117
118
            // We need to pop manually, since throwing an SS_HTTPResponse_Exception in onBeforeInit hijacks
119
            // the normal Controller control flow and confuses TestRunner (as they share global controller stack).
120
            $this->controller->popCurrent();
121
        }
122
    }
123
}
124