Completed
Pull Request — master (#360)
by
unknown
02:03
created

FixtureContext::assertMessageBoxContainsText()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace SilverStripe\AssetAdmin\Tests\Behat\Context;
4
5
use Behat\Mink\Element\DocumentElement;
6
use Behat\Mink\Element\NodeElement;
7
use SilverStripe\BehatExtension\Context\FixtureContext as BaseFixtureContext;
8
9
/**
10
 * Context used to create fixtures in the SilverStripe ORM.
11
 */
12
class FixtureContext extends BaseFixtureContext
13
{
14
15
    /**
16
     * Select a gallery item by type and name
17
     *
18
     * @Given /^I (?:(?:click on)|(?:select)) the file named "([^"]+)" in the gallery$/
19
     * @param string $name
20
     */
21
    public function stepISelectGalleryItem($name)
22
    {
23
        $item = $this->getGalleryItem($name);
24
        assertNotNull($item, "File named $name could not be found");
25
        $item->click();
26
    }
27
28
    /**
29
     * Check the checkbox for a given gallery item
30
     * @Given /^I check the file named "([^"]+)" in the gallery$/
31
     * @param string $name
32
     */
33
    public function stepICheckTheGalleryItem($name)
34
    {
35
        $item = $this->getGalleryItem($name);
36
        assertNotNull($item, "File named $name could not be found");
37
        $checkbox = $item->find('css', 'input[type="checkbox"]');
38
        assertNotNull($checkbox, "Could not find checkbox for file named {$name}");
39
        $checkbox->check();
40
    }
41
42
    /**
43
     * @Then /^I should see the file named "([^"]+)" in the gallery$/
44
     * @param string $name
45
     */
46
    public function iShouldSeeTheGalleryItem($name)
47
    {
48
        $item = $this->getGalleryItem($name);
49
        assertNotNull($item, "File named {$name} could not be found");
50
    }
51
52
    /**
53
     * @Then /^I should not see the file named "([^"]+)" in the gallery$/
54
     * @param string $name
55
     */
56
    public function iShouldNotSeeTheGalleryItem($name)
57
    {
58
        $item = $this->getGalleryItem($name, 0);
59
        assertNull($item, "File named {$name} was found when it should not be visible");
60
    }
61
62
    /**
63
     * @Then /^I should see the "([^"]*)" form$/
64
     * @param string $id HTML ID of form
65
     */
66
    public function iShouldSeeTheForm($id)
67
    {
68
        /** @var DocumentElement $page */
69
        $page = $this->getSession()->getPage();
70
        $form = $this->retry(function () use ($page, $id) {
71
            return $page->find('css', "form#{$id}");
72
        });
73
        assertNotNull($form, "form with id $id could not be found");
74
        assertTrue($form->isVisible(), "form with id $id is not visible");
75
    }
76
77
    /**
78
     * @Given /^I click on the latest history item$/
79
     */
80
    public function iClickOnTheLatestHistoryItem()
81
    {
82
        $this->getSession()->wait(
83
            5000,
84
            "window.jQuery && window.jQuery('.file-history__list li').size() > 0"
85
        );
86
87
        $page = $this->getSession()->getPage();
88
89
        $elements = $page->find('css', '.file-history__list li');
90
91
        if (null === $elements) {
92
            throw new \InvalidArgumentException(sprintf('Could not find list item'));
93
        }
94
95
        $elements->click();
96
    }
97
98
    /**
99
     * @Given /^I attach the file "([^"]*)" to dropzone "([^"]*)"$/
100
     * @see MinkContext::attachFileToField()
101
     */
102
    public function iAttachTheFileToDropzone($path, $name)
103
    {
104
        // Get path
105
        $filesPath = $this->getMainContext()->getMinkParameter('files_path');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Behat\Behat\Context\ExtendedContextInterface as the method getMinkParameter() does only exist in the following implementations of said interface: Behat\MinkExtension\Context\MinkContext, Behat\MinkExtension\Context\RawMinkContext, SilverStripe\AssetAdmin\...\Context\FeatureContext, SilverStripe\BehatExtens...ext\SilverStripeContext, SilverStripe\Cms\Test\Behaviour\FeatureContext.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
106
        if ($filesPath) {
107
            $fullPath = rtrim(realpath($filesPath), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$path;
108
            if (is_file($fullPath)) {
109
                $path = $fullPath;
110
            }
111
        }
112
113
        assertFileExists($path, "$path does not exist");
114
        // Find field
115
        $selector = "input[type=\"file\"].dz-hidden-input.dz-input-{$name}";
116
117
        /** @var DocumentElement $page */
118
        $page = $this->getSession()->getPage();
119
        $input = $page->find('css', $selector);
120
        assertNotNull($input, "Could not find {$selector}");
121
122
        // Make visible temporarily while attaching
123
        $this->getSession()->executeScript(
124
            <<<EOS
125
window.jQuery('.dz-hidden-input')
126
    .css('visibility', 'visible')
127
    .width(1)
128
    .height(1);
129
EOS
130
        );
131
132
        assert($input->isVisible());
133
        // Attach via html5
134
        $input->attachFile($path);
135
    }
136
137
    /**
138
     * Checks that the message box contains specified text.
139
     *
140
     * @Then /^I should see "(?P<text>(?:[^"]|\\")*)" in the message box$/
141
     */
142
    public function assertMessageBoxContainsText($text)
143
    {
144
        $this->assertSession()->elementTextContains('css', '.message-box', $this->fixStepArgument($text));
0 ignored issues
show
Bug introduced by
The method assertSession() does not seem to exist on object<SilverStripe\Asse...Context\FixtureContext>.

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...
Bug introduced by
The method fixStepArgument() does not seem to exist on object<SilverStripe\Asse...Context\FixtureContext>.

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...
145
    }
146
147
    /**
148
     * Helper for finding items in the visible gallery view
149
     *
150
     * @param string $name Title of item
151
     * @param int $timeout
152
     * @return NodeElement
153
     */
154
    protected function getGalleryItem($name, $timeout = 3)
155
    {
156
        /** @var DocumentElement $page */
157
        $page = $this->getSession()->getPage();
158
        return $this->retry(function () use ($page, $name) {
159
            // Find by cell
160
            $cell = $page->find(
161
                'xpath',
162
                "//div[contains(@class, 'gallery-item')]//div[contains(text(), '{$name}')]"
163
            );
164
            if ($cell) {
165
                return $cell;
166
            }
167
            // Find by row
168
            $row = $page->find(
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $row is correct as $page->find('xpath', "//...s(text(), '{$name}')]") (which targets Behat\Mink\Element\Element::find()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
169
                'xpath',
170
                "//tr[contains(@class, 'gallery__table-row')]//div[contains(text(), '{$name}')]"
171
            );
172
            if ($row) {
173
                return $row;
174
            }
175
            return null;
176
        }, $timeout);
177
    }
178
179
    /**
180
     * Invoke $try callback for a non-empty result with a given timeout
181
     *
182
     * @param callable $try
183
     * @param int $timeout Number of seconds to retry for
184
     * @return mixed Result of invoking $try, or null if timed out
185
     */
186
    protected function retry($try, $timeout = 3)
187
    {
188
        do {
189
            $result = $try();
190
            if ($result) {
191
                return $result;
192
            }
193
            sleep(1);
194
        } while (--$timeout >= 0);
195
        return null;
196
    }
197
}
198