Compare commits

..

301 Commits

Author SHA1 Message Date
58cff003d8 release: v1.19.0 2021-09-20 19:30:58 +01:00
ae997e6eee No need for --ignore-platform-req=php 2021-09-20 19:28:43 +01:00
e6c7d68def Adds php-81 support 2021-09-20 19:26:47 +01:00
2f0cd7a4e3 Adds Fathom Analytics as sponsor 2021-09-15 10:03:05 +01:00
447af55e7c Merge pull request #391 from gabbanaesteban/master
Add `toHaveProperties`
2021-09-03 09:52:39 +01:00
253e9d10c8 Fix types 2021-09-03 04:44:10 -04:00
536ce1eca0 Update snapshots 2021-09-03 04:40:48 -04:00
4331b2aaf6 Add toHaveProperties 2021-09-03 04:26:57 -04:00
8d99cacc95 Update README.md 2021-09-02 23:36:02 +01:00
3c38facc8a Update README.md 2021-09-02 23:35:51 +01:00
ed389d35d0 Adds Auth0 as sponsor 2021-09-02 23:35:40 +01:00
60c0636523 release: v1.18.0 2021-08-30 00:05:26 +01:00
16b6f96b47 Merge pull request #389 from dansysanalyst/toHaveLength-mblen
Use mb_strlen instead of grapheme_strlen
2021-08-29 12:18:38 +01:00
042f2ec3f3 Use mb_strlen instead of grapheme_strlen
Due to inconsistent behave, mb_strlen will be used.
2021-08-29 12:55:37 +02:00
851ce36010 Merge pull request #386 from dansysanalyst/expectation-toHaveLength
Adds toHaveLength() Expectation & Tests
2021-08-29 00:45:39 +01:00
4f386894bd Revert "Use toHaveCount"
This reverts commit 2289adade2.
2021-08-28 18:14:55 +02:00
2289adade2 Use toHaveCount
changes to toHaveCount
2021-08-28 17:54:29 +02:00
29e21e3814 Merge pull request #385 from dansysanalyst/snapshot-contrib
Update snapshots
2021-08-28 16:47:25 +01:00
8367af22e7 Adds toHaveLength() Expectation & Tests
Adds toHaveLength() Expectation and its tests. toHaveLength checks if the given value has the informed length. Works with strings, array, object and collections.
2021-08-28 17:02:09 +02:00
e3d678dc04 Update snapshots
Adds update:snapshots to CONTRIBUTING
2021-08-28 16:30:17 +02:00
4ae482c707 feat: adds support for nunomaduro/collision:^6.0 2021-08-27 22:32:18 +01:00
075c31bc78 release: v1.17.0 2021-08-26 21:17:03 +01:00
2125bf9668 chore: adjusts tests 2021-08-26 21:14:56 +01:00
dbf3c0a8cf Merge pull request #361 from kbond/throw-expectation
Add `toThrow` expectation
2021-08-26 21:02:38 +01:00
eca5f89e59 release: v1.16.0 2021-08-19 17:07:45 +01:00
0b0beac122 Script update 2021-08-16 22:12:13 +01:00
578e97123d Changes -P to -p 2021-08-13 22:09:55 +01:00
01d672d563 Merge pull request #369 from pestphp/parallel
Parallel testing support
2021-08-13 16:00:26 +01:00
490b2d66e5 Fix 2021-08-13 13:41:00 +01:00
0368c4846f Adds a composer test:parallel script 2021-08-13 13:40:07 +01:00
4dfc02c5da Refactor 2021-08-13 11:19:03 +01:00
5c84b0c6d3 The getFilenames method now respects only calls. 2021-08-13 11:07:52 +01:00
b6c06e8c30 Bugfix 2021-08-13 10:46:07 +01:00
c6435d5606 Adds a helpful message for users trying to run parallel without the plugin 2021-08-13 10:44:11 +01:00
2887d212e3 CS fix 2021-08-13 10:30:26 +01:00
cadae52d5d Updates snapshots 2021-08-13 10:29:21 +01:00
d9749ca65b Adds a method for getting all filenames 2021-08-13 10:26:38 +01:00
c2070cd99d Refactor 2021-08-13 10:19:10 +01:00
03d34e9a10 Removes isInParallel 2021-08-13 10:14:01 +01:00
45e76a6df6 Typehint updates 2021-08-13 09:41:45 +01:00
28dd3c2a03 Adds -P as a parallel shortcut 2021-08-13 09:39:56 +01:00
5de981d923 Updates composer.json 2021-08-13 09:12:56 +01:00
a55b31e7c3 Update FUNDING.yml 2021-08-12 21:41:42 +01:00
5f0bd8180e Update FUNDING.yml 2021-08-12 21:41:05 +01:00
e1f1fcccbe Removes unneeded dependency 2021-08-11 21:25:41 +01:00
ab04aef561 Refactors addOutput 2021-08-11 20:59:19 +01:00
79ddb1f58e Composer change 2021-08-11 15:57:49 +01:00
c7a2e68941 Fixes a problem with the PhpUnit logger 2021-08-10 14:57:36 +01:00
5c592928d4 Adds a new method, isInParallel, to the Testable trait to allow a test to determine its parallel status. 2021-08-10 14:34:10 +01:00
bcab4224fb Skips a test that doesn't support parallel. 2021-08-10 14:24:34 +01:00
892f70b5b5 Refactor 2021-08-10 13:17:11 +01:00
5c7de5ad75 Refactor 2021-08-10 12:04:15 +01:00
995088b522 Refactor 2021-08-10 11:32:43 +01:00
ef503646ee Removes parallel classes. 2021-08-10 11:30:48 +01:00
a760470e48 Adds Pest output to parallel. 2021-08-09 18:57:20 +01:00
31d1b1b91d Adds a little more spacing above the coverage output. 2021-08-06 15:15:09 +01:00
7524c80af6 Merge pull request #370 from nuernbergerA/parallel
Parallel additions
2021-08-06 15:04:51 +01:00
721d5134b7 replace str_starts_with to support pre php 8.0 2021-08-06 16:00:03 +02:00
0b5321fdd7 only check for coverage driver if option is present 2021-08-06 15:48:38 +02:00
c86058fed1 use support class 2021-08-06 15:39:19 +02:00
8b295b5e9d remove debug statements 2021-08-06 15:38:59 +02:00
221248e691 introduced argument mapping, added pest coverage 2021-08-06 15:25:28 +02:00
7621247bb7 Adds workflows for parallel 2021-08-05 17:45:50 +01:00
463a50ebd4 Investigating bug fix 2021-08-05 17:39:23 +01:00
62aabc6ae1 Bugfix. The TestCase is now aware of if it is running in parallel or not 😎 2021-08-05 17:09:45 +01:00
1ca9aa5ca6 Further cleanup 2021-08-05 16:43:09 +01:00
7a76f8dce2 Further cleanup 2021-08-05 16:21:06 +01:00
beca27599c Further cleanup 2021-08-05 16:18:47 +01:00
256b167eaf Improvements 2021-08-05 15:31:09 +01:00
5526d4c24d Cleanup 2021-08-05 13:51:55 +01:00
7ea138c640 CS fixes 2021-08-05 13:41:04 +01:00
c4a659c3b5 Composer changes 2021-08-05 13:16:29 +01:00
0a3991c314 Initial working draft 2021-08-05 13:13:53 +01:00
d1a9e0bbe3 release: v1.15.0 2021-08-04 23:02:18 +01:00
17eacfdf95 Update RELEASE.md 2021-08-04 23:01:40 +01:00
9ec0762d41 tests: refactors toBeTruthy and toBeFalsy 2021-08-04 22:56:18 +01:00
30f39f1850 Merge pull request #367 from gabbanaesteban/add-to-be-falsy-and-to-be-truthy
Add `toBeTruthy` and `ToBeFalsy`
2021-08-04 22:45:39 +01:00
8ee07330b3 Add toBeFalsy 2021-08-03 20:55:07 -04:00
cffde4564d Add toBeTruthy 2021-08-03 20:54:56 -04:00
ce7a7649a2 chore: removes scripts folder 2021-08-03 18:59:36 +01:00
eeed7e6a0a chore: removes scripts folder 2021-08-03 18:57:41 +01:00
d6844f5239 Delete compile.php 2021-08-03 18:55:53 +01:00
06c4019e81 cs: removes comment 2021-08-03 18:22:15 +01:00
7785a8cc58 chore: reverts changes regarding PHP 8.1 2021-08-03 18:00:42 +01:00
663516c1e3 Merge pull request #366 from jeroenvanrensen/patch-1
Fix typography
2021-08-03 14:32:50 +01:00
e83667a20b docs: update changelog 2021-08-03 14:01:53 +01:00
aa96d75fb9 Merge pull request #364 from pestphp/bound-datasets
Datasets can now access the test case
2021-08-03 13:58:35 +01:00
a5af4bc5ed Fix typography 2021-08-03 15:04:03 +03:00
57161ba5ad Merges master 2021-08-02 14:03:33 +01:00
b1a9254fc1 Merge branch 'master' into bound-datasets
# Conflicts:
#	tests/.snapshots/success.txt
2021-08-02 14:02:49 +01:00
e56e818659 Splits 8.1 OS jobs 2021-08-02 13:06:41 +01:00
79de0d5875 Splits 8.1 OS jobs 2021-08-02 13:05:55 +01:00
f6f8140ebc Splits 8.1 OS jobs 2021-08-02 13:05:29 +01:00
eed221af46 Adds continue-on-error for php 8.1 2021-08-02 13:03:13 +01:00
524457a4e6 Adds continue-on-error for php 8.1 2021-08-02 13:00:07 +01:00
8e289b7a7d Adds continue-on-error for php 8.1 2021-08-02 12:59:07 +01:00
172b69cf15 Adds continue-on-error for php 8.1 2021-08-02 12:57:57 +01:00
475279a4fa Adds continue-on-error for php 8.1 2021-08-02 12:56:29 +01:00
4b236bf9ff docs: update changelog 2021-08-02 12:50:44 +01:00
50e2d10029 docs: update changelog 2021-08-02 12:50:28 +01:00
fa8a57f1ab Merge pull request #350 from pestphp/teamcity-styling
Teamcity styling
2021-08-02 12:47:54 +01:00
715f8b420b Updates phpunit dependency version 2021-08-02 12:41:23 +01:00
c776bcf86d add toThrow expectation 2021-08-01 12:33:09 -04:00
a0637d86ff Refactors 2021-08-01 17:00:01 +01:00
1a941d7f92 Refactors 2021-08-01 16:45:06 +01:00
b5959aa3fa Refactors 2021-08-01 15:42:52 +01:00
8861dd2401 Merges with master 2021-08-01 15:40:34 +01:00
da73f4b395 Merge branch 'master' into teamcity-styling
# Conflicts:
#	tests/.snapshots/success.txt
2021-08-01 15:36:53 +01:00
d5097d0fe5 Merge conflicts 2021-07-31 23:28:23 +01:00
022ad4be0d Merge branch 'master' into bound-datasets
# Conflicts:
#	tests/.snapshots/success.txt
2021-07-31 23:27:38 +01:00
2d2a83e9e8 chore: run tests against php 8.1 2021-07-31 22:56:33 +01:00
67c7bee4fa Merge pull request #365 from def-studio/expect-toContain-with-multiple-needles
implements multiple needles in expect()->toContain()
2021-07-31 20:34:33 +01:00
675b0f1ec8 implements multiple needles in expect()->toContain() 2021-07-31 18:29:03 +02:00
c2b86c3ab3 Removes pest from stack traces 2021-07-30 16:34:30 +01:00
46337b8085 Removes pest from stack traces 2021-07-30 16:32:00 +01:00
df172d8eed Adds new lines 2021-07-30 15:36:38 +01:00
24b9160b79 Removes new line from event printing 2021-07-30 15:34:31 +01:00
a7860b0b8e CS 2021-07-30 12:41:57 +01:00
7471c224fa Output improvements. 2021-07-30 12:39:20 +01:00
2996135155 Output improvements. 2021-07-30 12:38:13 +01:00
1abab8d440 Output improvements. 2021-07-30 12:36:52 +01:00
e52c83e5be Output improvements. 2021-07-30 12:35:20 +01:00
5ed4545737 Output improvements. 2021-07-30 12:34:10 +01:00
8b39df68ce Output improvements. 2021-07-30 12:32:27 +01:00
04d8a3762b Output improvements. 2021-07-30 12:31:03 +01:00
0f7c8d00d6 Output improvements. 2021-07-30 12:29:39 +01:00
12fb4f8639 Output improvements. 2021-07-30 12:24:23 +01:00
6a84b825e6 Output improvements. 2021-07-30 12:23:24 +01:00
e8595c56b3 Merge branch 'master' into teamcity-styling 2021-07-30 11:46:57 +01:00
4a9fb2fa74 Snapshot update 2021-07-28 10:41:47 +01:00
d8fae6d689 Datasets can now access the test case and are executed after the setup method has run. 2021-07-28 10:39:39 +01:00
252f9a0e46 Merge pull request #321 from jordanbrauer/fix-missing-dataset-errors
Add user-friendly exception message for missing test inputs
2021-07-28 09:57:39 +01:00
8d24b4a217 chore: replace prop set/check with method call 2021-07-27 23:39:26 -05:00
43920f79a9 feat: add count method for checking message type presence 2021-07-27 23:36:09 -05:00
55bfc5856b Merge branch 'master' into fix-missing-dataset-errors 2021-07-27 23:02:12 -05:00
cd9d4acbc2 release: v1.13.0 2021-07-28 02:03:24 +01:00
2b5355419a chore: fixes types 2021-07-28 01:59:47 +01:00
22b822ce87 fix: skip with a false condition being ignored 2021-07-28 01:57:13 +01:00
b2c298b926 Merge pull request #363 from freekmurze/add-to-be-in
Add `toBeIn` expectation
2021-07-28 00:09:54 +01:00
671f3df115 fix tests 2021-07-28 01:00:19 +02:00
2dd77001b7 static analysis fix 2021-07-28 00:42:54 +02:00
5f574ded81 add toBeIn 2021-07-28 00:36:43 +02:00
6309e6818d Update README.md 2021-07-26 23:19:51 +01:00
4813ab6ffb Add sponsor 2021-07-26 23:18:55 +01:00
4ebba1298a release: v1.12.0 2021-07-26 22:46:22 +01:00
2e0d1bb5a0 Merge branch 'master' of https://github.com/pestphp/pest 2021-07-26 22:45:08 +01:00
09d2b16767 docs: updates changelog 2021-07-26 22:45:03 +01:00
f56556eb73 Merge pull request #357 from jordanbrauer/fix-static-hooks
Fix static hooks
2021-07-26 22:33:58 +01:00
f387ca8624 Merge pull request #353 from rezaamini-ir/master
Add --force flag to pest:test command
2021-07-26 22:27:08 +01:00
ca9d783cf9 chore: makes phpunit/phpunit requirement above ^9.3.7 2021-07-26 22:02:57 +01:00
863ddea50b style: split assignment into two lines clarity 2021-07-22 17:54:22 -05:00
00b4bb6305 Merge branch 'master' into fix-missing-dataset-errors 2021-07-21 21:26:33 -05:00
d217503a6a test: use consistent test descriptors 2021-07-21 20:47:48 -05:00
b6012862c4 style: run linter 2021-07-21 20:43:21 -05:00
60c0ad006f fix: prevent the global hooks from piling up (#351)
this happens due to the global `*All()` hooks (before & after) being
defined as static. We should be a good citizen and we need to clean up
our mess for the next person in the test instance constructor
2021-07-21 20:38:20 -05:00
79ff332afe test: global "all" hooks must only run once (#351)
in other words, they can only run once per file
2021-07-21 20:32:39 -05:00
595bbe32a4 Add bool to the condition 2021-07-22 01:41:12 +04:30
328427bfdb docs: update changelog 2021-07-21 12:59:45 +01:00
51f556799c Merge pull request #352 from pestphp/higher-order-callable-datasets
Higher order callable datasets
2021-07-21 12:04:35 +01:00
5e0a0855ea Add a better description 2021-07-21 14:38:11 +04:30
7ec3460d73 Add --force flag to pest:test command 2021-07-21 13:02:09 +04:30
4c8c42cd20 Refactor 2021-07-21 08:47:55 +01:00
09682dd393 Alters test to prove order doesn't matter 2021-07-21 08:16:54 +01:00
82c18d3848 Type fixes 2021-07-21 07:58:05 +01:00
3bdba9210d Adds another test 2021-07-21 07:44:05 +01:00
371620d161 Adds support for receiving datasets in higher order tests 2021-07-21 07:40:19 +01:00
d10281f851 Adds test cases for loggers and removes use of str_starts_with. 2021-07-19 12:59:18 +01:00
47ceb2419b Update README.md 2021-07-16 22:12:31 +01:00
771b5b2e53 Adds Spatie 2021-07-16 22:12:19 +01:00
05f72f9b6d Aligns test case name with test names 2021-07-16 17:59:07 +01:00
f9de1b9c00 Refactor 2021-07-16 17:51:12 +01:00
9516e56242 Improves test case name styling 2021-07-16 17:50:18 +01:00
5f315fc899 Updates warning color 2021-07-16 17:46:30 +01:00
e59606818d More work on output 2021-07-16 17:26:48 +01:00
e16104350e More work on output 2021-07-16 16:45:35 +01:00
df31191f4e Merge branch 'master' into teamcity-assertion-fix 2021-07-16 16:45:16 +01:00
5b310f6f93 More work on output 2021-07-16 15:58:44 +01:00
0200f90e9a Start of work on better TeamCity output 2021-07-16 15:06:10 +01:00
027e69e48f Merge pull request #349 from pestphp/teamcity-assertion-fix
Fixes the assertion output showing as 0 in the TeamCity logger
2021-07-16 14:58:30 +01:00
33e01e3805 Merge pull request #348 from jdanino/stubfix
Fix the unit test stub
2021-07-16 14:26:01 +01:00
13781dcd14 Fixes the assertion output showing as 0 in the TeamCity logger. 2021-07-16 13:17:33 +01:00
164bad437a Fixes the assertion output showing as 0 in the TeamCity logger. 2021-07-16 13:10:30 +01:00
7ddcc03ad9 Update stubs/Unit.php
Co-authored-by: Owen Voke <development@voke.dev>
2021-07-16 13:00:32 +01:00
bbe4445257 Fix the unit test stub 2021-07-16 12:40:57 +02:00
d90ddf889c docs: update changelog 2021-07-12 11:54:40 +01:00
5907164749 Merge pull request #341 from pestphp/hot-hoe
Adds support for Higher Order Expectations in Higher Order Tests
2021-07-12 11:52:04 +01:00
eb6de433b7 docs: update changelog 2021-07-11 09:08:31 +01:00
32f72cdf55 Merge pull request #344 from pestphp/callable-expect-fix
Forces higher order test callable expects to be closures
2021-07-11 09:04:59 +01:00
c160d97428 Forces higher order test callable expects to be closures. 2021-07-11 07:56:02 +01:00
2a8de0565f Adds support for Higher Order Expectations in Higher Order Tests 2021-07-09 16:50:15 +01:00
5ab3c6e2d7 Merge pull request #340 from pestphp/better-tap-type-hinting
Better tap type hinting
2021-07-09 16:34:18 +01:00
50ece576a7 Improves type-hinting for target in HigherOrderTapProxy 2021-07-09 16:09:53 +01:00
9c202fa2d7 Improves type-hinting for tap method 2021-07-09 16:07:37 +01:00
e4e9cb09e4 docs: update changelog 2021-07-09 09:15:22 +01:00
6a7597c01a Merge pull request #339 from pestphp/exception-improvements
Allows you to just specify an exception message when calling `throws`.
2021-07-09 09:08:05 +01:00
dd05452edd Renames a property to be more inclusive. 2021-07-08 18:39:09 +01:00
99ea9f42e5 Allows you to just specify an exception message when calling throws. 2021-07-08 18:32:02 +01:00
7d6a86adc7 docs: update changelog 2021-07-08 18:11:02 +01:00
7fbd2661c8 Merge pull request #338 from pestphp/skip-closure-support
Closures passed to the `skip` method are now bound to the test case
2021-07-08 18:05:27 +01:00
6ce678d1c2 Adds an extra test to ensure that skipping takes place before higher order callables. 2021-07-08 17:52:56 +01:00
5049b996db Merge branch 'master' into skip-closure-support
# Conflicts:
#	src/Support/HigherOrderMessage.php
2021-07-08 17:50:48 +01:00
d838456caa Merge pull request #331 from pestphp/higher-order-tap-and-defer
Adds a new `tap` method to Higher Order tests
2021-07-08 17:38:17 +01:00
e45c4ff4f1 Refactors HigherOrderMessage 2021-07-08 17:30:39 +01:00
fa3959db17 Type hints for callable 2021-07-08 13:12:30 +01:00
b97e206f7a Closures passed to the skip method are now bound to the test case to allow for more complex logic. 2021-07-08 09:44:28 +01:00
7e9edecc7f Higher Order Tests now resolve callable expectations. The tap method now always returns the test case. 2021-07-06 14:05:40 +01:00
dc75b34deb refactor: move logic into boolean method in TestCaseFactory 2021-06-30 09:51:49 -05:00
8e22803797 Merge branch 'master' into fix-missing-dataset-errors 2021-06-30 09:04:20 -05:00
c290909eb3 Adds @mixin for HigherOrderCallables class 2021-06-25 09:24:16 +01:00
f2e56da2da Updates snapshots 2021-06-24 22:58:29 +01:00
e6b258534a Merge branch 'master' into higher-order-tap-and-defer
# Conflicts:
#	tests/.snapshots/success.txt
2021-06-24 22:57:48 +01:00
acef002a2d Adds tap for Higher Order tests 2021-06-24 22:57:26 +01:00
11ebe014fb docs: update changelog 2021-06-24 21:44:57 +01:00
2d13c6e219 Merge pull request #330 from pestphp/higher-order-expectation-and
Allows `and` in Higher Order Expectations.
2021-06-24 21:42:22 +01:00
fbcb492c79 Simplification 2021-06-24 21:40:24 +01:00
4f67eff619 Start of work 2021-06-24 21:38:02 +01:00
3c2c767e09 Updates snapshot 2021-06-24 21:35:16 +01:00
ff527baa1d Allows and in Higher Order Expectations. 2021-06-24 21:31:12 +01:00
621718d4b1 Merge pull request #329 from bigint/master
Update phpunit/phpunit to 9.5.6
2021-06-23 10:28:49 +01:00
59adc57344 Update phpunit/phpunit to 9.5.6 2021-06-23 14:55:09 +05:30
82bd836ae9 Merge branch 'master' into fix-missing-dataset-errors 2021-06-21 19:50:15 -05:00
1680613e12 docs: update changelog 2021-06-19 14:42:29 +01:00
f6d3ce41bc chore: updates funding 2021-06-18 22:17:44 +01:00
d16a48bf0f chore: cs 2021-06-18 22:16:54 +01:00
9459ce4030 Merge pull request #324 from pestphp/nested-higher-order-expectations
Adds Nested Higher Order Expectations
2021-06-18 22:12:17 +01:00
c773d1cd57 chore: type checks scripts folder 2021-06-18 22:09:56 +01:00
22a1aac84a Fixes types 2021-06-18 22:08:47 +01:00
3a20696da4 CS 2021-06-18 22:03:51 +01:00
99bcf98617 Rebuilds snapshots 2021-06-18 22:03:01 +01:00
09d9bae988 Merge branch 'master' into nested-higher-order-expectations
# Conflicts:
#	tests/.snapshots/success.txt
2021-06-18 22:01:30 +01:00
27de6106ab Adds type hinting 2021-06-18 22:01:16 +01:00
aeded0a356 refacto: coding style updates 2021-06-18 22:01:14 +01:00
afef1d56e8 Merge pull request #323 from pestphp/non-callable-sequence
Sequenced expectations can now be passed as non-callable values
2021-06-18 21:53:04 +01:00
4b55de27f1 Adds generics 2021-06-18 21:52:24 +01:00
3d7b6426a1 Updates snapshots 2021-06-18 21:49:38 +01:00
1d415eb7fb Merge branch 'master' into nested-higher-order-expectations
# Conflicts:
#	tests/.snapshots/success.txt
2021-06-18 21:49:05 +01:00
8a384a6d65 Merge fixes 2021-06-18 21:46:57 +01:00
7c4dd2f2e7 Merge branch 'master' into non-callable-sequence
# Conflicts:
#	tests/.snapshots/success.txt
2021-06-18 21:45:02 +01:00
b6f0496c3c chore: updates funding 2021-06-18 12:39:05 +01:00
9b34650e72 Adds changelog for 1.6.0 2021-06-18 12:36:43 +01:00
db9f1254b5 Tags Pest 1.6 2021-06-18 12:30:57 +01:00
b0e2ce6896 Merge pull request #325 from dansysanalyst/feat/json
Method json() to parse JSON strings
2021-06-18 12:28:45 +01:00
3afdedbd3f Snapshots 2021-06-18 13:11:37 +02:00
4bf69b97bd feat(json): updates docs 2021-06-18 12:06:41 +01:00
ecb37fce91 Refactoring to use toBeJson()
Refactoring according to @lukeraymonddowning suggestion
2021-06-18 13:04:31 +02:00
c1b27579ca Method json() to parse JSON strings
- Parse a JSON string into array
- Test
2021-06-18 12:43:17 +02:00
e64856c664 test: use throws method instead of assert 2021-06-17 13:33:11 -05:00
de86598c0d Merge branch 'master' into fix-missing-dataset-errors 2021-06-16 21:36:42 -05:00
553b45306f feat: handle unions (PHP 8) 2021-06-16 21:29:08 -05:00
d96a2485b6 Updates snapshot 2021-06-17 00:18:12 +01:00
9e9d1cc8cc Merge branch 'master' into nested-higher-order-expectations
# Conflicts:
#	src/Expectation.php
#	tests/.snapshots/success.txt
2021-06-17 00:17:25 +01:00
579bb1b90c Updates DocBlock type hinting 2021-06-17 00:15:42 +01:00
5116b4341e Merge pull request #322 from pestphp/to-have-key
Reimplements the new `toHaveArray` features.
2021-06-16 23:12:43 +01:00
7ff64540a6 Adds nested Higher Order Expectations. 2021-06-16 20:48:23 +01:00
2e7192ab95 chore: static analysis adjustments - deprecation RE: ReflectionType::__toString 2021-06-16 14:42:51 -05:00
241d4cf94c Reimplements non-callable sequence values. 2021-06-16 20:34:17 +01:00
a5ce2dc1a1 Reimplements the new toHaveArray features. 2021-06-16 20:27:36 +01:00
e21e3080e0 test: add new exception check & update snapshots 2021-06-16 14:04:50 -05:00
6a7ee90ff5 feat: throw user-friendly exception for missing argument data 2021-06-16 01:01:34 -05:00
9d66893d5a feat: add boolean property to signal dependency proxy calls 2021-06-16 01:00:23 -05:00
64e780cf72 fix: types 2021-06-16 00:58:46 -05:00
9bf141f698 style: formatting & linting 2021-06-16 00:54:22 -05:00
9904094590 feat: add new exception for missing datasets on tests with arguments 2021-06-16 00:53:17 -05:00
9e5b779abc feat: add helper function for mapping a function's arguments 2021-06-16 00:52:31 -05:00
729638a3bb release: v1.5.0 2021-06-15 23:06:43 +01:00
82768382da chore: bumps dependencies 2021-06-15 23:06:22 +01:00
3cb52447bb chore: adjusts type checker 2021-06-15 23:06:06 +01:00
8d670b4ed7 refactor: renames traits 2021-06-15 23:05:57 +01:00
624f6e0acc Merge pull request #320 from owenvoke/feature/expectations
feat: move Expectations API out of external plugin
2021-06-15 22:38:44 +01:00
c07cd8c252 feat: move Expectations API out of external plugin 2021-06-15 17:10:21 +01:00
a10b29a8da Merge pull request #318 from owenvoke/feature/coverage
feat: move Coverage out of external plugin
2021-06-15 14:34:49 +01:00
ea696f819e feat: move Coverage out of external plugin 2021-06-15 14:26:57 +01:00
e9b564a50c Merge pull request #317 from owenvoke/feature/init
feat: move init command out of external plugin
2021-06-15 13:17:59 +01:00
fa16775ee2 fix: allow copying the phpunit.xml 2021-06-15 09:37:58 +01:00
55449c956a feat: move init command out of external plugin 2021-06-15 09:29:33 +01:00
e4b4e55dcd Merge pull request #314 from ordago/typos
fixes typos
2021-06-13 14:35:48 +01:00
1c57de7e36 fixes typos 2021-06-13 11:45:18 +01:00
dd2921fd26 tests: fixes snapshots 2021-06-10 19:26:42 +01:00
977dbb5bcb docs: updates changelog 2021-06-10 19:21:02 +01:00
49de462250 Adds support for incompleted tests 2021-06-10 19:20:16 +01:00
95e8add29b Merge pull request #303 from def-studio/matrix-datasets
Matrix datasets
2021-06-10 18:43:31 +01:00
b682fe631d chore: bumps expectation plugin 2021-06-10 18:40:38 +01:00
d32a648af5 updated test snapshots after merge from master 2021-06-10 09:03:32 +02:00
50e9978dc3 Merge branch 'master' into matrix-datasets
# Conflicts:
#	tests/.snapshots/success.txt
2021-06-10 09:01:09 +02:00
17d407a26a Updates changelog 2021-06-07 15:27:33 +01:00
cdc3bd3f45 Merge pull request #308 from titouanmathis/fix/test-key-separator
Fix/test key separator
2021-06-07 15:22:05 +01:00
95b4192c0d Fix visual success test 2021-06-07 10:40:11 +02:00
4c911cd0eb docs: update changelog 2021-06-07 08:59:27 +01:00
7408999b0e Merge branch 'master' into matrix-datasets 2021-06-06 23:59:54 +02:00
574cd11a40 Add tests 2021-06-04 02:08:12 +02:00
c04d6d946d Fix a bug where plugins could not be used in a path containing an @
Fix #307
2021-06-03 14:15:20 +02:00
36c2a985a6 Merge branch 'pestphp:master' into matrix-datasets 2021-06-03 12:19:15 +02:00
ea0be9e7a4 Refactored Datasets::resolve() to make it more readable 2021-05-27 08:46:38 +02:00
838ac273ab writed tests with multiple datasets
Took 1 hour 6 minutes
2021-05-25 23:56:46 +02:00
296e1c37e8 updates snapshots
Took 7 minutes
2021-05-24 23:43:53 +02:00
3117f11fae phpstan fixes
Took 3 minutes
2021-05-24 23:36:51 +02:00
294c41f0dc lint fixes
Took 3 minutes
2021-05-24 23:33:43 +02:00
60afbb2c20 adds new test to check dataset matrix generation
Took 39 seconds
2021-05-24 23:30:50 +02:00
19a45c856e updates Dataset::resolve to generate a matrix of values from multiple datasets
Took 42 seconds
2021-05-24 23:30:11 +02:00
3b784060b8 updated TestCaseFactory.php to store multiple datasets
Took 44 seconds
2021-05-24 23:29:29 +02:00
dd5a11a61f updated TestCall.php to store multiple datasets
Took 1 hour 59 minutes
2021-05-24 23:28:46 +02:00
132 changed files with 5348 additions and 330 deletions

2
.gitattributes vendored
View File

@ -8,7 +8,7 @@
.gitattributes export-ignore
.gitignore export-ignore
phpstan.neon export-ignore
phpunit.xml export-ignore
/phpunit.xml export-ignore
CHANGELOG.md export-ignore
CONTRIBUTING.md export-ignore
README.md export-ignore

3
.github/FUNDING.yml vendored
View File

@ -1,5 +1,4 @@
# These are supported funding model platforms
github: [nunomaduro,owenvoke,olivernybroe,octoper]
github: [nunomaduro,owenvoke,olivernybroe,octoper,lukeraymonddowning]
patreon: nunomaduro
custom: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=66BYDWAT92N6L

View File

@ -8,10 +8,11 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
php: ['7.3', '7.4', '8.0']
php: ['7.3', '7.4', '8.0', '8.1']
dependency-version: [prefer-lowest, prefer-stable]
parallel: ['', '--parallel']
name: PHP ${{ matrix.php }} - ${{ matrix.os }} - ${{ matrix.dependency-version }}
name: PHP ${{ matrix.php }} - ${{ matrix.os }} - ${{ matrix.dependency-version }} - ${{ matrix.parallel }}
steps:
- name: Checkout
@ -29,16 +30,11 @@ jobs:
echo "::add-matcher::${{ runner.tool_cache }}/php.json"
echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
- name: Install PHP 7 dependencies
- name: Install PHP dependencies
run: composer update --${{ matrix.dependency-version }} --no-interaction --no-progress
if: "matrix.php < 8"
- name: Install PHP 8 dependencies
run: composer update --${{ matrix.dependency-version }} --ignore-platform-req=php --no-interaction --no-progress
if: "matrix.php >= 8"
- name: Unit Tests
run: php bin/pest --colors=always --exclude-group=integration
run: php bin/pest --colors=always --exclude-group=integration ${{ matrix.parallel }}
- name: Integration Tests
run: php bin/pest --colors=always --group=integration

View File

@ -3,7 +3,6 @@
$finder = PhpCsFixer\Finder::create()
->in(__DIR__ . DIRECTORY_SEPARATOR . 'tests')
->in(__DIR__ . DIRECTORY_SEPARATOR . 'bin')
->in(__DIR__ . DIRECTORY_SEPARATOR . 'scripts')
->in(__DIR__ . DIRECTORY_SEPARATOR . 'stubs')
->in(__DIR__ . DIRECTORY_SEPARATOR . 'src')
->append(['.php-cs-fixer.dist.php']);

View File

@ -4,10 +4,108 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).
## [v1.19.0 (2021-09-20)](https://github.com/pestphp/pest/compare/v1.18.0...v1.19.0)
### Added
- PHP 8.1 support ([e6c7d68](https://github.com/pestphp/pest/commit/e6c7d68defaec8efe01e71e15dd8d8c45b0cf60f))
## [v1.18.0 (2021-08-30)](https://github.com/pestphp/pest/compare/v1.17.0...v1.18.0)
### Added
- `toHaveLength` expectation ([#386](https://github.com/pestphp/pest/pull/386))
- `nunomaduro/collision:^6.0` support ([4ae482c](https://github.com/pestphp/pest/commit/4ae482c7073fb77782b8a4b5738ef1fcea0f82ab))
## [v1.17.0 (2021-08-26)](https://github.com/pestphp/pest/compare/v1.16.0...v1.17.0)
### Added
- `toThrow` expectation ([#361](https://github.com/pestphp/pest/pull/361))
## [v1.16.0 (2021-08-19)](https://github.com/pestphp/pest/compare/v1.15.0...v1.16.0)
### Added
- Support for new parallel options ([#369](https://github.com/pestphp/pest/pull/369))
## [v1.15.0 (2021-08-04)](https://github.com/pestphp/pest/compare/v1.14.0...v1.15.0)
### Added
- `toBeTruthy` and `toBeFalsy` ([#367](https://github.com/pestphp/pest/pull/367))
## [v1.14.0 (2021-08-03)](https://github.com/pestphp/pest/compare/v1.13.0...v1.14.0)
### Added
- A new bound closure that allows you to access the test case in Datasets ([#364](https://github.com/pestphp/pest/pull/364))
## [v1.13.0 (2021-08-02)](https://github.com/pestphp/pest/compare/v1.12.0...v1.13.0)
### Added
- A cleaner output when running the Pest runner in PhpStorm ([#350](https://github.com/pestphp/pest/pull/350))
- `toBeIn` expectation ([#363](https://github.com/pestphp/pest/pull/363))
### Fixed
- `skip` with false condition marking test as skipped ([22b822c](https://github.com/pestphp/pest/commit/22b822ce87a3d19d84960fa5c93eb286820b525d))
## [v1.12.0 (2021-07-26)](https://github.com/pestphp/pest/compare/v1.11.0...v1.12.0)
### Added
- `--force` option to override tests in `pest:test` artisan command ([#353](https://github.com/pestphp/pest/pull/353))
- Support for PHPUnit `^9.3.7` ([ca9d783](https://github.com/pestphp/pest/commit/ca9d783cf942a2caabc85ff7a728c7f28350c67a))
### Fixed
- `beforeAll` and `afterAll` behind called multiple times per test ([#357](https://github.com/pestphp/pest/pull/357))
## [v1.11.0 (2021-07-21)](https://github.com/pestphp/pest/compare/v1.10.0...v1.11.0)
### Added
- Support for interacting with datasets in higher order tests ([#352](https://github.com/pestphp/pest/pull/352))
### Changed
- The unit test stub now uses the expectation API ([#348](https://github.com/pestphp/pest/pull/348))
### Fixed
- PhpStorm will no longer show 0 assertions in the output ([#349](https://github.com/pestphp/pest/pull/349))
## [v1.10.0 (2021-07-12)](https://github.com/pestphp/pest/compare/v1.9.1...v1.10.0)
### Added
- The ability to use higher order expectations inside higher order tests ([#341](https://github.com/pestphp/pest/pull/341))
## [v1.9.1 (2021-07-11)](https://github.com/pestphp/pest/compare/v1.9.0...v1.9.1)
### Fixed
- Callable `expect` values in higher order tests failing if the value was an existing method name ([#334](https://github.com/pestphp/pest/pull/344))
## [v1.9.0 (2021-07-09)](https://github.com/pestphp/pest/compare/v1.8.0...v1.9.0)
### Changed
- You may now pass just an exception message when using the `throws` method ([#339](https://github.com/pestphp/pest/pull/339))
## [v1.8.0 (2021-07-08)](https://github.com/pestphp/pest/compare/v1.7.1...v1.8.0)
### Added
- A new `tap` and test case aware `expect` methods for higher order tests ([#331](https://github.com/pestphp/pest/pull/331))
- Access to test case methods and properties when using `skip` ([#338](https://github.com/pestphp/pest/pull/338))
## [v1.7.1 (2021-06-24)](https://github.com/pestphp/pest/compare/v1.7.0...v1.7.1)
### Fixed
- The `and` method not being usable in Higher Order expectations ([#330](https://github.com/pestphp/pest/pull/330))
## [v1.7.0 (2021-06-19)](https://github.com/pestphp/pest/compare/v1.6.0...v1.7.0)
### Added
- Support for non-callable values in the sequence method, which will be passed as `toEqual` ([#323](https://github.com/pestphp/pest/pull/323))
- Support for nested Higher Order Expectations ([#324](https://github.com/pestphp/pest/pull/324))
## [v1.6.0 (2021-06-18)](https://github.com/pestphp/pest/compare/v1.5.0...v1.6.0)
### Added
- Adds a new `json` expectation method to improve testing with JSON strings ([#325](https://github.com/pestphp/pest/pull/325))
- Adds dot notation support to the `toHaveKey` and `toHaveKeys` expectations ([#322](https://github.com/pestphp/pest/pull/322))
## [v1.5.0 (2021-06-15)](https://github.com/pestphp/pest/compare/v1.4.0...v1.5.0)
### Changed
- Moves plugins from the `require` section to the core itself ([#317](https://github.com/pestphp/pest/pull/317)), ([#318](https://github.com/pestphp/pest/pull/318)), ([#320](https://github.com/pestphp/pest/pull/320))
## [v1.4.0 (2021-06-10)](https://github.com/pestphp/pest/compare/v1.3.2...v1.4.0)
### Added
- Support for multiple datasets (Matrix) on the `with` method ([#303](https://github.com/pestphp/pest/pull/303))
- Support for incompleted tests ([49de462](https://github.com/pestphp/pest/commit/49de462250cf9f65f09e13eaf6dcc0e06865b930))
## [v1.3.2 (2021-06-07)](https://github.com/pestphp/pest/compare/v1.3.1...v1.3.2)
### Fixed
- Test cases with the @ symbol in the directory fail ([#308](https://github.com/pestphp/pest/pull/308))
## [v1.3.1 (2021-06-06)](https://github.com/pestphp/pest/compare/v1.3.0...v1.3.1)
### Added
- Added for PHPUnit 9.5.5 ([#310](https://github.com/pestphp/pest/pull/310))
### Changed
- Lock minimum Pest plugin versions ([#306](https://github.com/pestphp/pest/pull/306))
## [v1.3.0 (2021-05-23)](https://github.com/pestphp/pest/compare/v1.2.1...v1.3.0)
### Added
- Named datasets no longer show the arguments ([#302](https://github.com/pestphp/pest/pull/302))
@ -155,7 +253,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
### Added
- Expectation API (TODO)
- PHPUnit 9.3 and PHP 8 support ([#128](https://github.com/pestphp/pest/pull/128))
- Fowards `$this` calls to globals ([#169](https://github.com/pestphp/pest/pull/169))
- Forwards `$this` calls to globals ([#169](https://github.com/pestphp/pest/pull/169))
### Fixed
- don't decorate output if --colors=never is set ([36b879f](https://github.com/pestphp/pest/commit/36b879f97d7b187c87a94eb60af5b7d3b7253d56))
@ -170,7 +268,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- `depends` phpunit feature ([#103](https://github.com/pestphp/pest/pull/103))
### Fixes
- datasets name conflit ([#101](https://github.com/pestphp/pest/pull/101))
- datasets name conflict ([#101](https://github.com/pestphp/pest/pull/101))
## [v0.2.1 (2020-06-17)](https://github.com/pestphp/pest/compare/v0.2.0...v0.2.1)
### Fixes

View File

@ -31,6 +31,10 @@ composer lint
```
## Tests
Update the snapshots:
```bash
composer update:snapshots
```
Run all tests:
```bash
composer test

View File

@ -21,8 +21,12 @@ We would like to extend our thanks to the following sponsors for funding Pest de
### Premium Sponsors
- **[Scout APM](https://scoutapm.com)**
- **[Akaunting](https://akaunting.com)**
- **[Meema](https://meema.io/)**
- **[Auth0](https://auth0.com)**
- **[Codecourse](https://codecourse.com/)**
- **[Fathom Analytics](https://usefathom.com/)**
- **[Meema](https://meema.io)**
- **[Scout APM](https://scoutapm.com)**
- **[Spatie](https://spatie.be)**
Pest was created by **[Nuno Maduro](https://twitter.com/enunomaduro)** under the **[Sponsorware license](https://github.com/sponsorware/docs)**. It got open-sourced and is now licensed under the **[MIT license](https://opensource.org/licenses/MIT)**.
Pest is an open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**.

View File

@ -6,7 +6,7 @@ When releasing a new version of Pest there are some checks and updates that need
- On the GitHub repository, check the contents of [github.com/pestphp/pest/compare/{latest_version}...master](https://github.com/pestphp/pest/compare/{latest_version}...master) and update the [changelog](CHANGELOG.md) file with the main changes for this release
- Update the version number in [src/Pest.php](src/Pest.php)
- Run the tests locally using: `composer test`
- Commit the CHANGELOG and Pest file with the message: `git commit -m "docs: update changelog"`
- Commit the CHANGELOG and Pest file with the message: `git commit -m "release: vX.X.X"`
- Push the changes to GitHub
- Check that the CI is passing as expected: [github.com/pestphp/pest/actions](https://github.com/pestphp/pest/actions)
- Tag and push the tag with `git tag vX.X.X && git push --tags`

View File

@ -3,9 +3,9 @@
use NunoMaduro\Collision\Provider;
use Pest\Actions\ValidatesEnvironment;
use Pest\Console\Command;
use Pest\Support\Container;
use Pest\TestSuite;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
@ -27,7 +27,7 @@ use Symfony\Component\Console\Output\OutputInterface;
(new Provider())->register();
// get $rootPath based on $autoloadPath
// Get $rootPath based on $autoloadPath
$rootPath = dirname($autoloadPath, 2);
$argv = new ArgvInput();
@ -42,14 +42,22 @@ use Symfony\Component\Console\Output\OutputInterface;
ValidatesEnvironment::in($testSuite);
// lets remove any arguments that PHPUnit does not understand
$args = $_SERVER['argv'];
// Let's remove any arguments that PHPUnit does not understand
if ($argv->hasParameterOption('--test-directory')) {
foreach ($_SERVER['argv'] as $key => $value) {
foreach ($args as $key => $value) {
if (strpos($value, '--test-directory') !== false) {
unset($_SERVER['argv'][$key]);
unset($args[$key]);
}
}
}
exit($container->get(Command::class)->run($_SERVER['argv']));
if (($runInParallel = $argv->hasParameterOption(['--parallel', '-p'])) && !class_exists(\Pest\Parallel\Command::class)) {
$output->writeln("Parallel support requires the Pest Parallel plugin. Run <fg=yellow;options=bold>`composer require --dev pestphp/pest-plugin-parallel`</> first.");
exit(Command::FAILURE);
}
$command = $runInParallel ? \Pest\Parallel\Command::class : \Pest\Console\Command::class;
exit($container->get($command)->run($args));
})();

View File

@ -18,12 +18,9 @@
],
"require": {
"php": "^7.3 || ^8.0",
"nunomaduro/collision": "^5.0",
"pestphp/pest-plugin": "^1.0",
"pestphp/pest-plugin-coverage": "^1.0",
"pestphp/pest-plugin-expectations": "^1.3",
"pestphp/pest-plugin-init": "^1.1",
"phpunit/phpunit": ">= 9.3.7 <= 9.5.5"
"nunomaduro/collision": "^5.4.0|^6.0",
"pestphp/pest-plugin": "^1.0.0",
"phpunit/phpunit": "^9.5.5"
},
"autoload": {
"psr-4": {
@ -43,10 +40,11 @@
]
},
"require-dev": {
"illuminate/console": "^8.32.1",
"illuminate/support": "^8.32.1",
"laravel/dusk": "^6.13.0",
"pestphp/pest-dev-tools": "dev-master"
"illuminate/console": "^8.47.0",
"illuminate/support": "^8.47.0",
"laravel/dusk": "^6.15.0",
"pestphp/pest-dev-tools": "dev-master",
"pestphp/pest-plugin-parallel": "^1.0"
},
"minimum-stability": "dev",
"prefer-stable": true,
@ -60,14 +58,16 @@
"scripts": {
"lint": "php-cs-fixer fix -v",
"test:lint": "php-cs-fixer fix -v --dry-run",
"test:types": "phpstan analyse --ansi --memory-limit=0",
"test:types": "phpstan analyse --ansi --memory-limit=-1",
"test:unit": "php bin/pest --colors=always --exclude-group=integration",
"test:parallel": "php bin/pest -p --colors=always --exclude-group=integration",
"test:integration": "php bin/pest --colors=always --group=integration",
"update:snapshots": "REBUILD_SNAPSHOTS=true php bin/pest --colors=always",
"test": [
"@test:lint",
"@test:types",
"@test:unit",
"@test:parallel",
"@test:integration"
]
},
@ -77,6 +77,8 @@
},
"pest": {
"plugins": [
"Pest\\Plugins\\Coverage",
"Pest\\Plugins\\Init",
"Pest\\Plugins\\Version"
]
},

View File

@ -24,7 +24,7 @@ parameters:
message: '#Call to an undefined method PHPUnit\\Framework\\Test::getName\(\)#'
path: src/Logging
-
message: '#invalid typehint type Pest\\Concerns\\TestCase#'
message: '#invalid typehint type Pest\\Concerns\\Testable#'
path: src/Logging
-
message: '#is not subtype of native type PHPUnit\\Framework\\Test#'

View File

@ -1,36 +0,0 @@
<?php
declare(strict_types=1);
$globalsFilePath = implode(DIRECTORY_SEPARATOR, [
dirname(__DIR__),
'vendor',
'phpunit',
'phpunit',
'src',
'Framework',
'Assert',
'Functions.php',
]);
$compiledFilePath = implode(DIRECTORY_SEPARATOR, [dirname(__DIR__), 'compiled', 'globals.php']);
@unlink($compiledFilePath);
$replace = function ($contents, $string, $by) {
return str_replace($string, $by, $contents);
};
$remove = function ($contents, $string) {
return str_replace($string, '', $contents);
};
$contents = file_get_contents($globalsFilePath);
$contents = $replace($contents, 'namespace PHPUnit\Framework;', 'use PHPUnit\Framework\Assert;');
$contents = $remove($contents, 'use ArrayAccess;');
$contents = $remove($contents, 'use Countable;');
$contents = $remove($contents, 'use DOMDocument;');
$contents = $remove($contents, 'use DOMElement;');
$contents = $remove($contents, 'use Throwable;');
file_put_contents(implode(DIRECTORY_SEPARATOR, [dirname(__DIR__), 'compiled', 'globals.php']), $contents);

View File

@ -30,7 +30,7 @@ final class AddsDefaults
}
if ($arguments[self::PRINTER] === \PHPUnit\Util\Log\TeamCity::class) {
$arguments[self::PRINTER] = new TeamCity($arguments['verbose'] ?? false, $arguments['colors'] ?? DefaultResultPrinter::COLOR_ALWAYS);
$arguments[self::PRINTER] = new TeamCity(null, $arguments['verbose'] ?? false, $arguments['colors'] ?? DefaultResultPrinter::COLOR_ALWAYS);
}
// Load our junit logger instead.

View File

@ -22,8 +22,6 @@ final class AddsTests
{
self::removeTestClosureWarnings($testSuite);
// @todo refactor this...
$testSuites = [];
$pestTestSuite->tests->build($pestTestSuite, function (TestCase $testCase) use (&$testSuites): void {
$testCaseClass = get_class($testCase);

View File

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Pest\Actions;
use Pest\Contracts\Plugins\AddsOutput;
use Pest\Contracts\Plugins\HandlesArguments;
use Pest\Plugin\Loader;
/**
* @internal
*/
final class InteractsWithPlugins
{
/**
* Transform the input arguments by passing it to the relevant plugins.
*
* @param array<int, string> $argv
*
* @return array<int, string>
*/
public static function handleArguments(array $argv): array
{
$plugins = Loader::getPlugins(HandlesArguments::class);
/** @var HandlesArguments $plugin */
foreach ($plugins as $plugin) {
$argv = $plugin->handleArguments($argv);
}
return $argv;
}
/**
* Provides an opportunity for any plugins that want
* to provide additional output after test execution.
*/
public static function addOutput(int $result): int
{
$plugins = Loader::getPlugins(AddsOutput::class);
/** @var AddsOutput $plugin */
foreach ($plugins as $plugin) {
$result = $plugin->addOutput($result);
}
return $result;
}
}

View File

@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Pest\Concerns;
use Pest\Expectation;
/**
* @internal
*/
trait Expectable
{
/**
* @template TValue
*
* Creates a new expectation.
*
* @param TValue $value
*
* @return Expectation<TValue>
*/
public function expect($value): Expectation
{
return new Expectation($value);
}
}

View File

@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace Pest\Concerns;
use BadMethodCallException;
use Closure;
/**
* @internal
*/
trait Extendable
{
/**
* @var array<string, Closure>
*/
private static $extends = [];
/**
* Register a custom extend.
*/
public static function extend(string $name, Closure $extend): void
{
static::$extends[$name] = $extend;
}
/**
* Checks if extend is registered.
*/
public static function hasExtend(string $name): bool
{
return array_key_exists($name, static::$extends);
}
/**
* Dynamically handle calls to the class.
*
* @param array<int, mixed> $parameters
*
* @return mixed
*/
public function __call(string $method, array $parameters)
{
if (!static::hasExtend($method)) {
throw new BadMethodCallException("$method is not a callable method name.");
}
/** @var Closure $extend */
$extend = static::$extends[$method]->bindTo($this, static::class);
return $extend(...$parameters);
}
}

View File

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Pest\Concerns\Logging;
/**
* @internal
*/
trait WritesToConsole
{
private function writeSuccess(string $message): void
{
$this->writePestTestOutput($message, 'fg-green, bold', '✓');
}
private function writeError(string $message): void
{
$this->writePestTestOutput($message, 'fg-red, bold', '');
}
private function writeWarning(string $message): void
{
$this->writePestTestOutput($message, 'fg-yellow, bold', '-');
}
private function writePestTestOutput(string $message, string $color, string $symbol): void
{
$this->writeWithColor($color, "$symbol ", false);
$this->write($message);
$this->writeNewLine();
}
}

View File

@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Pest\Concerns;
/**
* @internal
*/
trait RetrievesValues
{
/**
* @template TRetrievableValue
*
* Safely retrieve the value at the given key from an object or array.
*
* @param array<string, TRetrievableValue>|object $value
* @param TRetrievableValue|null $default
*
* @return TRetrievableValue|null
*/
private function retrieve(string $key, $value, $default = null)
{
if (is_array($value)) {
return $value[$key] ?? $default;
}
// @phpstan-ignore-next-line
return $value->$key ?? $default;
}
}

View File

@ -17,7 +17,7 @@ use Throwable;
*
* @internal
*/
trait TestCase
trait Testable
{
/**
* The test case description. Contains the first
@ -73,6 +73,8 @@ trait TestCase
{
$this->__test = $test;
$this->__description = $description;
self::$beforeAll = null;
self::$afterAll = null;
parent::__construct('__test', $data);
}
@ -271,7 +273,19 @@ trait TestCase
*/
public function __test()
{
return $this->__callClosure($this->__test, func_get_args());
return $this->__callClosure($this->__test, $this->resolveTestArguments(func_get_args()));
}
/**
* Resolve the passed arguments. Any Closures will be bound to the testcase and resolved.
*
* @throws Throwable
*/
private function resolveTestArguments(array $arguments): array
{
return array_map(function ($data) {
return $data instanceof Closure ? $this->__callClosure($data, []) : $data;
}, $arguments);
}
/**

View File

@ -6,11 +6,9 @@ namespace Pest\Console;
use Pest\Actions\AddsDefaults;
use Pest\Actions\AddsTests;
use Pest\Actions\InteractsWithPlugins;
use Pest\Actions\LoadStructure;
use Pest\Actions\ValidatesConfiguration;
use Pest\Contracts\Plugins\AddsOutput;
use Pest\Contracts\Plugins\HandlesArguments;
use Pest\Plugin\Loader;
use Pest\Plugins\Version;
use Pest\Support\Container;
use Pest\TestSuite;
@ -57,23 +55,12 @@ final class Command extends BaseCommand
*/
protected function handleArguments(array $argv): void
{
/*
* First, let's call all plugins that want to handle arguments
*/
$plugins = Loader::getPlugins(HandlesArguments::class);
$argv = InteractsWithPlugins::handleArguments($argv);
/** @var HandlesArguments $plugin */
foreach ($plugins as $plugin) {
$argv = $plugin->handleArguments($argv);
}
/*
* Next, as usual, let's send the console arguments to PHPUnit.
*/
parent::handleArguments($argv);
/*
* Finally, let's validate the configuration. Making
* Let's validate the configuration. Making
* sure all options are yet supported by Pest.
*/
ValidatesConfiguration::in($this->arguments);
@ -128,16 +115,7 @@ final class Command extends BaseCommand
LoadStructure::in($this->testSuite->rootPath);
$result = parent::run($argv, false);
/*
* Let's call all plugins that want to add output after test execution
*/
$plugins = Loader::getPlugins(AddsOutput::class);
/** @var AddsOutput $plugin */
foreach ($plugins as $plugin) {
$result = $plugin->addOutput($result);
}
$result = InteractsWithPlugins::addOutput($result);
exit($result);
}

View File

@ -51,36 +51,34 @@ final class Datasets
/**
* Resolves the current dataset to an array value.
*
* @param Traversable<int|string, mixed>|Closure|iterable<int|string, mixed>|string|null $data
* @param array<Closure|iterable<int|string, mixed>|string> $datasets
*
* @return array<string, mixed>
*/
public static function resolve(string $description, $data): array
public static function resolve(string $description, array $datasets): array
{
/* @phpstan-ignore-next-line */
if (is_null($data) || empty($data)) {
if (empty($datasets)) {
return [$description => []];
}
if (is_string($data)) {
$data = self::get($data);
}
$datasets = self::processDatasets($datasets);
if (is_callable($data)) {
$data = call_user_func($data);
}
if ($data instanceof Traversable) {
$data = iterator_to_array($data);
}
$datasetCombinations = self::getDataSetsCombinations($datasets);
$dataSetDescriptions = [];
$dataSetValues = [];
foreach ($data as $key => $values) {
$values = is_array($values) ? $values : [$values];
foreach ($datasetCombinations as $datasetCombination) {
$partialDescriptions = [];
$values = [];
$dataSetDescriptions[] = $description . self::getDataSetDescription($key, $values);
foreach ($datasetCombination as $dataset_data) {
$partialDescriptions[] = $dataset_data['label'];
$values = array_merge($values, $dataset_data['values']);
}
$dataSetDescriptions[] = $description . ' with ' . implode(' / ', $partialDescriptions);
$dataSetValues[] = $values;
}
@ -103,6 +101,65 @@ final class Datasets
return $namedData;
}
/**
* @param array<Closure|iterable<int|string, mixed>|string> $datasets
*
* @return array<array>
*/
private static function processDatasets(array $datasets): array
{
$processedDatasets = [];
foreach ($datasets as $index => $data) {
$processedDataset = [];
if (is_string($data)) {
$datasets[$index] = self::get($data);
}
if (is_callable($datasets[$index])) {
$datasets[$index] = call_user_func($datasets[$index]);
}
if ($datasets[$index] instanceof Traversable) {
$datasets[$index] = iterator_to_array($datasets[$index]);
}
foreach ($datasets[$index] as $key => $values) {
$values = is_array($values) ? $values : [$values];
$processedDataset[] = [
'label' => self::getDataSetDescription($key, $values),
'values' => $values,
];
}
$processedDatasets[] = $processedDataset;
}
return $processedDatasets;
}
/**
* @param array<array> $combinations
*
* @return array<array>
*/
private static function getDataSetsCombinations(array $combinations): array
{
$result = [[]];
foreach ($combinations as $index => $values) {
$tmp = [];
foreach ($result as $resultItem) {
foreach ($values as $value) {
$tmp[] = array_merge($resultItem, [$index => $value]);
}
}
$result = $tmp;
}
return $result;
}
/**
* @param int|string $key
* @param array<int, mixed> $data
@ -112,9 +169,9 @@ final class Datasets
$exporter = new Exporter();
if (is_int($key)) {
return \sprintf(' with (%s)', $exporter->shortenedRecursiveExport($data));
return \sprintf('(%s)', $exporter->shortenedRecursiveExport($data));
}
return \sprintf(' with data set "%s"', $key);
return \sprintf('data set "%s"', $key);
}
}

77
src/Each.php Normal file
View File

@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace Pest;
/**
* @internal
*
* @mixin Expectation
*/
final class Each
{
/**
* @var Expectation
*/
private $original;
/**
* @var bool
*/
private $opposite = false;
/**
* Creates an expectation on each item of the iterable "value".
*/
public function __construct(Expectation $original)
{
$this->original = $original;
}
/**
* Creates a new expectation.
*
* @param mixed $value
*/
public function and($value): Expectation
{
return $this->original->and($value);
}
/**
* Creates the opposite expectation for the value.
*/
public function not(): Each
{
$this->opposite = true;
return $this;
}
/**
* Dynamically calls methods on the class with the given arguments on each item.
*
* @param array<int|string, mixed> $arguments
*/
public function __call(string $name, array $arguments): Each
{
foreach ($this->original->value as $item) {
/* @phpstan-ignore-next-line */
$this->opposite ? expect($item)->not()->$name(...$arguments) : expect($item)->$name(...$arguments);
}
$this->opposite = false;
return $this;
}
/**
* Dynamically calls methods on the class without any arguments on each item.
*/
public function __get(string $name): Each
{
/* @phpstan-ignore-next-line */
return $this->$name();
}
}

View File

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Pest\Exceptions;
use BadFunctionCallException;
use NunoMaduro\Collision\Contracts\RenderlessEditor;
use NunoMaduro\Collision\Contracts\RenderlessTrace;
use Symfony\Component\Console\Exception\ExceptionInterface;
/**
* Creates a new instance of dataset is not present for test that has arguments.
*
* @internal
*/
final class DatasetMissing extends BadFunctionCallException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{
/**
* Create new exception instance.
*
* @param array<string, string> $args A map of argument names to their typee
*/
public function __construct(string $file, string $name, array $args)
{
parent::__construct(sprintf(
"A test with the description '%s' has %d argument(s) ([%s]) and no dataset(s) provided in %s",
$name,
count($args),
implode(', ', array_map(static function (string $arg, string $type): string {
return sprintf('%s $%s', $type, $arg);
}, array_keys($args), $args)),
$file,
));
}
}

899
src/Expectation.php Normal file
View File

@ -0,0 +1,899 @@
<?php
declare(strict_types=1);
namespace Pest;
use BadMethodCallException;
use Closure;
use InvalidArgumentException;
use Pest\Concerns\Extendable;
use Pest\Concerns\RetrievesValues;
use Pest\Support\Arr;
use Pest\Support\NullClosure;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use ReflectionFunction;
use ReflectionNamedType;
use SebastianBergmann\Exporter\Exporter;
use Throwable;
/**
* @internal
*
* @template TValue
*
* @property Expectation $not Creates the opposite expectation.
* @property Each $each Creates an expectation on each element on the traversable value.
*/
final class Expectation
{
use Extendable {
__call as __extendsCall;
}
use RetrievesValues;
/**
* The expectation value.
*
* @readonly
*
* @var mixed
*/
public $value;
/**
* The exporter instance, if any.
*
* @readonly
*
* @var Exporter|null
*/
private $exporter;
/**
* Creates a new expectation.
*
* @param TValue $value
*/
public function __construct($value)
{
$this->value = $value;
}
/**
* Creates a new expectation.
*
* @param TValue $value
*
* @return Expectation<TValue>
*/
public function and($value): Expectation
{
return new self($value);
}
/**
* Creates a new expectation with the decoded JSON value.
*/
public function json(): Expectation
{
return $this->toBeJson()->and(json_decode($this->value, true));
}
/**
* Dump the expectation value and end the script.
*
* @param mixed $arguments
*
* @return never
*/
public function dd(...$arguments): void
{
if (function_exists('dd')) {
dd($this->value, ...$arguments);
}
var_dump($this->value);
exit(1);
}
/**
* Send the expectation value to Ray along with all given arguments.
*
* @param mixed $arguments
*/
public function ray(...$arguments): self
{
if (function_exists('ray')) {
// @phpstan-ignore-next-line
ray($this->value, ...$arguments);
}
return $this;
}
/**
* Creates the opposite expectation for the value.
*/
public function not(): OppositeExpectation
{
return new OppositeExpectation($this);
}
/**
* Creates an expectation on each item of the iterable "value".
*/
public function each(callable $callback = null): Each
{
if (!is_iterable($this->value)) {
throw new BadMethodCallException('Expectation value is not iterable.');
}
if (is_callable($callback)) {
foreach ($this->value as $item) {
$callback(new self($item));
}
}
return new Each($this);
}
/**
* Allows you to specify a sequential set of expectations for each item in a iterable "value".
*
* @template TSequenceValue
*
* @param callable(self, self): void|TSequenceValue ...$callbacks
*/
public function sequence(...$callbacks): Expectation
{
if (!is_iterable($this->value)) {
throw new BadMethodCallException('Expectation value is not iterable.');
}
$value = is_array($this->value) ? $this->value : iterator_to_array($this->value);
$keys = array_keys($value);
$values = array_values($value);
$index = 0;
while (count($callbacks) < count($values)) {
$callbacks[] = $callbacks[$index];
$index = $index < count($values) - 1 ? $index + 1 : 0;
}
foreach ($values as $key => $item) {
if (is_callable($callbacks[$key])) {
call_user_func($callbacks[$key], new self($item), new self($keys[$key]));
continue;
}
(new self($item))->toEqual($callbacks[$key]);
}
return $this;
}
/**
* Asserts that two variables have the same type and
* value. Used on objects, it asserts that two
* variables reference the same object.
*
* @param mixed $expected
*/
public function toBe($expected): Expectation
{
Assert::assertSame($expected, $this->value);
return $this;
}
/**
* Asserts that the value is empty.
*/
public function toBeEmpty(): Expectation
{
Assert::assertEmpty($this->value);
return $this;
}
/**
* Asserts that the value is true.
*/
public function toBeTrue(): Expectation
{
Assert::assertTrue($this->value);
return $this;
}
/**
* Asserts that the value is truthy.
*/
public function toBeTruthy(): Expectation
{
Assert::assertTrue((bool) $this->value);
return $this;
}
/**
* Asserts that the value is false.
*/
public function toBeFalse(): Expectation
{
Assert::assertFalse($this->value);
return $this;
}
/**
* Asserts that the value is falsy.
*/
public function toBeFalsy(): Expectation
{
Assert::assertFalse((bool) $this->value);
return $this;
}
/**
* Asserts that the value is greater than $expected.
*
* @param int|float $expected
*/
public function toBeGreaterThan($expected): Expectation
{
Assert::assertGreaterThan($expected, $this->value);
return $this;
}
/**
* Asserts that the value is greater than or equal to $expected.
*
* @param int|float $expected
*/
public function toBeGreaterThanOrEqual($expected): Expectation
{
Assert::assertGreaterThanOrEqual($expected, $this->value);
return $this;
}
/**
* Asserts that the value is less than or equal to $expected.
*
* @param int|float $expected
*/
public function toBeLessThan($expected): Expectation
{
Assert::assertLessThan($expected, $this->value);
return $this;
}
/**
* Asserts that the value is less than $expected.
*
* @param int|float $expected
*/
public function toBeLessThanOrEqual($expected): Expectation
{
Assert::assertLessThanOrEqual($expected, $this->value);
return $this;
}
/**
* Asserts that $needle is an element of the value.
*
* @param mixed $needles
*/
public function toContain(...$needles): Expectation
{
foreach ($needles as $needle) {
if (is_string($this->value)) {
Assert::assertStringContainsString($needle, $this->value);
} else {
Assert::assertContains($needle, $this->value);
}
}
return $this;
}
/**
* Asserts that the value starts with $expected.
*/
public function toStartWith(string $expected): Expectation
{
Assert::assertStringStartsWith($expected, $this->value);
return $this;
}
/**
* Asserts that the value ends with $expected.
*/
public function toEndWith(string $expected): Expectation
{
Assert::assertStringEndsWith($expected, $this->value);
return $this;
}
/**
* Asserts that $number matches value's Length.
*/
public function toHaveLength(int $number): Expectation
{
if (is_string($this->value)) {
Assert::assertEquals($number, mb_strlen($this->value));
return $this;
}
if (is_iterable($this->value)) {
return $this->toHaveCount($number);
}
if (is_object($this->value)) {
if (method_exists($this->value, 'toArray')) {
$array = $this->value->toArray();
} else {
$array = (array) $this->value;
}
Assert::assertCount($number, $array);
return $this;
}
throw new BadMethodCallException('Expectation value length is not countable.');
}
/**
* Asserts that $count matches the number of elements of the value.
*/
public function toHaveCount(int $count): Expectation
{
Assert::assertCount($count, $this->value);
return $this;
}
/**
* Asserts that the value contains the property $name.
*
* @param mixed $value
*/
public function toHaveProperty(string $name, $value = null): Expectation
{
$this->toBeObject();
Assert::assertTrue(property_exists($this->value, $name));
if (func_num_args() > 1) {
/* @phpstan-ignore-next-line */
Assert::assertEquals($value, $this->value->{$name});
}
return $this;
}
/**
* Asserts that the value contains the provided properties $names.
*
* @param iterable<array-key, string> $names
*/
public function toHaveProperties(iterable $names): Expectation
{
foreach ($names as $name) {
$this->toHaveProperty($name);
}
return $this;
}
/**
* Asserts that two variables have the same value.
*
* @param mixed $expected
*/
public function toEqual($expected): Expectation
{
Assert::assertEquals($expected, $this->value);
return $this;
}
/**
* Asserts that two variables have the same value.
* The contents of $expected and the $this->value are
* canonicalized before they are compared. For instance, when the two
* variables $expected and $this->value are arrays, then these arrays
* are sorted before they are compared. When $expected and $this->value
* are objects, each object is converted to an array containing all
* private, protected and public attributes.
*
* @param mixed $expected
*/
public function toEqualCanonicalizing($expected): Expectation
{
Assert::assertEqualsCanonicalizing($expected, $this->value);
return $this;
}
/**
* Asserts that the absolute difference between the value and $expected
* is lower than $delta.
*
* @param mixed $expected
*/
public function toEqualWithDelta($expected, float $delta): Expectation
{
Assert::assertEqualsWithDelta($expected, $this->value, $delta);
return $this;
}
/**
* Asserts that the value is one of the given values.
*
* @param iterable<int|string, mixed> $values
*/
public function toBeIn(iterable $values): Expectation
{
Assert::assertContains($this->value, $values);
return $this;
}
/**
* Asserts that the value is infinite.
*/
public function toBeInfinite(): Expectation
{
Assert::assertInfinite($this->value);
return $this;
}
/**
* Asserts that the value is an instance of $class.
*
* @param string $class
*/
public function toBeInstanceOf($class): Expectation
{
/* @phpstan-ignore-next-line */
Assert::assertInstanceOf($class, $this->value);
return $this;
}
/**
* Asserts that the value is an array.
*/
public function toBeArray(): Expectation
{
Assert::assertIsArray($this->value);
return $this;
}
/**
* Asserts that the value is of type bool.
*/
public function toBeBool(): Expectation
{
Assert::assertIsBool($this->value);
return $this;
}
/**
* Asserts that the value is of type callable.
*/
public function toBeCallable(): Expectation
{
Assert::assertIsCallable($this->value);
return $this;
}
/**
* Asserts that the value is of type float.
*/
public function toBeFloat(): Expectation
{
Assert::assertIsFloat($this->value);
return $this;
}
/**
* Asserts that the value is of type int.
*/
public function toBeInt(): Expectation
{
Assert::assertIsInt($this->value);
return $this;
}
/**
* Asserts that the value is of type iterable.
*/
public function toBeIterable(): Expectation
{
Assert::assertIsIterable($this->value);
return $this;
}
/**
* Asserts that the value is of type numeric.
*/
public function toBeNumeric(): Expectation
{
Assert::assertIsNumeric($this->value);
return $this;
}
/**
* Asserts that the value is of type object.
*/
public function toBeObject(): Expectation
{
Assert::assertIsObject($this->value);
return $this;
}
/**
* Asserts that the value is of type resource.
*/
public function toBeResource(): Expectation
{
Assert::assertIsResource($this->value);
return $this;
}
/**
* Asserts that the value is of type scalar.
*/
public function toBeScalar(): Expectation
{
Assert::assertIsScalar($this->value);
return $this;
}
/**
* Asserts that the value is of type string.
*/
public function toBeString(): Expectation
{
Assert::assertIsString($this->value);
return $this;
}
/**
* Asserts that the value is a JSON string.
*/
public function toBeJson(): Expectation
{
Assert::assertIsString($this->value);
Assert::assertJson($this->value);
return $this;
}
/**
* Asserts that the value is NAN.
*/
public function toBeNan(): Expectation
{
Assert::assertNan($this->value);
return $this;
}
/**
* Asserts that the value is null.
*/
public function toBeNull(): Expectation
{
Assert::assertNull($this->value);
return $this;
}
/**
* Asserts that the value array has the provided $key.
*
* @param string|int $key
* @param mixed $value
*/
public function toHaveKey($key, $value = null): Expectation
{
if (is_object($this->value) && method_exists($this->value, 'toArray')) {
$array = $this->value->toArray();
} else {
$array = (array) $this->value;
}
try {
Assert::assertTrue(Arr::has($array, $key));
/* @phpstan-ignore-next-line */
} catch (ExpectationFailedException $exception) {
throw new ExpectationFailedException("Failed asserting that an array has the key '$key'", $exception->getComparisonFailure());
}
if (func_num_args() > 1) {
Assert::assertEquals($value, Arr::get($array, $key));
}
return $this;
}
/**
* Asserts that the value array has the provided $keys.
*
* @param array<int, int|string> $keys
*/
public function toHaveKeys(array $keys): Expectation
{
foreach ($keys as $key) {
$this->toHaveKey($key);
}
return $this;
}
/**
* Asserts that the value is a directory.
*/
public function toBeDirectory(): Expectation
{
Assert::assertDirectoryExists($this->value);
return $this;
}
/**
* Asserts that the value is a directory and is readable.
*/
public function toBeReadableDirectory(): Expectation
{
Assert::assertDirectoryIsReadable($this->value);
return $this;
}
/**
* Asserts that the value is a directory and is writable.
*/
public function toBeWritableDirectory(): Expectation
{
Assert::assertDirectoryIsWritable($this->value);
return $this;
}
/**
* Asserts that the value is a file.
*/
public function toBeFile(): Expectation
{
Assert::assertFileExists($this->value);
return $this;
}
/**
* Asserts that the value is a file and is readable.
*/
public function toBeReadableFile(): Expectation
{
Assert::assertFileIsReadable($this->value);
return $this;
}
/**
* Asserts that the value is a file and is writable.
*/
public function toBeWritableFile(): Expectation
{
Assert::assertFileIsWritable($this->value);
return $this;
}
/**
* Asserts that the value array matches the given array subset.
*
* @param array<int|string, mixed> $array
*/
public function toMatchArray($array): Expectation
{
if (is_object($this->value) && method_exists($this->value, 'toArray')) {
$valueAsArray = $this->value->toArray();
} else {
$valueAsArray = (array) $this->value;
}
foreach ($array as $key => $value) {
Assert::assertArrayHasKey($key, $valueAsArray);
Assert::assertEquals(
$value,
$valueAsArray[$key],
sprintf(
'Failed asserting that an array has a key %s with the value %s.',
$this->export($key),
$this->export($valueAsArray[$key]),
),
);
}
return $this;
}
/**
* Asserts that the value object matches a subset
* of the properties of an given object.
*
* @param array<string, mixed>|object $object
*/
public function toMatchObject($object): Expectation
{
foreach ((array) $object as $property => $value) {
Assert::assertTrue(property_exists($this->value, $property));
/* @phpstan-ignore-next-line */
$propertyValue = $this->value->{$property};
Assert::assertEquals(
$value,
$propertyValue,
sprintf(
'Failed asserting that an object has a property %s with the value %s.',
$this->export($property),
$this->export($propertyValue),
),
);
}
return $this;
}
/**
* Asserts that the value matches a regular expression.
*/
public function toMatch(string $expression): Expectation
{
Assert::assertMatchesRegularExpression($expression, $this->value);
return $this;
}
/**
* Asserts that the value matches a constraint.
*/
public function toMatchConstraint(Constraint $constraint): Expectation
{
Assert::assertThat($this->value, $constraint);
return $this;
}
/**
* Asserts that executing value throws an exception.
*
* @param (Closure(Throwable): mixed)|string $exception
*/
public function toThrow($exception, string $exceptionMessage = null): Expectation
{
$callback = NullClosure::create();
if ($exception instanceof Closure) {
$callback = $exception;
$parameters = (new ReflectionFunction($exception))->getParameters();
if (1 !== count($parameters)) {
throw new InvalidArgumentException('The given closure must have a single parameter type-hinted as the class string.');
}
if (!($type = $parameters[0]->getType()) instanceof ReflectionNamedType) {
throw new InvalidArgumentException('The given closure\'s parameter must be type-hinted as the class string.');
}
$exception = $type->getName();
}
try {
($this->value)();
} catch (Throwable $e) { // @phpstan-ignore-line
if (!class_exists($exception)) {
Assert::assertStringContainsString($exception, $e->getMessage());
return $this;
}
if ($exceptionMessage !== null) {
Assert::assertStringContainsString($exceptionMessage, $e->getMessage());
}
Assert::assertInstanceOf($exception, $e);
$callback($e);
return $this;
}
if (!class_exists($exception)) {
throw new ExpectationFailedException("Exception with message \"{$exception}\" not thrown.");
}
throw new ExpectationFailedException("Exception \"{$exception}\" not thrown.");
}
/**
* Exports the given value.
*
* @param mixed $value
*/
private function export($value): string
{
if ($this->exporter === null) {
$this->exporter = new Exporter();
}
return $this->exporter->export($value);
}
/**
* Dynamically handle calls to the class or
* creates a new higher order expectation.
*
* @param array<int, mixed> $parameters
*
* @return HigherOrderExpectation|mixed
*/
public function __call(string $method, array $parameters)
{
if (!static::hasExtend($method)) {
/* @phpstan-ignore-next-line */
return new HigherOrderExpectation($this, $this->value->$method(...$parameters));
}
return $this->__extendsCall($method, $parameters);
}
/**
* Dynamically calls methods on the class without any arguments
* or creates a new higher order expectation.
*
* @return Expectation|HigherOrderExpectation
*/
public function __get(string $name)
{
if (!method_exists($this, $name) && !static::hasExtend($name)) {
return new HigherOrderExpectation($this, $this->retrieve($name, $this->value));
}
/* @phpstan-ignore-next-line */
return $this->{$name}();
}
}

View File

@ -11,9 +11,9 @@ use Pest\Contracts\HasPrintableTestCaseName;
use Pest\Datasets;
use Pest\Exceptions\ShouldNotHappen;
use Pest\Support\HigherOrderMessageCollection;
use Pest\Support\NullClosure;
use Pest\Support\Str;
use Pest\TestSuite;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\TestCase;
use RuntimeException;
@ -62,9 +62,9 @@ final class TestCaseFactory
/**
* Holds the dataset, if any.
*
* @var Closure|iterable<int|string, mixed>|string|null
* @var array<Closure|iterable<int|string, mixed>|string>
*/
public $dataset;
public $datasets = [];
/**
* The FQN of the test case class.
@ -79,7 +79,8 @@ final class TestCaseFactory
* @var array <int, string>
*/
public $traits = [
Concerns\TestCase::class,
Concerns\Testable::class,
Concerns\Expectable::class,
];
/**
@ -113,7 +114,11 @@ final class TestCaseFactory
{
$this->filename = $filename;
$this->description = $description;
$this->test = $closure ?? NullClosure::create();
$this->test = $closure ?? function (): void {
if (Assert::getCount() === 0) {
self::markTestIncomplete(); // @phpstan-ignore-line
}
};
$this->factoryProxies = new HigherOrderMessageCollection();
$this->proxies = new HigherOrderMessageCollection();
@ -155,7 +160,7 @@ final class TestCaseFactory
return $testCase;
};
$datasets = Datasets::resolve($this->description, $this->dataset);
$datasets = Datasets::resolve($this->description, $this->datasets);
return array_map($createTest, array_keys($datasets), $datasets);
}
@ -223,4 +228,13 @@ final class TestCaseFactory
return $classFQN;
}
/**
* Determine if the test case will receive argument input from Pest, or not.
*/
public function receivesArguments(): bool
{
return count($this->datasets) > 0
|| $this->factoryProxies->count('addDependencies') > 0;
}
}

View File

@ -3,15 +3,33 @@
declare(strict_types=1);
use Pest\Datasets;
use Pest\Expectation;
use Pest\PendingObjects\AfterEachCall;
use Pest\PendingObjects\BeforeEachCall;
use Pest\PendingObjects\TestCall;
use Pest\PendingObjects\UsesCall;
use Pest\Support\Backtrace;
use Pest\Support\Extendable;
use Pest\Support\HigherOrderTapProxy;
use Pest\TestSuite;
use PHPUnit\Framework\TestCase;
/**
* Creates a new expectation.
*
* @param mixed $value the Value
*
* @return Expectation|Extendable
*/
function expect($value = null)
{
if (func_num_args() === 0) {
return new Extendable(Expectation::class);
}
return new Expectation($value);
}
if (!function_exists('beforeAll')) {
/**
* Runs the given closure before all tests in the current file.

View File

@ -0,0 +1,144 @@
<?php
declare(strict_types=1);
namespace Pest;
use Pest\Concerns\Expectable;
use Pest\Concerns\RetrievesValues;
/**
* @internal
*
* @mixin Expectation
*/
final class HigherOrderExpectation
{
use Expectable;
use RetrievesValues;
/**
* @var Expectation
*/
private $original;
/**
* @var Expectation|Each
*/
private $expectation;
/**
* @var bool
*/
private $opposite = false;
/**
* @var bool
*/
private $shouldReset = false;
/**
* @var string
*/
private $name;
/**
* Creates a new higher order expectation.
*
* @param mixed $value
*/
public function __construct(Expectation $original, $value)
{
$this->original = $original;
$this->expectation = $this->expect($value);
}
/**
* Creates the opposite expectation for the value.
*/
public function not(): HigherOrderExpectation
{
$this->opposite = !$this->opposite;
return $this;
}
/**
* Creates a new expectation.
*
* @template TValue
*
* @param TValue $value
*
* @return Expectation<TValue>
*/
public function and($value): Expectation
{
return $this->expect($value);
}
/**
* Dynamically calls methods on the class with the given arguments.
*
* @param array<int, mixed> $arguments
*/
public function __call(string $name, array $arguments): self
{
if (!$this->expectationHasMethod($name)) {
/* @phpstan-ignore-next-line */
return new self($this->original, $this->getValue()->$name(...$arguments));
}
return $this->performAssertion($name, $arguments);
}
/**
* Accesses properties in the value or in the expectation.
*/
public function __get(string $name): self
{
if ($name === 'not') {
return $this->not();
}
if (!$this->expectationHasMethod($name)) {
return new self($this->original, $this->retrieve($name, $this->getValue()));
}
return $this->performAssertion($name, []);
}
/**
* Determines if the original expectation has the given method name.
*/
private function expectationHasMethod(string $name): bool
{
return method_exists($this->original, $name) || $this->original::hasExtend($name);
}
/**
* Retrieve the applicable value based on the current reset condition.
*
* @return mixed
*/
private function getValue()
{
return $this->shouldReset ? $this->original->value : $this->expectation->value;
}
/**
* Performs the given assertion with the current expectation.
*
* @param array<int, mixed> $arguments
*/
private function performAssertion(string $name, array $arguments): self
{
/* @phpstan-ignore-next-line */
$this->expectation = ($this->opposite ? $this->expectation->not() : $this->expectation)->{$name}(...$arguments);
$this->opposite = false;
$this->shouldReset = true;
return $this;
}
}

View File

@ -21,7 +21,7 @@ final class PestTestCommand extends Command
*
* @var string
*/
protected $signature = 'pest:test {name : The name of the file} {--unit : Create a unit test} {--dusk : Create a Dusk test} {--test-directory=tests : The name of the tests directory}';
protected $signature = 'pest:test {name : The name of the file} {--unit : Create a unit test} {--dusk : Create a Dusk test} {--test-directory=tests : The name of the tests directory} {--force : Overwrite the existing test file with the same name}';
/**
* The console command description.
@ -56,7 +56,7 @@ final class PestTestCommand extends Command
File::makeDirectory(dirname($target), 0777, true, true);
}
if (File::exists($target)) {
if (File::exists($target) && !(bool) $this->option('force')) {
throw new InvalidConsoleArgument(sprintf('%s already exist', $target));
}

View File

@ -18,7 +18,7 @@ use DOMElement;
use Exception;
use function get_class;
use function method_exists;
use Pest\Concerns\TestCase;
use Pest\Concerns\Testable;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\ExceptionWrapper;
use PHPUnit\Framework\SelfDescribing;
@ -266,7 +266,7 @@ final class JUnit extends Printer implements TestListener
/**
* A test started.
*
* @param Test|TestCase $test
* @param Test|Testable $test
*/
public function startTest(Test $test): void
{

View File

@ -5,25 +5,34 @@ declare(strict_types=1);
namespace Pest\Logging;
use function getmypid;
use Pest\Concerns\TestCase;
use Pest\Concerns\Logging\WritesToConsole;
use Pest\Concerns\Testable;
use Pest\Support\ExceptionTrace;
use function Pest\version;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestResult;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\Warning;
use PHPUnit\TextUI\DefaultResultPrinter;
use function round;
use function str_replace;
use function strlen;
use Throwable;
final class TeamCity extends DefaultResultPrinter
{
use WritesToConsole;
private const PROTOCOL = 'pest_qn://';
private const NAME = 'name';
private const LOCATION_HINT = 'locationHint';
private const DURATION = 'duration';
private const TEST_SUITE_STARTED = 'testSuiteStarted';
private const TEST_SUITE_FINISHED = 'testSuiteFinished';
private const TEST_COUNT = 'testCount';
private const TEST_STARTED = 'testStarted';
private const TEST_FINISHED = 'testFinished';
/** @var int */
private $flowId;
@ -34,148 +43,105 @@ final class TeamCity extends DefaultResultPrinter
/** @var \PHPUnit\Util\Log\TeamCity */
private $phpunitTeamCity;
public function __construct(bool $verbose, string $colors)
/**
* @param resource|string|null $out
*/
public function __construct($out, bool $verbose, string $colors)
{
parent::__construct(null, $verbose, $colors, false, 80, false);
$this->phpunitTeamCity = new \PHPUnit\Util\Log\TeamCity(
null,
$verbose,
$colors,
false,
80,
false
);
parent::__construct($out, $verbose, $colors);
$this->phpunitTeamCity = new \PHPUnit\Util\Log\TeamCity($out, $verbose, $colors);
$this->logo();
}
private function logo(): void
{
$this->writeNewLine();
$this->write('Pest ' . version());
$this->writeNewLine();
}
public function printResult(TestResult $result): void
{
$this->printHeader($result);
$this->printFooter($result);
$this->write('Tests: ');
$results = [
'failed' => ['count' => $result->errorCount() + $result->failureCount(), 'color' => 'fg-red'],
'skipped' => ['count' => $result->skippedCount(), 'color' => 'fg-yellow'],
'warned' => ['count' => $result->warningCount(), 'color' => 'fg-yellow'],
'risked' => ['count' => $result->riskyCount(), 'color' => 'fg-yellow'],
'incomplete' => ['count' => $result->notImplementedCount(), 'color' => 'fg-yellow'],
'passed' => ['count' => $this->successfulTestCount($result), 'color' => 'fg-green'],
];
$filteredResults = array_filter($results, function ($item): bool {
return $item['count'] > 0;
});
foreach ($filteredResults as $key => $info) {
$this->writeWithColor($info['color'], $info['count'] . " $key", false);
if ($key !== array_reverse(array_keys($filteredResults))[0]) {
$this->write(', ');
}
}
$this->writeNewLine();
$this->write("Assertions: $this->numAssertions");
$this->writeNewLine();
$this->write("Time: {$result->time()}s");
$this->writeNewLine();
}
private function successfulTestCount(TestResult $result): int
{
return $result->count()
- $result->failureCount()
- $result->errorCount()
- $result->skippedCount()
- $result->warningCount()
- $result->notImplementedCount()
- $result->riskyCount();
}
/** @phpstan-ignore-next-line */
public function startTestSuite(TestSuite $suite): void
{
$suiteName = $suite->getName();
if (static::isCompoundTestSuite($suite)) {
$this->writeWithColor('bold', ' ' . $suiteName);
} elseif (static::isPestTestSuite($suite)) {
$this->writeWithColor('fg-white, bold', ' ' . substr_replace($suiteName, '', 0, 2) . ' ');
} else {
$this->writeWithColor('fg-white, bold', ' ' . $suiteName);
}
$this->writeNewLine();
$this->flowId = (int) getmypid();
if (!$this->isSummaryTestCountPrinted) {
$this->printEvent(
'testCount',
['count' => $suite->count()]
);
$this->printEvent(self::TEST_COUNT, [
'count' => $suite->count(),
]);
$this->isSummaryTestCountPrinted = true;
}
$suiteName = $suite->getName();
if (file_exists($suiteName) || !method_exists($suiteName, '__getFileName')) {
$this->printEvent(
self::TEST_SUITE_STARTED, [
self::NAME => $suiteName,
self::LOCATION_HINT => self::PROTOCOL . $suiteName,
]);
return;
}
$fileName = $suiteName::__getFileName();
$this->printEvent(
self::TEST_SUITE_STARTED, [
self::NAME => substr($suiteName, 2),
self::LOCATION_HINT => self::PROTOCOL . $fileName,
$this->printEvent(self::TEST_SUITE_STARTED, [
self::NAME => static::isCompoundTestSuite($suite) ? $suiteName : substr($suiteName, 2),
self::LOCATION_HINT => self::PROTOCOL . (static::isCompoundTestSuite($suite) ? $suiteName : $suiteName::__getFileName()),
]);
}
/** @phpstan-ignore-next-line */
public function endTestSuite(TestSuite $suite): void
{
$suiteName = $suite->getName();
if (file_exists($suiteName) || !method_exists($suiteName, '__getFileName')) {
$this->printEvent(
self::TEST_SUITE_FINISHED, [
self::NAME => $suiteName,
self::LOCATION_HINT => self::PROTOCOL . $suiteName,
]);
return;
}
$this->printEvent(
self::TEST_SUITE_FINISHED, [
self::NAME => substr($suiteName, 2),
]);
}
/**
* @param Test|TestCase $test
*/
public function startTest(Test $test): void
{
if (!TeamCity::isPestTest($test)) {
$this->phpunitTeamCity->startTest($test);
return;
}
$this->printEvent('testStarted', [
self::NAME => $test->getName(),
// @phpstan-ignore-next-line
self::LOCATION_HINT => self::PROTOCOL . $test->toString(),
]);
}
/**
* @param Test|TestCase $test
*/
public function endTest(Test $test, float $time): void
{
if (!TeamCity::isPestTest($test)) {
$this->phpunitTeamCity->endTest($test, $time);
return;
}
$this->printEvent('testFinished', [
self::NAME => $test->getName(),
self::DURATION => self::toMilliseconds($time),
]);
}
/**
* @param Test|TestCase $test
*/
public function addError(Test $test, Throwable $t, float $time): void
{
$this->phpunitTeamCity->addError($test, $t, $time);
}
/**
* @phpstan-ignore-next-line
*
* @param Test|TestCase $test
*/
public function addWarning(Test $test, Warning $e, float $time): void
{
$this->phpunitTeamCity->addWarning($test, $e, $time);
}
public function addFailure(Test $test, AssertionFailedError $e, float $time): void
{
$this->phpunitTeamCity->addFailure($test, $e, $time);
}
protected function writeProgress(string $progress): void
{
}
/**
* @param array<string, string|int> $params
*/
private function printEvent(string $eventName, array $params = []): void
{
$this->write("\n##teamcity[{$eventName}");
$this->write("##teamcity[{$eventName}");
if ($this->flowId !== 0) {
$params['flowId'] = $this->flowId;
@ -198,9 +164,56 @@ final class TeamCity extends DefaultResultPrinter
);
}
private static function toMilliseconds(float $time): int
/** @phpstan-ignore-next-line */
public function endTestSuite(TestSuite $suite): void
{
return (int) round($time * 1000);
$suiteName = $suite->getName();
$this->writeNewLine();
$this->writeNewLine();
$this->printEvent(self::TEST_SUITE_FINISHED, [
self::NAME => static::isCompoundTestSuite($suite) ? $suiteName : substr($suiteName, 2),
self::LOCATION_HINT => self::PROTOCOL . (static::isCompoundTestSuite($suite) ? $suiteName : $suiteName::__getFileName()),
]);
}
/**
* @param Test|Testable $test
*/
public function startTest(Test $test): void
{
if (!TeamCity::isPestTest($test)) {
$this->phpunitTeamCity->startTest($test);
return;
}
$this->printEvent(self::TEST_STARTED, [
self::NAME => $test->getName(),
// @phpstan-ignore-next-line
self::LOCATION_HINT => self::PROTOCOL . $test->toString(),
]);
}
/**
* Verify that the given test suite is a valid Pest suite.
*
* @param TestSuite<Test> $suite
*/
private static function isPestTestSuite(TestSuite $suite): bool
{
return strncmp($suite->getName(), 'P\\', strlen('P\\')) === 0;
}
/**
* Determine if the test suite is made up of multiple smaller test suites.
*
* @param TestSuite<Test> $suite
*/
private static function isCompoundTestSuite(TestSuite $suite): bool
{
return file_exists($suite->getName()) || !method_exists($suite->getName(), '__getFileName');
}
public static function isPestTest(Test $test): bool
@ -208,6 +221,77 @@ final class TeamCity extends DefaultResultPrinter
/** @var array<string, string> $uses */
$uses = class_uses($test);
return in_array(TestCase::class, $uses, true);
return in_array(Testable::class, $uses, true);
}
/**
* @param Test|Testable $test
*/
public function endTest(Test $test, float $time): void
{
$this->printEvent(self::TEST_FINISHED, [
self::NAME => $test->getName(),
self::DURATION => self::toMilliseconds($time),
]);
if (!$this->lastTestFailed) {
$this->writeSuccess($test->getName());
}
$this->numAssertions += $test instanceof TestCase ? $test->getNumAssertions() : 1;
$this->lastTestFailed = false;
}
private static function toMilliseconds(float $time): int
{
return (int) round($time * 1000);
}
public function addError(Test $test, Throwable $t, float $time): void
{
$this->markAsFailure($t);
$this->writeError($test->getName());
$this->phpunitTeamCity->addError($test, $t, $time);
}
public function addFailure(Test $test, AssertionFailedError $e, float $time): void
{
$this->markAsFailure($e);
$this->writeError($test->getName());
$this->phpunitTeamCity->addFailure($test, $e, $time);
}
public function addWarning(Test $test, Warning $e, float $time): void
{
$this->markAsFailure($e);
$this->writeWarning($test->getName());
$this->phpunitTeamCity->addWarning($test, $e, $time);
}
public function addIncompleteTest(Test $test, Throwable $t, float $time): void
{
$this->markAsFailure($t);
$this->writeWarning($test->getName());
$this->phpunitTeamCity->addIncompleteTest($test, $t, $time);
}
public function addRiskyTest(Test $test, Throwable $t, float $time): void
{
$this->markAsFailure($t);
$this->writeWarning($test->getName());
$this->phpunitTeamCity->addRiskyTest($test, $t, $time);
}
public function addSkippedTest(Test $test, Throwable $t, float $time): void
{
$this->markAsFailure($t);
$this->writeWarning($test->getName());
$this->phpunitTeamCity->printIgnoredTest($test->getName(), $t, $time);
}
private function markAsFailure(Throwable $t): void
{
$this->lastTestFailed = true;
ExceptionTrace::removePestReferences($t);
}
}

View File

@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
namespace Pest;
use PHPUnit\Framework\ExpectationFailedException;
use SebastianBergmann\Exporter\Exporter;
/**
* @internal
*
* @mixin Expectation
*/
final class OppositeExpectation
{
/**
* @var Expectation
*/
private $original;
/**
* Creates a new opposite expectation.
*/
public function __construct(Expectation $original)
{
$this->original = $original;
}
/**
* Asserts that the value array not has the provided $keys.
*
* @param array<int, int|string> $keys
*/
public function toHaveKeys(array $keys): Expectation
{
foreach ($keys as $key) {
try {
$this->original->toHaveKey($key);
} catch (ExpectationFailedException $e) {
continue;
}
$this->throwExpectationFailedException('toHaveKey', [$key]);
}
return $this->original;
}
/**
* Handle dynamic method calls into the original expectation.
*
* @param array<int, mixed> $arguments
*/
public function __call(string $name, array $arguments): Expectation
{
try {
/* @phpstan-ignore-next-line */
$this->original->{$name}(...$arguments);
} catch (ExpectationFailedException $e) {
return $this->original;
}
// @phpstan-ignore-next-line
$this->throwExpectationFailedException($name, $arguments);
}
/**
* Handle dynamic properties gets into the original expectation.
*/
public function __get(string $name): Expectation
{
try {
/* @phpstan-ignore-next-line */
$this->original->{$name};
} catch (ExpectationFailedException $e) {
return $this->original;
}
// @phpstan-ignore-next-line
$this->throwExpectationFailedException($name);
}
/**
* Creates a new expectation failed exception with a nice readable message.
*
* @param array<int, mixed> $arguments
*/
private function throwExpectationFailedException(string $name, array $arguments = []): void
{
$exporter = new Exporter();
$toString = function ($argument) use ($exporter): string {
return $exporter->shortenedExport($argument);
};
throw new ExpectationFailedException(sprintf('Expecting %s not %s %s.', $toString($this->original->value), strtolower((string) preg_replace('/(?<!\ )[A-Z]/', ' $0', $name)), implode(' ', array_map(function ($argument) use ($toString): string { return $toString($argument); }, $arguments))));
}
}

View File

@ -7,14 +7,15 @@ namespace Pest\PendingObjects;
use Closure;
use Pest\Factories\TestCaseFactory;
use Pest\Support\Backtrace;
use Pest\Support\HigherOrderCallables;
use Pest\Support\NullClosure;
use Pest\TestSuite;
use SebastianBergmann\Exporter\Exporter;
/**
* @method \Pest\Expectations\Expectation expect(mixed $value)
*
* @internal
*
* @mixin HigherOrderCallables
*/
final class TestCall
{
@ -58,11 +59,15 @@ final class TestCall
/**
* Asserts that the test throws the given `$exceptionClass` when called.
*/
public function throws(string $exceptionClass, string $exceptionMessage = null): TestCall
public function throws(string $exception, string $exceptionMessage = null): TestCall
{
$this->testCaseFactory
->proxies
->add(Backtrace::file(), Backtrace::line(), 'expectException', [$exceptionClass]);
if (class_exists($exception)) {
$this->testCaseFactory
->proxies
->add(Backtrace::file(), Backtrace::line(), 'expectException', [$exception]);
} else {
$exceptionMessage = $exception;
}
if (is_string($exceptionMessage)) {
$this->testCaseFactory
@ -77,11 +82,13 @@ final class TestCall
* Runs the current test multiple times with
* each item of the given `iterable`.
*
* @param \Closure|iterable<int|string, mixed>|string $data
* @param array<\Closure|iterable<int|string, mixed>|string> $data
*/
public function with($data): TestCall
public function with(...$data): TestCall
{
$this->testCaseFactory->dataset = $data;
foreach ($data as $dataset) {
$this->testCaseFactory->datasets[] = $dataset;
}
return $this;
}
@ -141,21 +148,40 @@ final class TestCall
? $conditionOrMessage
: $message;
if ($condition() !== false) {
$this->testCaseFactory
->chains
->add(Backtrace::file(), Backtrace::line(), 'markTestSkipped', [$message]);
}
/** @var callable(): bool $condition */
$condition = $condition->bindTo(null);
$this->testCaseFactory
->chains
->addWhen($condition, Backtrace::file(), Backtrace::line(), 'markTestSkipped', [$message]);
return $this;
}
/**
* Saves the property accessors to be used on the target.
*/
public function __get(string $name): self
{
return $this->addChain($name);
}
/**
* Saves the calls to be used on the target.
*
* @param array<int, mixed> $arguments
*/
public function __call(string $name, array $arguments): self
{
return $this->addChain($name, $arguments);
}
/**
* Add a chain to the test case factory. Omitting the arguments will treat it as a property accessor.
*
* @param array<int, mixed>|null $arguments
*/
private function addChain(string $name, array $arguments = null): self
{
$this->testCaseFactory
->chains
@ -166,7 +192,9 @@ final class TestCall
if ($this->testCaseFactory->description !== null) {
$this->testCaseFactory->description .= ' → ';
}
$this->testCaseFactory->description .= sprintf('%s %s', $name, $exporter->shortenedRecursiveExport($arguments));
$this->testCaseFactory->description .= $arguments === null
? $name
: sprintf('%s %s', $name, $exporter->shortenedRecursiveExport($arguments));
}
return $this;

View File

@ -68,7 +68,7 @@ final class UsesCall
/**
* The directories or file where the
* class or trais should be used.
* class or traits should be used.
*/
public function in(string ...$targets): void
{

View File

@ -6,7 +6,7 @@ namespace Pest;
function version(): string
{
return '1.3.0';
return '1.18.0';
}
function testDirectory(string $file = ''): string

118
src/Plugins/Coverage.php Normal file
View File

@ -0,0 +1,118 @@
<?php
declare(strict_types=1);
namespace Pest\Plugins;
use Pest\Contracts\Plugins\AddsOutput;
use Pest\Contracts\Plugins\HandlesArguments;
use Pest\Support\Str;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @internal
*/
final class Coverage implements AddsOutput, HandlesArguments
{
/**
* @var string
*/
private const COVERAGE_OPTION = 'coverage';
/**
* @var string
*/
private const MIN_OPTION = 'min';
/**
* Whether should show the coverage or not.
*
* @var bool
*/
public $coverage = false;
/**
* The minimum coverage.
*
* @var float
*/
public $coverageMin = 0.0;
/**
* @var OutputInterface
*/
private $output;
public function __construct(OutputInterface $output)
{
$this->output = $output;
}
public function handleArguments(array $originals): array
{
$arguments = array_merge([''], array_values(array_filter($originals, function ($original): bool {
foreach ([self::COVERAGE_OPTION, self::MIN_OPTION] as $option) {
if ($original === sprintf('--%s', $option) || Str::startsWith($original, sprintf('--%s=', $option))) {
return true;
}
}
return false;
})));
$originals = array_flip($originals);
foreach ($arguments as $argument) {
unset($originals[$argument]);
}
$originals = array_flip($originals);
$inputs = [];
$inputs[] = new InputOption(self::COVERAGE_OPTION, null, InputOption::VALUE_NONE);
$inputs[] = new InputOption(self::MIN_OPTION, null, InputOption::VALUE_REQUIRED);
$input = new ArgvInput($arguments, new InputDefinition($inputs));
if ((bool) $input->getOption(self::COVERAGE_OPTION)) {
$this->coverage = true;
$originals[] = '--coverage-php';
$originals[] = \Pest\Support\Coverage::getPath();
}
if ($input->getOption(self::MIN_OPTION) !== null) {
$this->coverageMin = (float) $input->getOption(self::MIN_OPTION);
}
return $originals;
}
/**
* Allows to add custom output after the test suite was executed.
*/
public function addOutput(int $result): int
{
if ($result === 0 && $this->coverage) {
if (!\Pest\Support\Coverage::isAvailable()) {
$this->output->writeln(
"\n <fg=white;bg=red;options=bold> ERROR </> No code coverage driver is available.</>",
);
exit(1);
}
$coverage = \Pest\Support\Coverage::report($this->output);
$result = (int) ($coverage < $this->coverageMin);
if ($result === 1) {
$this->output->writeln(sprintf(
"\n <fg=white;bg=red;options=bold> FAIL </> Code coverage below expected:<fg=red;options=bold> %s %%</>. Minimum:<fg=white;options=bold> %s %%</>.",
number_format($coverage, 1),
number_format($this->coverageMin, 1)
));
}
}
return $result;
}
}

128
src/Plugins/Init.php Normal file
View File

@ -0,0 +1,128 @@
<?php
declare(strict_types=1);
namespace Pest\Plugins;
use Pest\Console\Thanks;
use Pest\Contracts\Plugins\HandlesArguments;
use Pest\TestSuite;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @internal
*/
final class Init implements HandlesArguments
{
/**
* The option the triggers the init job.
*/
private const INIT_OPTION = '--init';
/**
* The files that will be created.
*/
private const STUBS = [
'phpunit.xml' => 'phpunit.xml',
'Pest.php' => 'tests/Pest.php',
'ExampleTest.php' => 'tests/ExampleTest.php',
];
/**
* @var OutputInterface
*/
private $output;
/**
* @var TestSuite
*/
private $testSuite;
/**
* Creates a new Plugin instance.
*/
public function __construct(TestSuite $testSuite, OutputInterface $output)
{
$this->testSuite = $testSuite;
$this->output = $output;
}
public function handleArguments(array $arguments): array
{
if (!array_key_exists(1, $arguments) || $arguments[1] !== self::INIT_OPTION) {
return $arguments;
}
unset($arguments[1]);
$this->init();
return array_values($arguments);
}
private function init(): void
{
$testsBaseDir = "{$this->testSuite->rootPath}/tests";
if (!is_dir($testsBaseDir)) {
if (!mkdir($testsBaseDir) && !is_dir($testsBaseDir)) {
$this->output->writeln(sprintf(
"\n <fg=white;bg=red;options=bold> ERROR </> Directory `%s` was not created.</>",
$testsBaseDir
));
return;
}
$this->output->writeln(
' <fg=black;bg=green;options=bold> DONE </> Created `tests` directory.</>',
);
}
foreach (self::STUBS as $from => $to) {
$fromPath = __DIR__ . "/../../stubs/init/{$from}";
$toPath = "{$this->testSuite->rootPath}/{$to}";
if (file_exists($toPath)) {
$this->output->writeln(sprintf(
' <fg=black;bg=yellow;options=bold> INFO </> File `%s` already exists, skipped.</>',
$to
));
continue;
}
if ($from === 'phpunit.xml' && file_exists($toPath . '.dist')) {
$this->output->writeln(sprintf(
' <fg=black;bg=yellow;options=bold> INFO </> File `%s` already exists, skipped.</>',
$to . '.dist'
));
continue;
}
if (!copy($fromPath, $toPath)) {
$this->output->writeln(sprintf(
'<fg=black;bg=red>[WARNING] Failed to copy stub `%s` to `%s`</>',
$from,
$toPath
));
continue;
}
$this->output->writeln(sprintf(
' <fg=black;bg=green;options=bold> DONE </> Created `%s` file.</>',
$to
));
}
$this->output->writeln(
"\n <fg=black;bg=green;options=bold> DONE </> Pest initialised.</>\n",
);
(new Thanks($this->output))();
exit(0);
}
}

View File

@ -5,11 +5,13 @@ declare(strict_types=1);
namespace Pest\Repositories;
use Closure;
use Pest\Exceptions\DatasetMissing;
use Pest\Exceptions\ShouldNotHappen;
use Pest\Exceptions\TestAlreadyExist;
use Pest\Exceptions\TestCaseAlreadyInUse;
use Pest\Exceptions\TestCaseClassOrTraitNotFound;
use Pest\Factories\TestCaseFactory;
use Pest\Support\Reflection;
use Pest\Support\Str;
use Pest\TestSuite;
use PHPUnit\Framework\TestCase;
@ -19,6 +21,11 @@ use PHPUnit\Framework\TestCase;
*/
final class TestRepository
{
/**
* @var non-empty-string
*/
private const SEPARATOR = '>>>';
/**
* @var array<string, TestCaseFactory>
*/
@ -37,6 +44,20 @@ final class TestRepository
return count($this->state);
}
/**
* Returns the filename of each test that should be executed in the suite.
*
* @return array<int, string>
*/
public function getFilenames(): array
{
$testsWithOnly = $this->testsUsingOnly();
return array_values(array_map(function (TestCaseFactory $factory): string {
return $factory->filename;
}, count($testsWithOnly) > 0 ? $testsWithOnly : $this->state));
}
/**
* Calls the given callable foreach test case.
*/
@ -50,7 +71,7 @@ final class TestRepository
[$classOrTraits, $groups, $hooks] = $uses;
$setClassName = function (TestCaseFactory $testCase, string $key) use ($path, $classOrTraits, $groups, $startsWith, $hooks): void {
[$filename] = explode('@', $key);
[$filename] = explode(self::SEPARATOR, $key);
if ((!is_dir($path) && $filename === $path) || (is_dir($path) && $startsWith($filename, $path))) {
foreach ($classOrTraits as $class) { /** @var string $class */
@ -78,9 +99,7 @@ final class TestRepository
}
}
$onlyState = array_filter($this->state, function ($testFactory): bool {
return $testFactory->only;
});
$onlyState = $this->testsUsingOnly();
$state = count($onlyState) > 0 ? $onlyState : $this->state;
@ -93,6 +112,18 @@ final class TestRepository
}
}
/**
* Return all tests that have called the only method.
*
* @return array<TestCaseFactory>
*/
private function testsUsingOnly(): array
{
return array_filter($this->state, function ($testFactory): bool {
return $testFactory->only;
});
}
/**
* Uses the given `$testCaseClass` on the given `$paths`.
*
@ -131,10 +162,18 @@ final class TestRepository
throw ShouldNotHappen::fromMessage('Trying to create a test without description.');
}
if (array_key_exists(sprintf('%s@%s', $test->filename, $test->description), $this->state)) {
if (array_key_exists(sprintf('%s%s%s', $test->filename, self::SEPARATOR, $test->description), $this->state)) {
throw new TestAlreadyExist($test->filename, $test->description);
}
$this->state[sprintf('%s@%s', $test->filename, $test->description)] = $test;
if (!$test->receivesArguments()) {
$arguments = Reflection::getFunctionArguments($test->test);
if (count($arguments) > 0) {
throw new DatasetMissing($test->filename, $test->description, $arguments);
}
}
$this->state[sprintf('%s%s%s', $test->filename, self::SEPARATOR, $test->description)] = $test;
}
}

68
src/Support/Arr.php Normal file
View File

@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace Pest\Support;
/**
* Credits: most of this class methods and implementations
* belongs to the Arr helper of laravel/framework project
* (https://github.com/laravel/framework).
*
* @internal
*/
final class Arr
{
/**
* @param array<mixed> $array
* @param string|int $key
*/
public static function has(array $array, $key): bool
{
$key = (string) $key;
if (array_key_exists($key, $array)) {
return true;
}
foreach (explode('.', $key) as $segment) {
if (is_array($array) && array_key_exists($segment, $array)) {
$array = $array[$segment];
} else {
return false;
}
}
return true;
}
/**
* @param array<mixed> $array
* @param string|int $key
* @param null $default
*
* @return array|mixed|null
*/
public static function get(array $array, $key, $default = null)
{
$key = (string) $key;
if (array_key_exists($key, $array)) {
return $array[$key];
}
if (strpos($key, '.') === false) {
return $array[$key] ?? $default;
}
foreach (explode('.', $key) as $segment) {
if (is_array($array) && array_key_exists($segment, $array)) {
$array = $array[$segment];
} else {
return $default;
}
}
return $array;
}
}

169
src/Support/Coverage.php Normal file
View File

@ -0,0 +1,169 @@
<?php
declare(strict_types=1);
namespace Pest\Support;
use Pest\Exceptions\ShouldNotHappen;
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Node\Directory;
use SebastianBergmann\CodeCoverage\Node\File;
use SebastianBergmann\Environment\Runtime;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Terminal;
/**
* @internal
*/
final class Coverage
{
/**
* Returns the coverage path.
*/
public static function getPath(): string
{
return implode(DIRECTORY_SEPARATOR, [
dirname(__DIR__, 2),
'.temp',
'coverage.php',
]);
}
/**
* Runs true there is any code
* coverage driver available.
*/
public static function isAvailable(): bool
{
return (new Runtime())->canCollectCodeCoverage();
}
/**
* Reports the code coverage report to the
* console and returns the result in float.
*/
public static function report(OutputInterface $output): float
{
if (!file_exists($reportPath = self::getPath())) {
throw ShouldNotHappen::fromMessage(sprintf('Coverage not found in path: %s.', $reportPath));
}
/** @var CodeCoverage $codeCoverage */
$codeCoverage = require $reportPath;
unlink($reportPath);
$totalWidth = (new Terminal())->getWidth();
$dottedLineLength = $totalWidth <= 70 ? $totalWidth : 70;
$totalCoverage = $codeCoverage->getReport()->percentageOfExecutedLines();
$output->writeln(
sprintf(
' <fg=white;options=bold>Cov: </><fg=default>%s</>',
$totalCoverage->asString()
)
);
$output->writeln('');
/** @var Directory<File|Directory> $report */
$report = $codeCoverage->getReport();
foreach ($report->getIterator() as $file) {
if (!$file instanceof File) {
continue;
}
$dirname = dirname($file->id());
$basename = basename($file->id(), '.php');
$name = $dirname === '.' ? $basename : implode(DIRECTORY_SEPARATOR, [
$dirname,
$basename,
]);
$rawName = $dirname === '.' ? $basename : implode(DIRECTORY_SEPARATOR, [
$dirname,
$basename,
]);
$linesExecutedTakenSize = 0;
if ($file->percentageOfExecutedLines()->asString() != '0.00%') {
$linesExecutedTakenSize = strlen($uncoveredLines = trim(implode(', ', self::getMissingCoverage($file)))) + 1;
$name .= sprintf(' <fg=red>%s</>', $uncoveredLines);
}
$percentage = $file->numberOfExecutableLines() === 0
? '100.0'
: number_format($file->percentageOfExecutedLines()->asFloat(), 1, '.', '');
$takenSize = strlen($rawName . $percentage) + 4 + $linesExecutedTakenSize; // adding 3 space and percent sign
$percentage = sprintf(
'<fg=%s>%s</>',
$percentage === '100.0' ? 'green' : ($percentage === '0.0' ? 'red' : 'yellow'),
$percentage
);
$output->writeln(sprintf(
' %s %s %s %%',
$name,
str_repeat('.', max($dottedLineLength - $takenSize, 1)),
$percentage
));
}
return $totalCoverage->asFloat();
}
/**
* Generates an array of missing coverage on the following format:.
*
* ```
* ['11', '20..25', '50', '60..80'];
* ```
*
* @param File $file
*
* @return array<int, string>
*/
public static function getMissingCoverage($file): array
{
$shouldBeNewLine = true;
$eachLine = function (array $array, array $tests, int $line) use (&$shouldBeNewLine): array {
if (count($tests) > 0) {
$shouldBeNewLine = true;
return $array;
}
if ($shouldBeNewLine) {
$array[] = (string) $line;
$shouldBeNewLine = false;
return $array;
}
$lastKey = count($array) - 1;
if (array_key_exists($lastKey, $array) && strpos($array[$lastKey], '..') !== false) {
[$from] = explode('..', $array[$lastKey]);
$array[$lastKey] = $line > $from ? sprintf('%s..%s', $from, $line) : sprintf('%s..%s', $line, $from);
return $array;
}
$array[$lastKey] = sprintf('%s..%s', $array[$lastKey], $line);
return $array;
};
$array = [];
foreach (array_filter($file->lineCoverageData(), 'is_array') as $line => $tests) {
$array = $eachLine($array, $tests, $line);
}
return $array;
}
}

View File

@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Pest\Support;
use Closure;
use ReflectionProperty;
use Throwable;
/**
@ -36,4 +37,30 @@ final class ExceptionTrace
throw $throwable;
}
}
/**
* Removes any item from the stack trace referencing Pest so as not to
* crowd the error log for the end user.
*/
public static function removePestReferences(Throwable $t): void
{
if (!property_exists($t, 'serializableTrace')) {
return;
}
$property = new ReflectionProperty($t, 'serializableTrace');
$property->setAccessible(true);
$trace = $property->getValue($t);
$cleanedTrace = [];
foreach ($trace as $item) {
if (key_exists('file', $item) && mb_strpos($item['file'], 'vendor/pestphp/pest/') > 0) {
continue;
}
$cleanedTrace[] = $item;
}
$property->setValue($t, $cleanedTrace);
}
}

View File

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Pest\Support;
use Closure;
final class Extendable
{
/**
* The extendable class.
*
* @var string
*/
private $extendableClass;
/**
* Creates a new extendable instance.
*/
public function __construct(string $extendableClass)
{
$this->extendableClass = $extendableClass;
}
/**
* Register a custom extend.
*/
public function extend(string $name, Closure $extend): void
{
$this->extendableClass::extend($name, $extend);
}
}

View File

@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Pest\Support;
use Closure;
use Pest\Expectation;
use Pest\PendingObjects\TestCall;
use PHPUnit\Framework\TestCase;
/**
* @internal
*/
final class HigherOrderCallables
{
/**
* @var object
*/
private $target;
public function __construct(object $target)
{
$this->target = $target;
}
/**
* @template TValue
*
* Create a new expectation. Callable values will be executed prior to returning the new expectation.
*
* @param callable|TValue $value
*
* @return Expectation<TValue>
*/
public function expect($value)
{
return new Expectation($value instanceof Closure ? Reflection::bindCallableWithData($value) : $value);
}
/**
* @template TValue
*
* Create a new expectation. Callable values will be executed prior to returning the new expectation.
*
* @param callable|TValue $value
*
* @return Expectation<TValue>
*/
public function and($value)
{
return $this->expect($value);
}
/**
* Tap into the test case to perform an action and return the test case.
*
* @return TestCall|TestCase|object
*/
public function tap(callable $callable)
{
Reflection::bindCallableWithData($callable);
return $this->target;
}
}

View File

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Pest\Support;
use Closure;
use ReflectionClass;
use Throwable;
@ -33,33 +34,40 @@ final class HigherOrderMessage
public $line;
/**
* The method name.
* The method or property name to access.
*
* @readonly
*
* @var string
*/
public $methodName;
public $name;
/**
* The arguments.
*
* @var array<int, mixed>
* @var array<int, mixed>|null
*
* @readonly
*/
public $arguments;
/**
* An optional condition that will determine if the message will be executed.
*
* @var callable(): bool|null
*/
public $condition = null;
/**
* Creates a new higher order message.
*
* @param array<int, mixed> $arguments
* @param array<int, mixed>|null $arguments
*/
public function __construct(string $filename, int $line, string $methodName, array $arguments)
public function __construct(string $filename, int $line, string $methodName, $arguments)
{
$this->filename = $filename;
$this->line = $line;
$this->methodName = $methodName;
$this->name = $methodName;
$this->arguments = $arguments;
}
@ -70,24 +78,58 @@ final class HigherOrderMessage
*/
public function call(object $target)
{
/* @phpstan-ignore-next-line */
if (is_callable($this->condition) && call_user_func(Closure::bind($this->condition, $target)) === false) {
return $target;
}
if ($this->hasHigherOrderCallable()) {
/* @phpstan-ignore-next-line */
return (new HigherOrderCallables($target))->{$this->name}(...$this->arguments);
}
try {
return Reflection::call($target, $this->methodName, $this->arguments);
return is_array($this->arguments)
? Reflection::call($target, $this->name, $this->arguments)
: $target->{$this->name}; /* @phpstan-ignore-line */
} catch (Throwable $throwable) {
Reflection::setPropertyValue($throwable, 'file', $this->filename);
Reflection::setPropertyValue($throwable, 'line', $this->line);
if ($throwable->getMessage() === self::getUndefinedMethodMessage($target, $this->methodName)) {
if ($throwable->getMessage() === self::getUndefinedMethodMessage($target, $this->name)) {
/** @var ReflectionClass $reflection */
$reflection = new ReflectionClass($target);
/* @phpstan-ignore-next-line */
$reflection = $reflection->getParentClass() ?: $reflection;
Reflection::setPropertyValue($throwable, 'message', sprintf('Call to undefined method %s::%s()', $reflection->getName(), $this->methodName));
Reflection::setPropertyValue($throwable, 'message', sprintf('Call to undefined method %s::%s()', $reflection->getName(), $this->name));
}
throw $throwable;
}
}
/**
* Indicates that this message should only be called when the given condition is true.
*
* @param callable(): bool $condition
*/
public function when(callable $condition): self
{
$this->condition = $condition;
return $this;
}
/**
* Determines whether or not there exists a higher order callable with the message name.
*
* @return bool
*/
private function hasHigherOrderCallable()
{
return in_array($this->name, get_class_methods(HigherOrderCallables::class), true);
}
private static function getUndefinedMethodMessage(object $target, string $methodName): string
{
if (\PHP_MAJOR_VERSION >= 8) {

View File

@ -17,11 +17,21 @@ final class HigherOrderMessageCollection
/**
* Adds a new higher order message to the collection.
*
* @param array<int, mixed> $arguments
* @param array<int, mixed>|null $arguments
*/
public function add(string $filename, int $line, string $methodName, array $arguments): void
public function add(string $filename, int $line, string $name, array $arguments = null): void
{
$this->messages[] = new HigherOrderMessage($filename, $line, $methodName, $arguments);
$this->messages[] = new HigherOrderMessage($filename, $line, $name, $arguments);
}
/**
* Adds a new higher order message to the collection if the callable condition is does not return false.
*
* @param array<int, mixed>|null $arguments
*/
public function addWhen(callable $condition, string $filename, int $line, string $name, array $arguments = null): void
{
$this->messages[] = (new HigherOrderMessage($filename, $line, $name, $arguments))->when($condition);
}
/**
@ -43,4 +53,20 @@ final class HigherOrderMessageCollection
$message->call($target);
}
}
/**
* Count the number of messages with the given name.
*
* @param string $name A higher order message name (usually a method name)
*/
public function count(string $name): int
{
return array_reduce(
$this->messages,
static function (int $total, HigherOrderMessage $message) use ($name): int {
return $total + (int) ($name === $message->name);
},
0,
);
}
}

View File

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Pest\Support;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use Throwable;
@ -17,16 +18,14 @@ final class HigherOrderTapProxy
/**
* The target being tapped.
*
* @var mixed
* @var TestCase
*/
public $target;
/**
* Create a new tap proxy instance.
*
* @param mixed $target
*/
public function __construct($target)
public function __construct(TestCase $target)
{
$this->target = $target;
}

View File

@ -12,6 +12,7 @@ use ReflectionException;
use ReflectionFunction;
use ReflectionNamedType;
use ReflectionParameter;
use ReflectionUnionType;
/**
* @internal
@ -41,15 +42,40 @@ final class Reflection
}
if (is_callable($method)) {
return Closure::fromCallable($method)->bindTo(
TestSuite::getInstance()->test
)(...$args);
return static::bindCallable($method, $args);
}
throw $exception;
}
}
/**
* Bind a callable to the TestCase and return the result.
*
* @param array<int, mixed> $args
*
* @return mixed
*/
public static function bindCallable(callable $callable, array $args = [])
{
return Closure::fromCallable($callable)->bindTo(TestSuite::getInstance()->test)(...$args);
}
/**
* Bind a callable to the TestCase and return the result,
* passing in the current dataset values as arguments.
*
* @return mixed
*/
public static function bindCallableWithData(callable $callable)
{
$test = TestSuite::getInstance()->test;
return $test === null
? static::bindCallable($callable)
: Closure::fromCallable($callable)->bindTo($test)(...$test->getProvidedData());
}
/**
* Infers the file name from the given closure.
*/
@ -84,10 +110,6 @@ final class Reflection
}
}
if ($reflectionProperty === null) {
throw ShouldNotHappen::fromMessage('Reflection property not found.');
}
$reflectionProperty->setAccessible(true);
return $reflectionProperty->getValue($object);
@ -118,10 +140,6 @@ final class Reflection
}
}
if ($reflectionProperty === null) {
throw ShouldNotHappen::fromMessage('Reflection property not found.');
}
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($object, $value);
}
@ -153,4 +171,37 @@ final class Reflection
return $name;
}
/**
* Receive a map of function argument names to their types.
*
* @return array<string, string>
*/
public static function getFunctionArguments(Closure $function): array
{
$parameters = (new ReflectionFunction($function))->getParameters();
$arguments = [];
foreach ($parameters as $parameter) {
/** @var ReflectionNamedType|ReflectionUnionType|null $types */
$types = ($parameter->hasType()) ? $parameter->getType() : null;
if (is_null($types)) {
$arguments[$parameter->getName()] = 'mixed';
continue;
}
$arguments[$parameter->getName()] = implode('|', array_map(
static function (ReflectionNamedType $type): string {
return $type->getName();
},
($types instanceof ReflectionNamedType)
? [$types] // NOTE: normalize as list of to handle unions
: $types->getTypes(),
));
}
return $arguments;
}
}

View File

@ -1,5 +1,5 @@
<?php
test('{name}', function () {
assertTrue(true);
expect(true)->toBeTrue();
});

View File

@ -0,0 +1,5 @@
<?php
test('example', function () {
expect(true)->toBeTrue();
});

45
stubs/init/Pest.php Normal file
View File

@ -0,0 +1,45 @@
<?php
/*
|--------------------------------------------------------------------------
| Test Case
|--------------------------------------------------------------------------
|
| The closure you provide to your test functions is always bound to a specific PHPUnit test
| case class. By default, that class is "PHPUnit\Framework\TestCase". Of course, you may
| need to change it using the "uses()" function to bind a different classes or traits.
|
*/
// uses(Tests\TestCase::class)->in('Feature');
/*
|--------------------------------------------------------------------------
| Expectations
|--------------------------------------------------------------------------
|
| When you're writing tests, you often need to check that values meet certain conditions. The
| "expect()" function gives you access to a set of "expectations" methods that you can use
| to assert different things. Of course, you may extend the Expectation API at any time.
|
*/
expect()->extend('toBeOne', function () {
return $this->toBe(1);
});
/*
|--------------------------------------------------------------------------
| Functions
|--------------------------------------------------------------------------
|
| While Pest is very powerful out-of-the-box, you may have some testing code specific to your
| project that you don't want to repeat in every file. Here you can also expose helpers as
| global functions to help you to reduce the number of lines of code in your test files.
|
*/
function something()
{
// ..
}

18
stubs/init/phpunit.xml Normal file
View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Test Suite">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<coverage processUncoveredFiles="true">
<include>
<directory suffix=".php">./app</directory>
<directory suffix=".php">./src</directory>
</include>
</coverage>
</phpunit>

View File

@ -17,6 +17,12 @@
✓ it gets executed before each test
✓ it gets executed before each test once again
PASS Tests\Features\Coverage
✓ it has plugin
✓ it adds coverage if --coverage exist
✓ it adds coverage if --min exist
✓ it generates coverage based on file input
PASS Tests\Features\Datasets
✓ it throws exception if dataset does not exist
✓ it throws exception if dataset already exist
@ -51,11 +57,429 @@
✓ it creates unique test case names with ('Name 2', Pest\Plugin Object (), true)
✓ it creates unique test case names with ('Name 1', Pest\Plugin Object (), true) #3
✓ it creates unique test case names - count
✓ lazy multiple datasets with (1) / (3)
✓ lazy multiple datasets with (1) / (4)
✓ lazy multiple datasets with (2) / (3)
✓ lazy multiple datasets with (2) / (4)
✓ lazy multiple datasets did the job right
✓ eager multiple datasets with (1) / (3)
✓ eager multiple datasets with (1) / (4)
✓ eager multiple datasets with (2) / (3)
✓ eager multiple datasets with (2) / (4)
✓ eager multiple datasets did the job right
✓ lazy registered multiple datasets with (1) / (1)
✓ lazy registered multiple datasets with (1) / (2)
✓ lazy registered multiple datasets with (2) / (1)
✓ lazy registered multiple datasets with (2) / (2)
✓ lazy registered multiple datasets did the job right
✓ eager registered multiple datasets with (1) / (1)
✓ eager registered multiple datasets with (1) / (2)
✓ eager registered multiple datasets with (2) / (1)
✓ eager registered multiple datasets with (2) / (2)
✓ eager registered multiple datasets did the job right
✓ eager wrapped registered multiple datasets with (1) / (1)
✓ eager wrapped registered multiple datasets with (1) / (2)
✓ eager wrapped registered multiple datasets with (2) / (1)
✓ eager wrapped registered multiple datasets with (2) / (2)
✓ eager wrapped registered multiple datasets did the job right
✓ named multiple datasets with data set "one" / data set "three"
✓ named multiple datasets with data set "one" / data set "four"
✓ named multiple datasets with data set "two" / data set "three"
✓ named multiple datasets with data set "two" / data set "four"
✓ named multiple datasets did the job right
✓ more than two datasets with (1) / (3) / (5)
✓ more than two datasets with (1) / (3) / (6)
✓ more than two datasets with (1) / (4) / (5)
✓ more than two datasets with (1) / (4) / (6)
✓ more than two datasets with (2) / (3) / (5)
✓ more than two datasets with (2) / (3) / (6)
✓ more than two datasets with (2) / (4) / (5)
✓ more than two datasets with (2) / (4) / (6)
✓ more than two datasets did the job right
✓ it can resolve a dataset after the test case is available with (Closure Object (...))
✓ it can resolve a dataset after the test case is available with shared yield sets with (Closure Object (...)) #1
✓ it can resolve a dataset after the test case is available with shared yield sets with (Closure Object (...)) #2
✓ it can resolve a dataset after the test case is available with shared array sets with (Closure Object (...)) #1
✓ it can resolve a dataset after the test case is available with shared array sets with (Closure Object (...)) #2
PASS Tests\Features\Exceptions
✓ it gives access the the underlying expectException
✓ it catch exceptions
✓ it catch exceptions and messages
✓ it can just define the message
PASS Tests\Features\Expect\HigherOrder\methods
✓ it can access methods
✓ it can access multiple methods
✓ it works with not
✓ it can accept arguments
✓ it works with each
✓ it works inside of each
✓ it works with sequence
✓ it can compose complex expectations
✓ it can handle nested method calls
✓ it works with higher order tests
PASS Tests\Features\Expect\HigherOrder\methodsAndProperties
✓ it can access methods and properties
✓ it can handle nested methods and properties
✓ it works with higher order tests
✓ it can start a new higher order expectation using the and syntax
✓ it can start a new higher order expectation using the and syntax in higher order tests
PASS Tests\Features\Expect\HigherOrder\properties
✓ it allows properties to be accessed from the value
✓ it can access multiple properties from the value
✓ it works with not
✓ it works with each
✓ it works inside of each
✓ it works with sequence
✓ it can compose complex expectations
✓ it works with objects
✓ it works with nested properties
✓ it works with higher order tests
PASS Tests\Features\Expect\each
✓ an exception is thrown if the the type is not iterable
✓ it expects on each item
✓ it chains expectations on each item
✓ opposite expectations on each item
✓ chained opposite and non-opposite expectations
✓ it can add expectations via "and"
✓ it accepts callables
PASS Tests\Features\Expect\extend
✓ it macros true is true
✓ it macros false is not true
✓ it macros true is true with argument
✓ it macros false is not true with argument
PASS Tests\Features\Expect\json
✓ it properly parses json string
✓ fails with broken json string
PASS Tests\Features\Expect\not
✓ not property calls
PASS Tests\Features\Expect\ray
✓ ray calls do not fail when ray is not installed
PASS Tests\Features\Expect\sequence
✓ an exception is thrown if the the type is not iterable
✓ allows for sequences of checks to be run on iterable data
✓ loops back to the start if it runs out of sequence items
✓ it works if the number of items in the iterable is smaller than the number of expectations
✓ it works with associative arrays
✓ it can be passed non-callable values
✓ it can be passed a mixture of value types
PASS Tests\Features\Expect\toBe
✓ strict comparisons
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeArray
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeBool
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeCallable
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeDirectory
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeEmpty
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeFalse
✓ strict comparisons
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeFalsy
✓ passes as falsy with (false)
✓ passes as falsy with ('')
✓ passes as falsy with (null)
✓ passes as falsy with (0)
✓ passes as falsy with ('0')
✓ passes as not falsy with (true)
✓ passes as not falsy with (1) #1
✓ passes as not falsy with ('false')
✓ passes as not falsy with (1) #2
✓ passes as not falsy with (-1)
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeFile
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeFloat
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeGreatherThan
✓ passes
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeGreatherThanOrEqual
✓ passes
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeIn
✓ passes
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeInfinite
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeInstanceOf
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeInt
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeIterable
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeJson
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeLessThan
✓ passes
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeLessThanOrEqual
✓ passes
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeNAN
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeNull
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeNumeric
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeObject
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeReadableDirectory
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeReadableFile
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeResource
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeScalar
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeString
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeTrue
✓ strict comparisons
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeTruthy
✓ passes as truthy with (true)
✓ passes as truthy with (1) #1
✓ passes as truthy with ('false')
✓ passes as truthy with (1) #2
✓ passes as truthy with (-1)
✓ passes as not truthy with (false)
✓ passes as not truthy with ('')
✓ passes as not truthy with (null)
✓ passes as not truthy with (0)
✓ passes as not truthy with ('0')
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeWritableDirectory
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeWritableFile
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toContain
✓ passes strings
✓ passes strings with multiple needles
✓ passes arrays
✓ passes arrays with multiple needles
✓ passes with array needles
✓ failures
✓ failures with multiple needles (all failing)
✓ failures with multiple needles (some failing)
✓ not failures
✓ not failures with multiple needles (all failing)
✓ not failures with multiple needles (some failing)
PASS Tests\Features\Expect\toEndWith
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toEqual
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toEqualCanonicalizing
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toEqualWithDelta
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toHaveCount
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toHaveKey
✓ pass
✓ pass with nested key
✓ pass with plain key with dots
✓ pass with value check
✓ pass with value check and nested key
✓ pass with value check and plain key with dots
✓ failures
✓ failures with nested key
✓ failures with plain key with dots
✓ fails with wrong value
✓ fails with wrong value and nested key
✓ fails with wrong value and plain key with dots
✓ not failures
✓ not failures with nested key
✓ not failures with plain key with dots
✓ not failures with correct value
✓ not failures with correct value and with nested key
✓ not failures with correct value and with plain key with dots
PASS Tests\Features\Expect\toHaveKeys
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toHaveLength
✓ it passes with ('Fortaleza')
✓ it passes with ('Sollefteå')
✓ it passes with ('Ιεράπετρα')
✓ it passes with (stdClass Object (...))
✓ it passes with (Illuminate\Support\Collection Object (...))
✓ it passes with array
✓ it passes with *not*
✓ it properly fails with *not*
✓ it fails with (1)
✓ it fails with (1.5)
✓ it fails with (true)
✓ it fails with (null)
PASS Tests\Features\Expect\toHaveProperties
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toHaveProperty
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toMatch
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toMatchArray
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toMatchConstraint
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toMatchObject
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toStartWith
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toThrow
✓ passes
✓ failures 1
✓ failures 2
✓ failures 3
✓ failures 4
✓ failures 5
✓ failures 6
✓ failures 7
✓ not failures
✓ closure missing parameter
✓ closure missing type-hint
PASS Tests\Features\Helpers
✓ it can set/get properties on $this
@ -68,6 +492,22 @@
PASS Tests\Features\HigherOrderTests
✓ it proxies calls to object
✓ it is capable doing multiple assertions
✓ it resolves expect callables correctly
✓ does not treat method names as callables
✓ it can tap into the test
✓ it can pass datasets into the expect callables with (1, 2, 3)
✓ it can pass datasets into the tap callable with (1, 2, 3)
✓ it can pass shared datasets into callables with (1)
✓ it can pass shared datasets into callables with (2)
WARN Tests\Features\Incompleted
… incompleted
… it is incompleted
… it is incompleted even with method calls like skip
… it is incompleted even with method calls like group
✓ it is not incompleted because of expect
✓ it is not incompleted because of assert
✓ it is not incompleted because of test with assertions
PASS Tests\Features\It
✓ it is a test
@ -78,6 +518,7 @@
✓ it will throw exception from call if no macro exists
PASS Tests\Features\PendingHigherOrderTests
✓ get 'foo'
✓ get 'foo' → get 'bar' → expect true → toBeTrue
✓ get 'foo' → expect true → toBeTrue
@ -90,6 +531,8 @@
✓ it do not skips with falsy closure condition
- it skips with condition and message → skipped because foo
- it skips when skip after assertion
- it can use something in the test case as a condition → This test was skipped
- it can user higher order callables and skip
PASS Tests\Features\Test
✓ a test
@ -103,12 +546,14 @@
PASS Tests\Hooks\AfterAllTest
✓ global afterAll execution order
✓ it only gets called once per file
PASS Tests\Hooks\AfterEachTest
✓ global afterEach execution order
PASS Tests\Hooks\BeforeAllTest
✓ global beforeAll execution order
✓ it only gets called once per file
PASS Tests\Hooks\BeforeEachTest
✓ global beforeEach execution order
@ -122,6 +567,10 @@
PASS Tests\PHPUnit\CustomAffixes\AdditionalFileExtensionspec
✓ it runs file names like `AdditionalFileExtension.spec.php`
PASS Tests\PHPUnit\CustomAffixes\FolderWithAn\ExampleTest
✓ custom traits can be used
✓ trait applied in this file
PASS Tests\PHPUnit\CustomAffixes\ManyExtensionsclasstest
✓ it runs file names like `ManyExtensions.class.test.php`
@ -170,6 +619,9 @@
PASS Tests\Unit\Datasets
✓ it show only the names of named datasets in their description
✓ it show the actual dataset of non-named datasets in their description
✓ it show only the names of multiple named datasets in their description
✓ it show the actual dataset of multiple non-named datasets in their description
✓ it show the correct description for mixed named and not-named datasets
PASS Tests\Unit\Plugins\Version
✓ it outputs the version when --version is used
@ -193,10 +645,16 @@
PASS Tests\Unit\TestSuite
✓ it does not allow to add the same test description twice
✓ it alerts users about tests with arguments but no input
✓ it can return an array of all test suite filenames
✓ it can filter the test suite filenames to those with the only method
PASS Tests\Visual\Help
✓ visual snapshot of help command output
PASS Tests\Visual\JUnit
✓ it is can successfully call all public methods
PASS Tests\Visual\SingleTestOrDirectory
✓ allows to run a single test
✓ allows to run a directory
@ -206,6 +664,9 @@
WARN Tests\Visual\Success
- visual snapshot of test suite on success
PASS Tests\Visual\TeamCity
✓ it is can successfully call all public methods
PASS Tests\Features\Depends
✓ first
✓ second
@ -220,5 +681,5 @@
✓ it is a test
✓ it uses correct parent class
Tests: 7 skipped, 120 passed
Tests: 4 incompleted, 9 skipped, 447 passed

11
tests/Datasets/Bound.php Normal file
View File

@ -0,0 +1,11 @@
<?php
dataset('bound.closure', function () {
yield function () { return 1; };
yield function () { return 2; };
});
dataset('bound.array', [
function () { return 1; },
function () { return 2; },
]);

View File

@ -8,11 +8,11 @@ beforeAll(function () use ($foo) {
});
it('gets executed before tests', function () use ($foo) {
expect($foo->bar)->toBe(1);
expect($foo)->bar->toBe(1);
$foo->bar = 'changed';
});
it('do not get executed before each test', function () use ($foo) {
expect($foo->bar)->toBe('changed');
expect($foo)->bar->toBe('changed');
});

View File

@ -0,0 +1,58 @@
<?php
use Pest\Plugins\Coverage as CoveragePlugin;
use Pest\Support\Coverage;
use Pest\TestSuite;
use Symfony\Component\Console\Output\ConsoleOutput;
it('has plugin')->assertTrue(class_exists(CoveragePlugin::class));
it('adds coverage if --coverage exist', function () {
$plugin = new CoveragePlugin(new ConsoleOutput());
$testSuite = TestSuite::getInstance();
expect($plugin->coverage)->toBeFalse();
$arguments = $plugin->handleArguments([]);
expect($arguments)->toEqual([]);
expect($plugin->coverage)->toBeFalse();
$arguments = $plugin->handleArguments(['--coverage']);
expect($arguments)->toEqual(['--coverage-php', Coverage::getPath()]);
expect($plugin->coverage)->toBeTrue();
});
it('adds coverage if --min exist', function () {
$plugin = new CoveragePlugin(new ConsoleOutput());
expect($plugin->coverageMin)->toEqual(0.0);
expect($plugin->coverage)->toBeFalse();
$plugin->handleArguments([]);
expect($plugin->coverageMin)->toEqual(0.0);
$plugin->handleArguments(['--min=2']);
expect($plugin->coverageMin)->toEqual(2.0);
$plugin->handleArguments(['--min=2.4']);
expect($plugin->coverageMin)->toEqual(2.4);
});
it('generates coverage based on file input', function () {
expect(Coverage::getMissingCoverage(new class() {
public function lineCoverageData(): array
{
return [
1 => ['foo'],
2 => ['bar'],
4 => [],
5 => [],
6 => [],
7 => null,
100 => null,
101 => ['foo'],
102 => [],
];
}
}))->toEqual([
'4..6', '102',
]);
});

View File

@ -5,6 +5,10 @@ use Pest\Exceptions\DatasetAlreadyExist;
use Pest\Exceptions\DatasetDoesNotExist;
use Pest\Plugin;
beforeEach(function () {
$this->foo = 'bar';
});
it('throws exception if dataset does not exist', function () {
$this->expectException(DatasetDoesNotExist::class);
$this->expectExceptionMessage("A dataset with the name `first` does not exist. You can create it using `dataset('first', ['a', 'b']);`.");
@ -137,3 +141,103 @@ it('creates unique test case names', function (string $name, Plugin $plugin, boo
it('creates unique test case names - count', function () use (&$counter) {
expect($counter)->toBe(6);
});
$datasets_a = [[1], [2]];
$datasets_b = [[3], [4]];
test('lazy multiple datasets', function ($text_a, $text_b) use ($state, $datasets_a, $datasets_b) {
$state->text .= $text_a . $text_b;
expect($datasets_a)->toContain([$text_a]);
expect($datasets_b)->toContain([$text_b]);
})->with($datasets_a, $datasets_b);
test('lazy multiple datasets did the job right', function () use ($state) {
expect($state->text)->toBe('12121212121213142324');
});
$state->text = '';
test('eager multiple datasets', function ($text_a, $text_b) use ($state, $datasets_a, $datasets_b) {
$state->text .= $text_a . $text_b;
expect($datasets_a)->toContain([$text_a]);
expect($datasets_b)->toContain([$text_b]);
})->with(function () use ($datasets_a) {
return $datasets_a;
})->with(function () use ($datasets_b) {
return $datasets_b;
});
test('eager multiple datasets did the job right', function () use ($state) {
expect($state->text)->toBe('1212121212121314232413142324');
});
test('lazy registered multiple datasets', function ($text_a, $text_b) use ($state, $datasets) {
$state->text .= $text_a . $text_b;
expect($datasets)->toContain([$text_a]);
expect($datasets)->toContain([$text_b]);
})->with('numbers.array')->with('numbers.array');
test('lazy registered multiple datasets did the job right', function () use ($state) {
expect($state->text)->toBe('121212121212131423241314232411122122');
});
test('eager registered multiple datasets', function ($text_a, $text_b) use ($state, $datasets) {
$state->text .= $text_a . $text_b;
expect($datasets)->toContain([$text_a]);
expect($datasets)->toContain([$text_b]);
})->with('numbers.array')->with('numbers.closure');
test('eager registered multiple datasets did the job right', function () use ($state) {
expect($state->text)->toBe('12121212121213142324131423241112212211122122');
});
test('eager wrapped registered multiple datasets', function ($text_a, $text_b) use ($state, $datasets) {
$state->text .= $text_a . $text_b;
expect($datasets)->toContain([$text_a]);
expect($datasets)->toContain([$text_b]);
})->with('numbers.closure.wrapped')->with('numbers.closure');
test('eager wrapped registered multiple datasets did the job right', function () use ($state) {
expect($state->text)->toBe('1212121212121314232413142324111221221112212211122122');
});
test('named multiple datasets', function ($text_a, $text_b) use ($state, $datasets_a, $datasets_b) {
$state->text .= $text_a . $text_b;
expect($datasets_a)->toContain([$text_a]);
expect($datasets_b)->toContain([$text_b]);
})->with([
'one' => [1],
'two' => [2],
])->with([
'three' => [3],
'four' => [4],
]);
test('named multiple datasets did the job right', function () use ($state) {
expect($state->text)->toBe('121212121212131423241314232411122122111221221112212213142324');
});
test('more than two datasets', function ($text_a, $text_b, $text_c) use ($state, $datasets_a, $datasets_b) {
$state->text .= $text_a . $text_b . $text_c;
expect($datasets_a)->toContain([$text_a]);
expect($datasets_b)->toContain([$text_b]);
expect([5, 6])->toContain($text_c);
})->with($datasets_a, $datasets_b)->with([5, 6]);
test('more than two datasets did the job right', function () use ($state) {
expect($state->text)->toBe('121212121212131423241314232411122122111221221112212213142324135136145146235236245246');
});
it('can resolve a dataset after the test case is available', function ($result) {
expect($result)->toBe('bar');
})->with([
function () { return $this->foo; },
]);
it('can resolve a dataset after the test case is available with shared yield sets', function ($result) {
expect($result)->toBeInt()->toBeLessThan(3);
})->with('bound.closure');
it('can resolve a dataset after the test case is available with shared array sets', function ($result) {
expect($result)->toBeInt()->toBeLessThan(3);
})->with('bound.array');

View File

@ -13,3 +13,7 @@ it('catch exceptions', function () {
it('catch exceptions and messages', function () {
throw new Exception('Something bad happened');
})->throws(Exception::class, 'Something bad happened');
it('can just define the message', function () {
throw new Exception('Something bad happened');
})->throws('Something bad happened');

View File

@ -0,0 +1,120 @@
<?php
it('can access methods', function () {
expect(new HasMethods())
->name()->toBeString()->toEqual('Has Methods');
});
it('can access multiple methods', function () {
expect(new HasMethods())
->name()->toBeString()->toEqual('Has Methods')
->quantity()->toBeInt()->toEqual(20);
});
it('works with not', function () {
expect(new HasMethods())
->name()->not->toEqual('world')->toEqual('Has Methods')
->quantity()->toEqual(20)->not()->toEqual('bar')->not->toBeNull;
});
it('can accept arguments', function () {
expect(new HasMethods())
->multiply(5, 4)->toBeInt->toEqual(20);
});
it('works with each', function () {
expect(new HasMethods())
->attributes()->toBeArray->each->not()->toBeNull
->attributes()->each(function ($attribute) {
$attribute->not->toBeNull();
});
});
it('works inside of each', function () {
expect(new HasMethods())
->books()->each(function ($book) {
$book->title->not->toBeNull->cost->toBeGreaterThan(19);
});
});
it('works with sequence', function () {
expect(new HasMethods())
->books()->sequence(
function ($book) { $book->title->toEqual('Foo')->cost->toEqual(20); },
function ($book) { $book->title->toEqual('Bar')->cost->toEqual(30); },
);
});
it('can compose complex expectations', function () {
expect(new HasMethods())
->toBeObject()
->name()->toEqual('Has Methods')->not()->toEqual('bar')
->quantity()->not->toEqual('world')->toEqual(20)->toBeInt
->multiply(3, 4)->not->toBeString->toEqual(12)
->attributes()->toBeArray()
->books()->toBeArray->each->not->toBeEmpty
->books()->sequence(
function ($book) { $book->title->toEqual('Foo')->cost->toEqual(20); },
function ($book) { $book->title->toEqual('Bar')->cost->toEqual(30); },
);
});
it('can handle nested method calls', function () {
expect(new HasMethods())
->newInstance()->newInstance()->name()->toEqual('Has Methods')->toBeString()
->newInstance()->name()->toEqual('Has Methods')->not->toBeInt
->name()->toEqual('Has Methods')
->books()->each->toBeArray();
});
it('works with higher order tests')
->expect(new HasMethods())
->newInstance()->newInstance()->name()->toEqual('Has Methods')->toBeString()
->newInstance()->name()->toEqual('Has Methods')->not->toBeArray
->name()->toEqual('Has Methods')
->books()->each->toBeArray;
class HasMethods
{
public function name()
{
return 'Has Methods';
}
public function quantity()
{
return 20;
}
public function multiply($x, $y)
{
return $x * $y;
}
public function attributes()
{
return [
'name' => $this->name(),
'quantity' => $this->quantity(),
];
}
public function books()
{
return [
[
'title' => 'Foo',
'cost' => 20,
],
[
'title' => 'Bar',
'cost' => 30,
],
];
}
public function newInstance()
{
return new static();
}
}

View File

@ -0,0 +1,91 @@
<?php
it('can access methods and properties', function () {
expect(new HasMethodsAndProperties())
->name->toEqual('Has Methods and Properties')->not()->toEqual('bar')
->multiply(3, 4)->not->toBeString->toEqual(12)
->posts->each(function ($post) {
$post->is_published->toBeTrue;
})->books()->toBeArray()
->posts->toBeArray->each->not->toBeEmpty
->books()->sequence(
function ($book) { $book->title->toEqual('Foo')->cost->toEqual(20); },
function ($book) { $book->title->toEqual('Bar')->cost->toEqual(30); },
);
});
it('can handle nested methods and properties', function () {
expect(new HasMethodsAndProperties())
->meta->foo->bar->toBeString()->toEqual('baz')->not->toBeInt
->newInstance()->meta->foo->toBeArray()
->newInstance()->multiply(2, 2)->toEqual(4)->not->toEqual(5)
->newInstance()->books()->toBeArray();
});
it('works with higher order tests')
->expect(new HasMethodsAndProperties())
->meta->foo->bar->toBeString()->toEqual('baz')->not->toBeInt
->newInstance()->meta->foo->toBeArray
->newInstance()->multiply(2, 2)->toEqual(4)->not->toEqual(5)
->newInstance()->books()->toBeArray();
it('can start a new higher order expectation using the and syntax', function () {
expect(new HasMethodsAndProperties())
->toBeInstanceOf(HasMethodsAndProperties::class)
->meta->toBeArray
->and(['foo' => 'bar'])
->toBeArray()
->foo->toEqual('bar');
expect(static::getCount())->toEqual(4);
});
it('can start a new higher order expectation using the and syntax in higher order tests')
->expect(new HasMethodsAndProperties())
->toBeInstanceOf(HasMethodsAndProperties::class)
->meta->toBeArray
->and(['foo' => 'bar'])
->toBeArray()
->foo->toEqual('bar');
class HasMethodsAndProperties
{
public $name = 'Has Methods and Properties';
public $meta = ['foo' => ['bar' => 'baz']];
public $posts = [
[
'is_published' => true,
'title' => 'Foo',
],
[
'is_published' => true,
'title' => 'Bar',
],
];
public function books()
{
return [
[
'title' => 'Foo',
'cost' => 20,
],
[
'title' => 'Bar',
'cost' => 30,
],
];
}
public function multiply($x, $y)
{
return $x * $y;
}
public function newInstance()
{
return new static();
}
}

View File

@ -0,0 +1,90 @@
<?php
it('allows properties to be accessed from the value', function () {
expect(['foo' => 1])->foo->toBeInt()->toEqual(1);
});
it('can access multiple properties from the value', function () {
expect(['foo' => 'bar', 'hello' => 'world'])
->foo->toBeString()->toEqual('bar')
->hello->toBeString()->toEqual('world');
});
it('works with not', function () {
expect(['foo' => 'bar', 'hello' => 'world'])
->foo->not->not->toEqual('bar')
->foo->not->toEqual('world')->toEqual('bar')
->hello->toEqual('world')->not()->toEqual('bar')->not->toBeNull;
});
it('works with each', function () {
expect(['numbers' => [1, 2, 3, 4], 'words' => ['hey', 'there']])
->numbers->toEqual([1, 2, 3, 4])->each->toBeInt->toBeLessThan(5)
->words->each(function ($word) {
$word->toBeString()->not->toBeInt();
});
});
it('works inside of each', function () {
expect(['books' => [['title' => 'Foo', 'cost' => 20], ['title' => 'Bar', 'cost' => 30]]])
->books->each(function ($book) {
$book->title->not->toBeNull->cost->toBeGreaterThan(19);
});
});
it('works with sequence', function () {
expect(['books' => [['title' => 'Foo', 'cost' => 20], ['title' => 'Bar', 'cost' => 30]]])
->books->sequence(
function ($book) { $book->title->toEqual('Foo')->cost->toEqual(20); },
function ($book) { $book->title->toEqual('Bar')->cost->toEqual(30); },
);
});
it('can compose complex expectations', function () {
expect(['foo' => 'bar', 'numbers' => [1, 2, 3, 4]])
->toContain('bar')->toBeArray()
->numbers->toEqual([1, 2, 3, 4])->not()->toEqual('bar')->each->toBeInt
->foo->not->toEqual('world')->toEqual('bar')
->numbers->toBeArray();
});
it('works with objects', function () {
expect(new HasProperties())
->name->toEqual('foo')->not->toEqual('world')
->posts->toHaveCount(2)->each(function ($post) { $post->is_published->toBeTrue(); })
->posts->sequence(
function ($post) { $post->title->toEqual('Foo'); },
function ($post) { $post->title->toEqual('Bar'); },
);
});
it('works with nested properties', function () {
expect(new HasProperties())
->nested->foo->bar->toBeString()->toEqual('baz')
->posts->toBeArray()->toHaveCount(2);
});
it('works with higher order tests')
->expect(new HasProperties())
->nested->foo->bar->toBeString()->toEqual('baz')
->posts->toBeArray()->toHaveCount(2);
class HasProperties
{
public $name = 'foo';
public $posts = [
[
'is_published' => true,
'title' => 'Foo',
],
[
'is_published' => true,
'title' => 'Bar',
],
];
public $nested = [
'foo' => ['bar' => 'baz'],
];
}

View File

@ -0,0 +1,89 @@
<?php
use Pest\Expectation;
test('an exception is thrown if the the type is not iterable', function () {
expect('Foobar')->each()->toEqual('Foobar');
})->throws(BadMethodCallException::class, 'Expectation value is not iterable.');
it('expects on each item', function () {
expect([1, 1, 1])
->each()
->toEqual(1);
expect(static::getCount())->toBe(3); // + 1 assertion
expect([1, 1, 1])
->each
->toEqual(1);
expect(static::getCount())->toBe(7);
});
it('chains expectations on each item', function () {
expect([1, 1, 1])
->each()
->toBeInt()
->toEqual(1);
expect(static::getCount())->toBe(6); // + 1 assertion
expect([2, 2, 2])
->each
->toBeInt
->toEqual(2);
expect(static::getCount())->toBe(13);
});
test('opposite expectations on each item', function () {
expect([1, 2, 3])
->each()
->not()
->toEqual(4);
expect(static::getCount())->toBe(3);
expect([1, 2, 3])
->each()
->not->toBeString;
expect(static::getCount())->toBe(7);
});
test('chained opposite and non-opposite expectations', function () {
expect([1, 2, 3])
->each()
->not()
->toEqual(4)
->toBeInt();
expect(static::getCount())->toBe(6);
});
it('can add expectations via "and"', function () {
expect([1, 2, 3])
->each()
->toBeInt // + 3
->and([4, 5, 6])
->each
->toBeLessThan(7) // + 3
->not
->toBeLessThan(3)
->toBeGreaterThan(3) // + 3
->and('Hello World')
->toBeString // + 1
->toEqual('Hello World'); // + 1
expect(static::getCount())->toBe(14);
});
it('accepts callables', function () {
expect([1, 2, 3])->each(function ($number) {
expect($number)->toBeInstanceOf(Expectation::class);
expect($number->value)->toBeInt();
$number->toBeInt->not->toBeString;
});
expect(static::getCount())->toBe(12);
});

View File

@ -0,0 +1,29 @@
<?php
expect()->extend('toBeAMacroExpectation', function () {
$this->toBeTrue();
return $this;
});
expect()->extend('toBeAMacroExpectationWithArguments', function (bool $value) {
$this->toBe($value);
return $this;
});
it('macros true is true', function () {
expect(true)->toBeAMacroExpectation();
});
it('macros false is not true', function () {
expect(false)->not->toBeAMacroExpectation();
});
it('macros true is true with argument', function () {
expect(true)->toBeAMacroExpectationWithArguments(true);
});
it('macros false is not true with argument', function () {
expect(false)->not->toBeAMacroExpectationWithArguments(true);
});

View File

@ -0,0 +1,14 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('it properly parses json string', function () {
expect('{"name":"Nuno"}')
->json()
->name
->toBe('Nuno');
});
test('fails with broken json string', function () {
expect('{":"Nuno"}')->json();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,10 @@
<?php
test('not property calls', function () {
expect(true)
->toBeTrue()
->not()->toBeFalse()
->not->toBeFalse
->and(false)
->toBeFalse();
});

View File

@ -0,0 +1,5 @@
<?php
test('ray calls do not fail when ray is not installed', function () {
expect(true)->ray()->toBe(true);
});

View File

@ -0,0 +1,62 @@
<?php
test('an exception is thrown if the the type is not iterable', function () {
expect('Foobar')->each->sequence();
})->throws(BadMethodCallException::class, 'Expectation value is not iterable.');
test('allows for sequences of checks to be run on iterable data', function () {
expect([1, 2, 3])
->sequence(
function ($expectation) { $expectation->toBeInt()->toEqual(1); },
function ($expectation) { $expectation->toBeInt()->toEqual(2); },
function ($expectation) { $expectation->toBeInt()->toEqual(3); },
);
expect(static::getCount())->toBe(6);
});
test('loops back to the start if it runs out of sequence items', function () {
expect([1, 2, 3, 1, 2, 3, 1, 2])
->sequence(
function ($expectation) { $expectation->toBeInt()->toEqual(1); },
function ($expectation) { $expectation->toBeInt()->toEqual(2); },
function ($expectation) { $expectation->toBeInt()->toEqual(3); },
);
expect(static::getCount())->toBe(16);
});
test('it works if the number of items in the iterable is smaller than the number of expectations', function () {
expect([1, 2])
->sequence(
function ($expectation) { $expectation->toBeInt()->toEqual(1); },
function ($expectation) { $expectation->toBeInt()->toEqual(2); },
function ($expectation) { $expectation->toBeInt()->toEqual(3); },
);
expect(static::getCount())->toBe(4);
});
test('it works with associative arrays', function () {
expect(['foo' => 'bar', 'baz' => 'boom'])
->sequence(
function ($expectation, $key) { $expectation->toEqual('bar'); $key->toEqual('foo'); },
function ($expectation, $key) { $expectation->toEqual('boom'); $key->toEqual('baz'); },
);
});
test('it can be passed non-callable values', function () {
expect(['foo', 'bar', 'baz'])->sequence('foo', 'bar', 'baz');
expect(static::getCount())->toBe(3);
});
test('it can be passed a mixture of value types', function () {
expect(['foo', 'bar', 'baz'])->sequence(
'foo',
function ($expectation) { $expectation->toEqual('bar')->toBeString(); },
'baz'
);
expect(static::getCount())->toBe(4);
});

View File

@ -0,0 +1,20 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
expect(true)->toBeTrue()->and(false)->toBeFalse();
test('strict comparisons', function () {
$nuno = new stdClass();
$dries = new stdClass();
expect($nuno)->toBe($nuno)->not->toBe($dries);
});
test('failures', function () {
expect(1)->toBe(2);
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(1)->not->toBe(1);
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect([1, 2, 3])->toBeArray();
expect('1, 2, 3')->not->toBeArray();
});
test('failures', function () {
expect(null)->toBeArray();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(['a', 'b', 'c'])->not->toBeArray();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect(true)->toBeBool();
expect(0)->not->toBeBool();
});
test('failures', function () {
expect(null)->toBeBool();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(false)->not->toBeBool();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,18 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect(function () {})->toBeCallable();
expect(null)->not->toBeCallable();
});
test('failures', function () {
$hello = 5;
expect($hello)->toBeCallable();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(function () { return 42; })->not->toBeCallable();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,17 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
$temp = sys_get_temp_dir();
expect($temp)->toBeDirectory();
});
test('failures', function () {
expect('/random/path/whatever')->toBeDirectory();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect('.')->not->toBeDirectory();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,18 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect([])->toBeEmpty();
expect(null)->toBeEmpty();
});
test('failures', function () {
expect([1, 2])->toBeEmpty();
expect(' ')->toBeEmpty();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect([])->not->toBeEmpty();
expect(null)->not->toBeEmpty();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,15 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('strict comparisons', function () {
expect(false)->toBeFalse();
});
test('failures', function () {
expect('')->toBeFalse();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(false)->not->toBe(false);
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,19 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('passes as falsy', function ($value) {
expect($value)->toBeFalsy();
})->with([false, '', null, 0, '0']);
test('passes as not falsy', function ($value) {
expect($value)->not->toBeFalsy();
})->with([true, [1], 'false', 1, -1]);
test('failures', function () {
expect(1)->toBeFalsy();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(null)->not->toBeFalsy();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,23 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
beforeEach(function () {
touch($this->tempFile = sys_get_temp_dir() . '/fake.file');
});
afterEach(function () {
unlink($this->tempFile);
});
test('pass', function () {
expect($this->tempFile)->toBeFile();
});
test('failures', function () {
expect('/random/path/whatever.file')->toBeFile();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect($this->tempFile)->not->toBeFile();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect(1.0)->toBeFloat();
expect(1)->not->toBeFloat();
});
test('failures', function () {
expect(42)->toBeFloat();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(log(3))->not->toBeFloat();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('passes', function () {
expect(42)->toBeGreaterThan(41);
expect(4)->toBeGreaterThan(3.9);
});
test('failures', function () {
expect(4)->toBeGreaterThan(4);
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(5)->not->toBeGreaterThan(4);
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('passes', function () {
expect(42)->toBeGreaterThanOrEqual(41);
expect(4)->toBeGreaterThanOrEqual(4);
});
test('failures', function () {
expect(4)->toBeGreaterThanOrEqual(4.1);
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(5)->not->toBeGreaterThanOrEqual(5);
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('passes', function () {
expect('a')->toBeIn(['a', 'b', 'c']);
expect('d')->not->toBeIn(['a', 'b', 'c']);
});
test('failures', function () {
expect('d')->toBeIn(['a', 'b', 'c']);
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect('a')->not->toBeIn(['a', 'b', 'c']);
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect(log(0))->toBeInfinite();
expect(log(1))->not->toBeInfinite();
});
test('failures', function () {
expect(asin(2))->toBeInfinite();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(INF)->not->toBeInfinite();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect(new Exception())->toBeInstanceOf(Exception::class);
expect(new Exception())->not->toBeInstanceOf(RuntimeException::class);
});
test('failures', function () {
expect(new Exception())->toBeInstanceOf(RuntimeException::class);
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(new Exception())->not->toBeInstanceOf(Exception::class);
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect(42)->toBeInt();
expect(42.0)->not->toBeInt();
});
test('failures', function () {
expect(42.0)->toBeInt();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(6 * 7)->not->toBeInt();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,23 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect([])->toBeIterable();
expect(null)->not->toBeIterable();
});
test('failures', function () {
expect(42)->toBeIterable();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
function gen(): iterable
{
yield 1;
yield 2;
yield 3;
}
expect(gen())->not->toBeIterable();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,17 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect('{"hello":"world"}')->toBeJson();
expect('foo')->not->toBeJson();
expect('{"hello"')->not->toBeJson();
});
test('failures', function () {
expect(':"world"}')->toBeJson();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect('{"hello":"world"}')->not->toBeJson();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('passes', function () {
expect(41)->toBeLessThan(42);
expect(4)->toBeLessThan(5);
});
test('failures', function () {
expect(4)->toBeLessThan(4);
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(5)->not->toBeLessThan(6);
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('passes', function () {
expect(41)->toBeLessThanOrEqual(42);
expect(4)->toBeLessThanOrEqual(4);
});
test('failures', function () {
expect(4)->toBeLessThanOrEqual(3.9);
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(5)->not->toBeLessThanOrEqual(5);
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect(asin(2))->toBeNan();
expect(log(0))->not->toBeNan();
});
test('failures', function () {
expect(1)->toBeNan();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(acos(1.5))->not->toBeNan();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect(null)->toBeNull();
expect('')->not->toBeNull();
});
test('failures', function () {
expect('hello')->toBeNull();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(null)->not->toBeNull();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect(42)->toBeNumeric();
expect('A')->not->toBeNumeric();
});
test('failures', function () {
expect(null)->toBeNumeric();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(6 * 7)->not->toBeNumeric();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect((object) ['a' => 1])->toBeObject();
expect(['a' => 1])->not->toBeObject();
});
test('failures', function () {
expect(null)->toBeObject();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect((object) 'ciao')->not->toBeObject();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,15 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect(sys_get_temp_dir())->toBeReadableDirectory();
});
test('failures', function () {
expect('/random/path/whatever')->toBeReadableDirectory();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(sys_get_temp_dir())->not->toBeReadableDirectory();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,23 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
beforeEach(function () {
touch($this->tempFile = sys_get_temp_dir() . '/fake.file');
});
afterEach(function () {
unlink($this->tempFile);
});
test('pass', function () {
expect($this->tempFile)->toBeReadableFile();
});
test('failures', function () {
expect('/random/path/whatever.file')->toBeReadableFile();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect($this->tempFile)->not->toBeReadableFile();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,22 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
$resource = tmpfile();
afterAll(function () use ($resource) {
fclose($resource);
});
test('pass', function () use ($resource) {
expect($resource)->toBeResource();
expect(null)->not->toBeResource();
});
test('failures', function () {
expect(null)->toBeResource();
})->throws(ExpectationFailedException::class);
test('not failures', function () use ($resource) {
expect($resource)->not->toBeResource();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,15 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect(1.1)->toBeScalar();
});
test('failures', function () {
expect(null)->toBeScalar();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(42)->not->toBeScalar();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,16 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect('1.1')->toBeString();
expect(1.1)->not->toBeString();
});
test('failures', function () {
expect(null)->toBeString();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect('42')->not->toBeString();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,15 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('strict comparisons', function () {
expect(true)->toBeTrue();
});
test('failures', function () {
expect('')->toBeTrue();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(false)->not->toBe(false);
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,19 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('passes as truthy', function ($value) {
expect($value)->toBeTruthy();
})->with([true, [1], 'false', 1, -1]);
test('passes as not truthy', function ($value) {
expect($value)->not->toBeTruthy();
})->with([false, '', null, 0, '0']);
test('failures', function () {
expect(null)->toBeTruthy();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(1)->not->toBeTruthy();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,15 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect(sys_get_temp_dir())->toBeWritableDirectory();
});
test('failures', function () {
expect('/random/path/whatever')->toBeWritableDirectory();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(sys_get_temp_dir())->not->toBeWritableDirectory();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,23 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
beforeEach(function () {
touch($this->tempFile = sys_get_temp_dir() . '/fake.file');
});
afterEach(function () {
unlink($this->tempFile);
});
test('pass', function () {
expect($this->tempFile)->toBeWritableFile();
});
test('failures', function () {
expect('/random/path/whatever.file')->toBeWritableFile();
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect($this->tempFile)->not->toBeWritableFile();
})->throws(ExpectationFailedException::class);

View File

@ -0,0 +1,47 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('passes strings', function () {
expect('Nuno')->toContain('Nu');
});
test('passes strings with multiple needles', function () {
expect('Nuno')->toContain('Nu', 'no');
});
test('passes arrays', function () {
expect([1, 2, 42])->toContain(42);
});
test('passes arrays with multiple needles', function () {
expect([1, 2, 42])->toContain(42, 2);
});
test('passes with array needles', function () {
expect([[1, 2, 3], 2, 42])->toContain(42, [1, 2, 3]);
});
test('failures', function () {
expect([1, 2, 42])->toContain(3);
})->throws(ExpectationFailedException::class);
test('failures with multiple needles (all failing)', function () {
expect([1, 2, 42])->toContain(3, 4);
})->throws(ExpectationFailedException::class);
test('failures with multiple needles (some failing)', function () {
expect([1, 2, 42])->toContain(1, 3, 4);
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect([1, 2, 42])->not->toContain(42);
})->throws(ExpectationFailedException::class);
test('not failures with multiple needles (all failing)', function () {
expect([1, 2, 42])->not->toContain(42, 2);
})->throws(ExpectationFailedException::class);
test('not failures with multiple needles (some failing)', function () {
expect([1, 2, 42])->not->toContain(42, 1);
})->throws(ExpectationFailedException::class);

Some files were not shown because too many files have changed in this diff Show More