Passed
Pull Request — 1.x (#39)
by Kevin
04:31 queued 02:42
created

BrowserTests::can_use_current_browser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 8
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 13
rs 10
1
<?php
2
3
namespace Zenstruck\Browser\Tests;
4
5
use Symfony\Component\Filesystem\Filesystem;
6
use Symfony\Component\VarDumper\VarDumper;
7
use Zenstruck\Browser;
8
use Zenstruck\Browser\Test\HasBrowser;
9
use Zenstruck\Browser\Tests\Fixture\TestComponent1;
10
use Zenstruck\Browser\Tests\Fixture\TestComponent2;
11
use Zenstruck\Callback\Exception\UnresolveableArgument;
12
13
/**
14
 * @author Kevin Bond <[email protected]>
15
 */
16
trait BrowserTests
17
{
18
    use HasBrowser {
19
        browser as kernelBrowser;
20
    }
21
22
    /**
23
     * @test
24
     */
25
    public function multiple_browsers(): void
26
    {
27
        $browser1 = $this->browser()
28
            ->visit('/page1')
29
            ->assertOn('/page1')
30
        ;
31
32
        $browser2 = $this->browser()
0 ignored issues
show
Unused Code introduced by
The assignment to $browser2 is dead and can be removed.
Loading history...
33
            ->visit('/page2')
34
            ->assertOn('/page2')
35
        ;
36
37
        // this ensures a different browser is actually used
38
        $browser1->assertOn('/page1');
39
    }
40
41
    /**
42
     * @test
43
     */
44
    public function assert_on(): void
45
    {
46
        $this->browser()
47
            ->visit('/page1')
48
            ->assertOn('/page1')
49
            ->assertOn('http://www.example.com/page1')
50
            ->assertNotOn('/page2')
51
            ->assertNotOn('http://www.example.com/page1', ['path', 'host'])
52
            ->visit('/page1?foo=bar')
53
            ->assertOn('/page1?foo=bar')
54
            ->assertOn('/page1', ['path'])
55
            ->assertOn('/page1', ['path', 'fragment'])
56
            ->assertNotOn('/page1?foo=baz')
57
        ;
58
    }
59
60
    /**
61
     * @test
62
     * @dataProvider encodedUrlProvider
63
     */
64
    public function assert_on_encoded($url, $expected): void
65
    {
66
        $this->browser()
67
            ->visit($url)
68
            ->assertOn($expected)
69
        ;
70
    }
71
72
    public static function encodedUrlProvider(): iterable
73
    {
74
        yield ['/page1?filter[q]=value', '/page1?filter[q]=value'];
75
        yield ['/page1?filter%5Bq%5D=value', '/page1?filter[q]=value'];
76
        yield ['/page1?filter[q]=value', '/page1?filter%5Bq%5D=value'];
77
        yield ['/page1#foo bar', '/page1#foo bar'];
78
        yield ['/page1#foo%20bar', '/page1#foo bar'];
79
        yield ['/page1#foo bar', '/page1#foo%20bar'];
80
        yield ['/page1#foo+bar', '/page1#foo bar'];
81
        yield ['/page1#foo bar', '/page1#foo+bar'];
82
    }
83
84
    /**
85
     * @test
86
     */
87
    public function can_use_current_browser(): void
88
    {
89
        $browser = $this->browser();
90
91
        $browser
92
            ->use(function(Browser $b) use ($browser) {
93
                $this->assertSame($b, $browser);
0 ignored issues
show
Bug introduced by
The method assertSame() does not exist on Zenstruck\Browser\Tests\BrowserTests. Did you maybe mean assert_on()? ( Ignorable by Annotation )

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

93
                $this->/** @scrutinizer ignore-call */ 
94
                       assertSame($b, $browser);

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...
94
95
                $browser->visit('/redirect1');
96
            })
97
            ->assertOn('/page1')
98
            ->use(function() {
99
                $this->assertTrue(true);
0 ignored issues
show
Bug introduced by
The method assertTrue() does not exist on Zenstruck\Browser\Tests\BrowserTests. Did you maybe mean assert_on()? ( Ignorable by Annotation )

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

99
                $this->/** @scrutinizer ignore-call */ 
100
                       assertTrue(true);

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...
100
            })
101
        ;
102
    }
103
104
    /**
105
     * @test
106
     */
107
    public function can_use_components(): void
108
    {
109
        $this->browser()
110
            ->use(function(TestComponent1 $component) {
111
                $component->assertTitle('h1 title');
112
            })
113
            ->assertOn('/page1')
114
        ;
115
    }
116
117
    /**
118
     * @test
119
     */
120
    public function component_pre_assertions_and_actions_are_called(): void
121
    {
122
        $this->browser()
123
            ->use(function(TestComponent2 $component) {
124
                $this->assertTrue($component->preActionsCalled);
125
                $this->assertTrue($component->preAssertionsCalled);
126
            })
127
        ;
128
    }
129
130
    /**
131
     * @test
132
     */
133
    public function with_can_accept_multiple_browsers_and_components(): void
134
    {
135
        $browser = $this->browser();
136
137
        $browser
138
            ->use(function(Browser $browser1, $browser2, TestComponent1 $component1, TestComponent2 $component2) use ($browser) {
139
                $this->assertInstanceOf(Browser::class, $browser1);
0 ignored issues
show
Bug introduced by
It seems like assertInstanceOf() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

139
                $this->/** @scrutinizer ignore-call */ 
140
                       assertInstanceOf(Browser::class, $browser1);
Loading history...
140
                $this->assertInstanceOf(Browser::class, $browser2);
141
                $this->assertInstanceOf(\get_class($browser), $browser1);
142
                $this->assertInstanceOf(\get_class($browser), $browser2);
143
                $this->assertInstanceOf(TestComponent1::class, $component1);
144
                $this->assertInstanceOf(TestComponent2::class, $component2);
145
            })
146
        ;
147
    }
148
149
    /**
150
     * @test
151
     */
152
    public function invalid_use_callback_parameter_throws_type_error(): void
153
    {
154
        $this->expectException(UnresolveableArgument::class);
0 ignored issues
show
Bug introduced by
It seems like expectException() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

154
        $this->/** @scrutinizer ignore-call */ 
155
               expectException(UnresolveableArgument::class);
Loading history...
155
156
        $this->browser()->use(function(string $invalidType) {});
0 ignored issues
show
Unused Code introduced by
The parameter $invalidType is not used and could be removed. ( Ignorable by Annotation )

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

156
        $this->browser()->use(function(/** @scrutinizer ignore-unused */ string $invalidType) {});

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
157
    }
158
159
    /**
160
     * @test
161
     */
162
    public function redirects_are_followed_by_default(): void
163
    {
164
        $this->browser()
165
            ->visit('/redirect1')
166
            ->assertOn('/page1')
167
        ;
168
    }
169
170
    /**
171
     * @test
172
     */
173
    public function content_assertions(): void
174
    {
175
        $this->browser()
176
            ->visit('/page1')
177
            ->assertContains('h1 title')
178
            ->assertNotContains('invalid text')
179
        ;
180
    }
181
182
    /**
183
     * @test
184
     */
185
    public function can_dump_response(): void
186
    {
187
        $output = self::catchVarDumperOutput(function() {
188
            $this->browser()
189
                ->visit('/page1')
190
                ->dump()
191
            ;
192
        });
193
194
        $this->assertStringContainsString('/page1', $output[0]);
0 ignored issues
show
Bug introduced by
It seems like assertStringContainsString() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

194
        $this->/** @scrutinizer ignore-call */ 
195
               assertStringContainsString('/page1', $output[0]);
Loading history...
195
        $this->assertStringContainsString('<html', $output[0]);
196
        $this->assertStringContainsString('<h1>h1 title</h1>', $output[0]);
197
    }
198
199
    /**
200
     * @test
201
     */
202
    public function can_save_source(): void
203
    {
204
        $contents = self::catchFileContents(__DIR__.'/../var/browser/source/source.txt', function() {
205
            $this->browser()
206
                ->visit('/page1')
207
                ->saveSource('source.txt')
208
            ;
209
        });
210
211
        $this->assertStringContainsString('/page1', $contents);
212
        $this->assertStringContainsString('<html', $contents);
213
        $this->assertStringContainsString('<h1>h1 title</h1>', $contents);
214
    }
215
216
    /**
217
     * @test
218
     */
219
    public function html_assertions(): void
220
    {
221
        $this->browser()
222
            ->visit('/page1')
223
            ->assertSee('h1 title')
224
            ->assertNotSee('invalid text')
225
            ->assertSeeIn('h1', 'title')
226
            ->assertNotSeeIn('h1', 'invalid text')
227
            ->assertSeeElement('h1')
228
            ->assertNotSeeElement('h2')
229
            ->assertElementCount('ul li', 2)
230
        ;
231
    }
232
233
    /**
234
     * @test
235
     */
236
    public function html_head_assertions(): void
237
    {
238
        $this->browser()
239
            ->visit('/page1')
240
            ->assertSeeIn('title', 'meta title')
241
            ->assertElementAttributeContains('meta[name="description"]', 'content', 'meta')
242
            ->assertElementAttributeNotContains('meta[name="description"]', 'content', 'invalid')
243
            ->assertElementAttributeContains('html', 'lang', 'en')
244
        ;
245
    }
246
247
    /**
248
     * @test
249
     */
250
    public function form_assertions(): void
251
    {
252
        $this->browser()
253
            ->visit('/page1')
254
            ->assertFieldEquals('Input 1', 'input 1')
255
            ->assertFieldEquals('input1', 'input 1')
256
            ->assertFieldEquals('input_1', 'input 1')
257
            ->assertFieldNotEquals('Input 1', 'invalid')
258
            ->assertFieldNotEquals('input1', 'invalid')
259
            ->assertFieldNotEquals('input_1', 'invalid')
260
            ->assertChecked('Input 3')
261
            ->assertChecked('input3')
262
            ->assertChecked('input_3')
263
            ->assertNotChecked('Input 2')
264
            ->assertNotChecked('input2')
265
            ->assertNotChecked('input_2')
266
            ->assertSelected('Input 4', 'option 1')
267
            ->assertSelected('input4', 'option 1')
268
            ->assertSelected('input_4', 'option 1')
269
            ->assertSelected('Input 7', 'option 1')
270
            ->assertSelected('input7', 'option 1')
271
            ->assertSelected('input_7[]', 'option 1')
272
            ->assertSelected('Input 7', 'option 3')
273
            ->assertSelected('input7', 'option 3')
274
            ->assertSelected('input_7[]', 'option 3')
275
            ->assertNotSelected('Input 4', 'option 2')
276
            ->assertNotSelected('input4', 'option 2')
277
            ->assertNotSelected('input_4', 'option 2')
278
            ->assertNotSelected('Input 7', 'option 2')
279
            ->assertNotSelected('input7', 'option 2')
280
            ->assertNotSelected('input_7[]', 'option 2')
281
        ;
282
    }
283
284
    /**
285
     * @test
286
     */
287
    public function link_action(): void
288
    {
289
        $this->browser()
290
            ->visit('/page1')
291
            ->follow('a link')
292
            ->assertOn('/page2')
293
            ->visit('/page1')
294
            ->click('a link')
295
            ->assertOn('/page2')
296
        ;
297
    }
298
299
    /**
300
     * @test
301
     */
302
    public function form_actions_by_field_label(): void
303
    {
304
        $this->browser()
305
            ->visit('/page1')
306
            ->fillField('Input 1', 'Kevin')
307
            ->checkField('Input 2')
308
            ->uncheckField('Input 3')
309
            ->selectFieldOption('Input 4', 'option 2')
310
            ->attachFile('Input 5', __FILE__)
311
            ->selectFieldOptions('Input 6', ['option 1', 'option 3'])
312
            ->click('Submit')
313
            ->assertOn('/submit-form')
314
            ->assertContains('"input_1":"Kevin"')
315
            ->assertContains('"input_2":"on"')
316
            ->assertNotContains('"input_3')
317
            ->assertContains('"input_4":"option 2"')
318
            ->assertContains(\sprintf('"input_5":"%s"', \pathinfo(__FILE__, \PATHINFO_BASENAME)))
0 ignored issues
show
Bug introduced by
It seems like pathinfo(__FILE__, PATHINFO_BASENAME) can also be of type array; however, parameter $values of sprintf() does only seem to accept double|integer|string, maybe add an additional type check? ( Ignorable by Annotation )

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

318
            ->assertContains(\sprintf('"input_5":"%s"', /** @scrutinizer ignore-type */ \pathinfo(__FILE__, \PATHINFO_BASENAME)))
Loading history...
319
            ->assertContains('"input_6":["option 1","option 3"]')
320
        ;
321
    }
322
323
    /**
324
     * @test
325
     */
326
    public function form_actions_by_field_id(): void
327
    {
328
        $this->browser()
329
            ->visit('/page1')
330
            ->fillField('input1', 'Kevin')
331
            ->checkField('input2')
332
            ->uncheckField('input3')
333
            ->selectFieldOption('input4', 'option 2')
334
            ->attachFile('input5', __FILE__)
335
            ->selectFieldOptions('input6', ['option 1', 'option 3'])
336
            ->click('Submit')
337
            ->assertOn('/submit-form')
338
            ->assertContains('"input_1":"Kevin"')
339
            ->assertContains('"input_2":"on"')
340
            ->assertNotContains('"input_3')
341
            ->assertContains('"input_4":"option 2"')
342
            ->assertContains(\sprintf('"input_5":"%s"', \pathinfo(__FILE__, \PATHINFO_BASENAME)))
0 ignored issues
show
Bug introduced by
It seems like pathinfo(__FILE__, PATHINFO_BASENAME) can also be of type array; however, parameter $values of sprintf() does only seem to accept double|integer|string, maybe add an additional type check? ( Ignorable by Annotation )

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

342
            ->assertContains(\sprintf('"input_5":"%s"', /** @scrutinizer ignore-type */ \pathinfo(__FILE__, \PATHINFO_BASENAME)))
Loading history...
343
            ->assertContains('"input_6":["option 1","option 3"]')
344
        ;
345
    }
346
347
    /**
348
     * @test
349
     */
350
    public function form_actions_by_field_name(): void
351
    {
352
        $this->browser()
353
            ->visit('/page1')
354
            ->fillField('input_1', 'Kevin')
355
            ->checkField('input_2')
356
            ->uncheckField('input_3')
357
            ->selectFieldOption('input_4', 'option 2')
358
            ->attachFile('input_5', __FILE__)
359
            ->selectFieldOptions('input_6[]', ['option 1', 'option 3'])
360
            ->click('Submit')
361
            ->assertOn('/submit-form')
362
            ->assertContains('"input_1":"Kevin"')
363
            ->assertContains('"input_2":"on"')
364
            ->assertNotContains('"input_3')
365
            ->assertContains('"input_4":"option 2"')
366
            ->assertContains(\sprintf('"input_5":"%s"', \pathinfo(__FILE__, \PATHINFO_BASENAME)))
0 ignored issues
show
Bug introduced by
It seems like pathinfo(__FILE__, PATHINFO_BASENAME) can also be of type array; however, parameter $values of sprintf() does only seem to accept double|integer|string, maybe add an additional type check? ( Ignorable by Annotation )

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

366
            ->assertContains(\sprintf('"input_5":"%s"', /** @scrutinizer ignore-type */ \pathinfo(__FILE__, \PATHINFO_BASENAME)))
Loading history...
367
            ->assertContains('"input_6":["option 1","option 3"]')
368
        ;
369
    }
370
371
    /**
372
     * @test
373
     */
374
    public function can_dump_html_element(): void
375
    {
376
        $output = self::catchVarDumperOutput(function() {
377
            $this->browser()
378
                ->visit('/page1')
379
                ->dump('p#link')
380
            ;
381
        });
382
383
        $this->assertCount(1, $output);
0 ignored issues
show
Bug introduced by
The method assertCount() does not exist on Zenstruck\Browser\Tests\BrowserTests. Did you maybe mean assert_on()? ( Ignorable by Annotation )

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

383
        $this->/** @scrutinizer ignore-call */ 
384
               assertCount(1, $output);

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...
384
        $this->assertSame('<a href="/page2">a link</a> not a link', $output[0]);
385
    }
386
387
    /**
388
     * @test
389
     */
390
    public function if_dump_selector_matches_multiple_elements_all_are_dumped(): void
391
    {
392
        $output = self::catchVarDumperOutput(function() {
393
            $this->browser()
394
                ->visit('/page1')
395
                ->dump('li')
396
            ;
397
        });
398
399
        $this->assertCount(2, $output);
400
        $this->assertSame('list 1', $output[0]);
401
        $this->assertSame('list 2', $output[1]);
402
    }
403
404
    /**
405
     * @test
406
     */
407
    public function can_access_cookies(): void
408
    {
409
        $cookies = $this->browser()->visit('/page1')->cookies();
410
411
        $this->assertIsArray($cookies->all());
0 ignored issues
show
Bug introduced by
It seems like assertIsArray() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

411
        $this->/** @scrutinizer ignore-call */ 
412
               assertIsArray($cookies->all());
Loading history...
412
    }
413
414
    protected static function catchFileContents(string $expectedFile, callable $callback): string
415
    {
416
        (new Filesystem())->remove($expectedFile);
417
418
        $callback();
419
420
        self::assertFileExists($expectedFile);
421
422
        return \file_get_contents($expectedFile);
423
    }
424
425
    protected static function catchVarDumperOutput(callable $callback): array
426
    {
427
        $output[] = null;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$output was never initialized. Although not strictly required by PHP, it is generally a good practice to add $output = array(); before regardless.
Loading history...
428
429
        VarDumper::setHandler(function($var) use (&$output) {
430
            $output[] = $var;
431
        });
432
433
        $callback();
434
435
        // reset to default handler
436
        VarDumper::setHandler();
437
438
        // a null value is added to the beginning
439
        return \array_values(\array_filter($output));
440
    }
441
442
    abstract protected function browser(): Browser;
443
}
444