Compare commits

...

270 Commits

Author SHA1 Message Date
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
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
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
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
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
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
bb13bdaa80 docs: updates changelog 2021-06-06 01:07:27 +01:00
10e7cbe006 Merge pull request #310 from bigint/master
Update phpunit/phpunit to 9.5.5
2021-06-05 16:29:02 +01:00
0ad232e9de Update phpunit/phpunit to 9.5.5 2021-06-05 20:47:57 +05:30
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
91eff755fd Merge pull request #306 from owenvoke/feature/lock-plugins
chore(deps): update minimum plugin versions
2021-06-02 12:43:05 +01:00
c05d287fcc chore(deps): update minimum plugin versions 2021-06-02 09:24:07 +01: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
9133b88d65 release: 1.3.0 2021-05-23 22:06:11 +01:00
93b9afbd27 docs: updates changelog 2021-05-23 22:05:46 +01:00
6c6bba2a04 tests: updates snapshots 2021-05-23 22:02:06 +01:00
dd24b7e347 Merge pull request #300 from pestphp/feat-function_exists
Wrap functions in function_exists
2021-05-23 21:47:25 +01:00
ce896b9c83 Merge pull request #302 from def-studio/show-only-name-for-named-datasets
hides dataset values if they have a name
2021-05-23 21:46:59 +01:00
a3c1a61b59 updates tests
Took 1 minute
2021-05-23 22:17:35 +02:00
98c62f4b1d show only name for named datasets
Took 4 minutes
2021-05-23 22:16:29 +02:00
dd78cc9a50 Wrap functions in function_exists 2021-05-19 09:47:29 +02:00
9027411004 feat(mock-plugin): moves mock stuff to their own plugin 2021-05-15 23:43:37 +01:00
9394aa4649 Merge pull request #289 from pestphp/feat/mock
feat: adds built-in mocking
2021-05-15 01:03:07 +01:00
88dc74bbe4 feat(mock): updates tests 2021-05-15 01:02:58 +01:00
7023cec432 feat(mock): updates tests 2021-05-15 01:01:46 +01:00
99d6fb9f5f feat(mock): updates tests 2021-05-14 23:59:50 +01:00
c9f723530d feat(mock): adds work in progress 2021-05-14 23:52:24 +01:00
3205b571b0 Merge branch 'master' of https://github.com/pestphp/pest 2021-05-14 10:51:54 +01:00
2c4aef5272 release: 1.2.1 2021-05-14 10:51:50 +01:00
4a45a7cc6b Merge pull request #297 from owenvoke/bugfix/laravel-commands
fix: resolve test directory before function call
2021-05-14 10:17:51 +01:00
ea8ab88056 style: apply fixes from PHPStan 2021-05-14 10:05:16 +01:00
564a21badd style: apply fixes from php-cs-fixer 2021-05-14 10:00:53 +01:00
41ce87450f fix: resolve test directory before function call 2021-05-14 09:33:52 +01:00
fb0eef4200 release: 1.2.0 2021-05-13 00:37:55 +01:00
819da37b89 Merge pull request #292 from shuvroroy/patch-1
Remove unused import
2021-05-12 21:21:59 +01:00
8eb9c408a9 Merge pull request #296 from pestphp/feature/php-cs-fixer-3
chore: migrate to PHP-CS-Fixer 3.x
2021-05-12 15:14:06 +01:00
1f10b46402 chore: migrate to PHP-CS-Fixer 3.x 2021-05-12 11:26:09 +01:00
7bb12b73e8 Merge pull request #288 from gregorip02/master
Ignore the absence of the tests folder
2021-05-11 08:19:14 +01:00
b8103697c9 Remove unused import 2021-05-07 12:45:55 +06:00
ca3f8b5702 Merge pull request #291 from olivernybroe/feat-junit
Add Junit support
2021-05-05 17:13:58 +01:00
daa01ea44b Merge pull request #283 from faustbrian/test-directory-config
make test directory configurable
2021-05-05 11:07:10 +01:00
26d577f9c5 separate directory and path by / 2021-05-05 05:07:17 +03:00
43fb711251 Merge branch 'master' into master 2021-05-03 11:47:36 -04:00
567af55a19 make test directory configurable 2021-05-03 18:28:20 +03:00
c6a2e3b4d0 chore: release 1.1.0 2021-05-02 23:41:59 +01:00
a10428efe6 Merge pull request #282 from jordanbrauer/reusable-hooks
Reusable hooks
2021-05-02 19:51:59 +01:00
1440637e41 Add Junit support 2021-05-02 11:22:19 +02:00
14cee66dfd Update README.md 2021-04-20 19:32:33 +01:00
d048d60d04 Ignore the absence of the tests folder 2021-04-10 11:51:13 -04:00
1b9162151c docs: add some method documentation and fix typo 2021-04-07 11:02:00 -05:00
885c9f1f06 test: update the snapshot with new test output 2021-04-07 10:56:19 -05:00
90efcc8a8a feat: add shared/global beforeAll and afterAll hooks 2021-04-07 10:55:19 -05:00
7d35ee9998 feat: add new helper to create static closure chains 2021-04-07 10:53:46 -05:00
584a7ac8a5 test: add cases for global before/after all hooks 2021-04-07 10:52:49 -05:00
f21e45ae64 fix: type declaration for and add small comment RE: merge behaviour 2021-04-07 09:49:53 -05:00
c7d26a27b6 fix: ensure that Pest is loaded before the test file itself 2021-04-07 09:49:12 -05:00
54f9397f47 style: address stan + lint issues 2021-04-06 19:32:49 -05:00
ff44589572 refactor: pack hooks into an array instead of 1 argument per hook 2021-04-06 19:27:50 -05:00
53333b56ab test: adding tests for beforeEach and afterEach + empty tests for *All 2021-04-06 19:26:42 -05:00
6616b6299b docs: update changelog 2021-03-31 16:00:01 +01:00
0bab649156 Merge pull request #284 from owenvoke/feature/update-phpunit
chore(deps): add support for PHPUnit 9.5.4
2021-03-31 15:42:50 +01:00
2de7cb4726 chore(deps): add support for PHPUnit 9.5.4 2021-03-31 15:29:58 +01:00
99500d0cae feat: add shared/global before each hook 2021-03-28 02:03:31 -05:00
7eb5478c42 test: add tests for shared/global before each hooks 2021-03-28 01:54:43 -05:00
d2babb1331 Merge pull request #280 from pristavu/master
Add Dusk command argument --browse
2021-03-25 12:57:46 +00:00
a6cced6b63 Update PestDuskCommand.php
Add Dusk command argument --browse
2021-03-22 01:16:09 +02:00
7917313422 docs: update changelog 2021-03-17 13:44:14 +00:00
e02c22e136 Merge pull request #278 from owenvoke/feature/phpunit-9.5.3
chore(deps): add support for PHPUnit 9.5.3
2021-03-17 13:41:58 +00:00
2157644a39 chore(deps): add support for PHPUnit 9.5.3 2021-03-17 13:38:53 +00:00
b6c2812a91 chore: bump static tests to PHP8.0 2021-03-13 11:14:27 +00:00
4b65d2c426 release: v1.0.3 2021-03-13 11:07:57 +00:00
3589f3d5e7 chore: fixes test suite 2021-03-13 11:06:34 +00:00
1f39b8d239 Merge pull request #269 from jordanbrauer/multiple-suffix-extensions
fix: allow multiple file extensions in test suffix (prevent class & file name syntax errors)
2021-03-13 10:36:02 +00:00
7c3c390cbf chore: bumps dev dependencies 2021-03-12 21:50:23 +00:00
19a1569fa8 cleanup for self-review 2021-02-13 13:31:25 -06:00
9a0240bc7b patch addslashes for windows paths 2021-02-13 12:48:43 -06:00
dd94a843b5 run linter & auto format 2021-02-13 12:14:22 -06:00
9426d08aa2 update snapshot for running tests with failed classnames 2021-02-13 12:12:32 -06:00
fe2fac37f8 address PHPStan warning about use of empty 2021-02-13 11:53:30 -06:00
cabd64df00 rename tests for windows, despite losing some coverage 2021-02-13 11:51:35 -06:00
bb57a54089 simplify quote escape sequence handling 2021-02-13 11:40:08 -06:00
5e0bfba7bf run linter 2021-02-13 11:21:14 -06:00
f6c19e469f in the event of no class name, make one on the fly as an escape hatch 2021-02-13 11:20:16 -06:00
13f09cc662 add helper method to generate a simple random string 2021-02-13 11:19:40 -06:00
a7e2856887 add test for totally invalid PHP class name 2021-02-13 11:19:00 -06:00
721e047485 add another test case with non-standard PHP test file name 2021-02-13 11:18:28 -06:00
301ff155a4 prevent parse errors by escaping the quote used for filename property 2021-02-13 11:17:52 -06:00
40f2065575 catch parse errors and let the user know in a friendlier manner 2021-02-13 11:12:09 -06:00
be906eb823 remove additional str_replace call in favour of adjusting the relative path regexp 2021-02-13 11:08:08 -06:00
2cee825f61 rename test sub directory 2021-02-13 11:07:22 -06:00
ea6308bfdf add tests for vaious file naming conventions resulting in various suffixes 2021-02-13 09:45:41 -06:00
c6a6f7e2ab fix typo 2021-02-13 00:15:54 -06:00
20077c285a WIP proof of concept fix for multiple file extensions in test suffix 2021-02-13 00:14:20 -06:00
fa13016785 docs: update changelog 2021-02-04 09:15:54 +00:00
b81bb9d621 chore(deps): add support for PHPUnit 9.5.2 2021-02-04 09:12:29 +00:00
2deb53c14f docs: fix typo 2021-01-18 09:50:21 +00:00
6b8feed08a docs: update changelog 2021-01-18 09:35:53 +00:00
2fe8e07cf3 Merge pull request #261 from owenvoke/feature/update-phpunit
chore(deps): add support for PHPUnit 9.5.1
2021-01-18 09:31:57 +00:00
d2c907868e chore(deps): add support for PHPUnit 9.5.1 2021-01-18 09:11:38 +00:00
a2900a5e09 Merge pull request #251 from MatanYadaev/fix-expect-phpdoc
Fix `TestCase@expect` phpDoc
2021-01-05 20:19:03 +01:00
df934bacd9 fix TestCase expect phpDoc 2021-01-05 20:42:14 +02:00
b0f03c278d docs: updates changelog 2021-01-03 17:27:11 +01:00
b59b321249 Merge pull request #245 from gpibarra/make-dusk-test
MakeDuskTest
2021-01-02 23:35:32 +01:00
82d6991cf8 docs: updates sponsors 2020-12-28 20:17:23 +01:00
d693d99379 Update src/Laravel/Commands/PestTestCommand.php
Co-authored-by: Owen Voke <development@voke.dev>
2020-12-28 13:51:03 -03:00
50c1136be8 MakeDuskTest 2020-12-28 13:13:30 -03:00
dd491e516c Update FUNDING.yml 2020-12-28 15:54:30 +01:00
078aab0d3d Update FUNDING.yml 2020-12-28 02:00:30 +01:00
89c9f4b428 Update FUNDING.yml 2020-12-28 01:59:56 +01:00
2148e896e2 Update FUNDING.yml 2020-12-28 01:59:30 +01:00
7ba49b2e3e chore: fixes style 2020-12-27 21:42:08 +01:00
54a285f7e3 Update PestInstallCommand.php 2020-12-27 17:40:26 +01:00
3ed20d059c Merge pull request #240 from pestphp/feat/improve-init
feat: improve init files
2020-12-27 16:25:48 +01:00
92b6800f28 feat(improve-init): fixes styleci 2020-12-27 15:39:17 +01:00
29cfd1a2dc feat(improve-init): typos 2020-12-27 15:33:52 +01:00
45c09ea0ed feat(improve-init): wording 2020-12-27 15:28:32 +01:00
424e24d530 feat: improve init files 2020-12-27 15:24:21 +01:00
26b2e3561a docs: update changelog 2020-12-27 11:36:24 +00:00
60aea6798d Merge pull request #239 from gpibarra/patch-1
change binary path pest:dusk
2020-12-27 02:46:08 +01:00
fac3fe3f55 docs: updates changelog 2020-12-26 21:31:38 +01:00
17fac0a488 Update composer.json 2020-12-26 21:19:28 +01:00
6abc2207b2 change binary path pest:dusk
In windows not work
full path is used in [7e05b3ca4f/src/Console/DuskCommand.php (L91)) and [163d5c2bd8/src/Adapters/Laravel/Commands/TestCommand.php (L108))
2020-12-23 15:08:49 -03:00
885d224c5d docs: updates changelog 2020-12-20 17:22:40 +01:00
12441deab8 chore: upgrades version 2020-12-20 17:22:33 +01:00
8852fd14ce Merge pull request #236 from avrahamappel/master
Add test for inheritance with depends
2020-12-20 17:18:53 +01:00
e3814e6d9c chore: fixes static analsysis on uses_classs 2020-12-20 17:12:08 +01:00
e19eba0942 Rebuild snapshots 2020-12-17 23:24:29 -05:00
b6e2763731 Move dependency mapping to TestCase
The `TestCaseFactory::getClassName` was removed since it can have
unexpected results when called too early, as it builds up the test class
prematurely. It is not currently used anywhere else.
2020-12-17 23:24:11 -05:00
f75a3ee865 Add test for inheritance with depends 2020-12-15 22:29:37 -05:00
d707c2f208 Merge pull request #209 from NickSdot/make-root-path-working-in-subdirectory-structures
Get root path based on composer autoloader
2020-12-15 01:58:05 +01:00
a43b86d9eb chore: removes rector 2020-12-13 23:11:50 +01:00
5279d5e913 chore: pin expectations plugin version 2020-12-13 23:09:32 +01:00
df7fb92e03 chore: removes rector 2020-12-13 22:55:09 +01:00
95c3418313 docs: updates changelog 2020-12-13 22:52:06 +01:00
67a8be9347 chore: fixes snapshots 2020-12-13 22:50:13 +01:00
5d7f262f4a feat: removes expectation api for a plugin 2020-12-13 22:35:30 +01:00
23eebc8127 docs: updates changelog 2020-12-04 21:19:40 +01:00
3b435e460e chore: increases version 2020-12-04 21:19:32 +01:00
b52e9826e7 Merge pull request #234 from soilSpoon/feature/phpunit
Update PHPUnit dependency version
2020-12-04 09:16:27 +01:00
ba49dd0499 Update PHPUnit dependency version 2020-12-04 15:46:25 +09:00
f9f6f28950 Merge pull request #233 from misaert/feat-authorize-associative-array-for-with
fix: authorize string as key for datasets
2020-11-30 16:42:35 +01:00
f017015d1e fix: authorize string as key for datasets 2020-11-30 14:50:40 +01:00
29b4ee33bb Merge pull request #232 from pestphp/feat/expect-extend
feat: makes expect extendable
2020-11-29 18:25:21 +01:00
03dc11c2f6 Adds expect extend 2020-11-29 16:30:57 +01:00
b79ba5098b docs: updates changelog 2020-11-28 18:55:22 +01:00
3c418d82e6 chore: increases version 2020-11-28 18:55:14 +01:00
73ede2e344 Merge pull request #223 from clmntgr/support-pest-command
Add a dusk command for Laravel
2020-11-28 18:46:51 +01:00
266d891488 Merge pull request #231 from pestphp/feat/feedback-on-to-match
feat: adds key/value context when toMatchObject or toMatchArray fails
2020-11-28 18:21:52 +01:00
c71490b472 feat(feedback-on-to-match): uses contextual messages inside expectations 2020-11-27 21:52:44 +01:00
07705079e2 Merge pull request #229 from owenvoke/feature/release-guide
docs: add release guide
2020-11-27 11:42:46 +01:00
d88c268426 docs: use docs prefix in release commit message 2020-11-27 09:13:38 +00:00
a1b142e885 docs: add details on plugin versioning 2020-11-26 19:55:42 +00:00
a50d739e50 docs: add release guide 2020-11-26 19:55:11 +00:00
f82bb56d89 chore: update changelog 2020-11-24 09:12:43 +00:00
de593c3b93 Add a dusk command for Laravel.
This new command will replicate Dusk behavior with .env.dusk files
2020-11-24 10:07:06 +01:00
eedd5d80a0 chore: updates version 2020-11-23 22:01:06 +01:00
5bbdd4f41e docs: updates changelog 2020-11-23 21:43:58 +01:00
3fd24d96d3 feat: casts to array using toArray 2020-11-23 21:37:35 +01:00
7bea51fe09 feat: adds toMatchArray 2020-11-23 21:26:02 +01:00
cdf0a38145 Merge pull request #216 from owenvoke/bugfix/depends
fix(depends): resolve issue with dependency names
2020-11-23 08:43:58 +00:00
bb2474ccbe tests: add regression tests for depends 2020-11-13 11:14:17 +00:00
01143a6f84 fix(depends): resolve issue with dependency names 2020-11-13 11:08:35 +00:00
b93485c2ed Merge pull request #217 from owenvoke/feature/help
feat: add Pest options to help output
2020-11-12 14:59:50 +00:00
04681690b6 tests: update help snapshot to only include Pest options 2020-11-12 09:53:40 +00:00
200877d691 tests: update to use snapshot for help output 2020-11-12 09:44:26 +00:00
feb6417f45 tests: add visual test for help output 2020-11-12 09:11:51 +00:00
e7585a4ba2 tests: update snapshots 2020-11-12 09:03:44 +00:00
c33ab0f670 tests: add test for help output 2020-11-12 09:03:44 +00:00
78181f66f6 feat: add Pest options to help output 2020-11-12 09:03:43 +00:00
925636be61 docs: add missing bracket 2020-11-11 23:31:19 +00:00
6be131d602 chore: update changelog 2020-11-11 23:29:18 +00:00
f950f57eed Merge pull request #219 from owenvoke/feature/phpunit
chore(deps): add support for PHPUnit 9.4.3
2020-11-11 22:35:26 +00:00
c6369feaea chore(deps): add support for PHPUnit 9.4.3 2020-11-11 22:26:53 +00:00
ba08f2c11e Changes based on feedback https://github.com/pestphp/pest-intellij/issues/73#issuecomment-709201510 2020-10-15 19:46:16 +08:00
13a8aee049 Get root path from already available and correct path of autoloader 2020-10-14 21:31:28 +08:00
157 changed files with 4304 additions and 729 deletions

30
.gitattributes vendored
View File

@ -1,16 +1,14 @@
/art export-ignore
/docs export-ignore
/tests export-ignore
/scripts export-ignore
/.github export-ignore
/.php_cs export-ignore
.editorconfig export-ignore
.gitattributes export-ignore
.gitignore export-ignore
.travis.yml export-ignore
phpstan.neon export-ignore
rector.yaml export-ignore
phpunit.xml export-ignore
CHANGELOG.md export-ignore
CONTRIBUTING.md export-ignore
README.md export-ignore
/art export-ignore
/docs export-ignore
/tests export-ignore
/scripts export-ignore
/.github export-ignore
/.php-cs-fixer.dist.php export-ignore
.editorconfig export-ignore
.gitattributes export-ignore
.gitignore export-ignore
phpstan.neon 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
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

@ -15,16 +15,13 @@ jobs:
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 7.4
php-version: 8.0
tools: composer:v2
coverage: none
- name: Install Dependencies
run: composer update --no-interaction --no-progress
- name: Run Rector
run: vendor/bin/rector process src --dry-run
- name: Run PHP-CS-Fixer
run: vendor/bin/php-cs-fixer fix -v --allow-risky=yes --dry-run
@ -43,7 +40,7 @@ jobs:
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 7.4
php-version: 8.0
tools: composer:v2
coverage: none

3
.gitignore vendored
View File

@ -4,7 +4,8 @@ composer.lock
/vendor/
coverage.xml
.phpunit.result.cache
.php_cs.cache
/.php-cs-fixer.php
.php-cs-fixer.cache
.temp/coverage.php
*.swp
*.swo

View File

@ -6,7 +6,7 @@ $finder = PhpCsFixer\Finder::create()
->in(__DIR__ . DIRECTORY_SEPARATOR . 'scripts')
->in(__DIR__ . DIRECTORY_SEPARATOR . 'stubs')
->in(__DIR__ . DIRECTORY_SEPARATOR . 'src')
->append(['.php_cs']);
->append(['.php-cs-fixer.dist.php']);
$rules = [
'@Symfony' => true,
@ -25,7 +25,7 @@ $rules = [
$rules['increment_style'] = ['style' => 'post'];
return PhpCsFixer\Config::create()
return (new PhpCsFixer\Config())
->setUsingCache(true)
->setRules($rules)
->setFinder($finder);

View File

@ -4,6 +4,150 @@ 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.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))
### Fixed
- Wraps global functions within `function_exists` ([#300](https://github.com/pestphp/pest/pull/300))
## [v1.2.1 (2021-05-14)](https://github.com/pestphp/pest/compare/v1.2.0...v1.2.1)
### Fixed
- Laravel commands failing with new `--test-directory` option ([#297](https://github.com/pestphp/pest/pull/297))
## [v1.2.0 (2021-05-13)](https://github.com/pestphp/pest/compare/v1.1.0...v1.2.0)
### Added
- Adds JUnit / Infection support ([#291](https://github.com/pestphp/pest/pull/291))
- `--test-directory` command line option ([#283](https://github.com/pestphp/pest/pull/283))
## [v1.1.0 (2021-05-02)](https://github.com/pestphp/pest/compare/v1.0.5...v1.1.0)
### Added
- Possibility of "hooks" being added using the "uses" function ([#282](https://github.com/pestphp/pest/pull/282))
## [v1.0.5 (2021-03-31)](https://github.com/pestphp/pest/compare/v1.0.4...v1.0.5)
### Added
- Add `--browse` option to `pest:dusk` command ([#280](https://github.com/pestphp/pest/pull/280))
- Support for PHPUnit 9.5.4 ([#284](https://github.com/pestphp/pest/pull/284))
## [v1.0.4 (2021-03-17)](https://github.com/pestphp/pest/compare/v1.0.3...v1.0.4)
### Added
- Support for PHPUnit 9.5.3 ([#278](https://github.com/pestphp/pest/pull/278))
## [v1.0.3 (2021-03-13)](https://github.com/pestphp/pest/compare/v1.0.2...v1.0.3)
### Added
- Support for test extensions ([#269](https://github.com/pestphp/pest/pull/269))
## [v1.0.2 (2021-02-04)](https://github.com/pestphp/pest/compare/v1.0.1...v1.0.2)
### Added
- Support for PHPUnit 9.5.2 ([#267](https://github.com/pestphp/pest/pull/267))
## [v1.0.1 (2021-01-18)](https://github.com/pestphp/pest/compare/v1.0.0...v1.0.1)
### Added
- Support for PHPUnit 9.5.1 ([#261](https://github.com/pestphp/pest/pull/261))
### Fixed
- Fix `TestCase@expect` PHPDoc tag ([#251](https://github.com/pestphp/pest/pull/251))
## [v1.0.0 (2021-01-03)](https://github.com/pestphp/pest/compare/v0.3.19...v1.0.0)
### Added
- `pest:test --dusk` option ([#245](https://github.com/pestphp/pest/pull/245))
### Changed
- Stable version
- Updates init structure ([#240](https://github.com/pestphp/pest/pull/240))
## [v0.3.19 (2020-12-27)](https://github.com/pestphp/pest/compare/v0.3.18...v0.3.19)
### Fixed
- Fix binary path in `pest:dusk` command ([#239](https://github.com/pestphp/pest/pull/239))
## [v0.3.18 (2020-12-26)](https://github.com/pestphp/pest/compare/v0.3.17...v0.3.18)
### Added
- `toBeJson()` expectation ([plugin-expectations#2](https://github.com/pestphp/pest-plugin-expectations/pull/2))
## [v0.3.17 (2020-12-20)](https://github.com/pestphp/pest/compare/v0.3.16...v0.3.17)
### Fixed
- Class inheritance with `depends()` ([#236](https://github.com/pestphp/pest/pull/236))
## [v0.3.16 (2020-12-13)](https://github.com/pestphp/pest/compare/v0.3.15...v0.3.16)
### Changed
- Moves expectation API for external plugin ([5d7f262](https://github.com/pestphp/pest/commit/5d7f262f4ab280a660a85900f402eebb23abfda8))
## [v0.3.15 (2020-12-04)](https://github.com/pestphp/pest/compare/v0.3.14...v0.3.15)
### Added
- Support for PHPUnit 9.5.0 ([#234](https://github.com/pestphp/pest/pull/234))
- Support for extending expectation API ([#232](https://github.com/pestphp/pest/pull/232))
### Fixed
- Static analysis while using string as key for datasets ([#233](https://github.com/pestphp/pest/pull/233))
## [v0.3.14 (2020-11-28)](https://github.com/pestphp/pest/compare/v0.3.13...v0.3.14)
### Added
- `pest:dusk` command ([#223](https://github.com/pestphp/pest/pull/223))
- Better feedback on errors in `toMatchArray` and `toMatchObject` ([#231](https://github.com/pestphp/pest/pull/231))
## [v0.3.13 (2020-11-23)](https://github.com/pestphp/pest/compare/v0.3.12...v0.3.13)
### Added
- `toMatchArray` expectation ([7bea51f](https://github.com/pestphp/pest/commit/7bea51fe09dd2eca7093e4c34cf2dab2e8d39fa5), [3fd24d9](https://github.com/pestphp/pest/commit/3fd24d96d3145dcebdb0aab40aa8b76faa8b6979))
- Add Pest options to `--help` output ([#217](https://github.com/pestphp/pest/pull/217))
### Fixed
- Resolve issue with name resolution in `depends()` ([#216](https://github.com/pestphp/pest/pull/216))
## [v0.3.12 (2020-11-11)](https://github.com/pestphp/pest/compare/v0.3.11...v0.3.12)
### Added
- Add support for PHPUnit 9.4.3 ([#219](https://github.com/pestphp/pest/pull/219))
## [v0.3.11 (2020-11-09)](https://github.com/pestphp/pest/compare/v0.3.10...v0.3.11)
### Changed
- Improved the exception output for the TeamCity printer (usage with phpstorm plugin) ([#215](https://github.com/pestphp/pest/pull/215))
@ -58,7 +202,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))
@ -73,7 +217,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

@ -21,6 +21,8 @@ We would like to extend our thanks to the following sponsors for funding Pest de
### Premium Sponsors
- **[Scout APM](https://github.com/scoutapp)**
- **[Scout APM](https://scoutapm.com)**
- **[Akaunting](https://akaunting.com)**
- **[Meema](https://meema.io/)**
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)**.

16
RELEASE.md Normal file
View File

@ -0,0 +1,16 @@
# Release process
When releasing a new version of Pest there are some checks and updates that need to be done:
- Clear your local repository with: `git add . && git reset --hard && git checkout master`
- 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"`
- 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`
### Plugins
Plugins should be versioned using the same major (or minor for `0.x` releases) version as Pest core.

View File

@ -19,17 +19,21 @@ use Symfony\Component\Console\Output\OutputInterface;
if (file_exists($vendorPath)) {
include_once $vendorPath;
$autoloadPath = $vendorPath;
} else {
include_once $localPath;
$autoloadPath = $localPath;
}
(new Provider())->register();
$rootPath = getcwd();
// get $rootPath based on $autoloadPath
$rootPath = dirname($autoloadPath, 2);
$argv = new ArgvInput();
$testSuite = TestSuite::getInstance($rootPath);
$testSuite = TestSuite::getInstance($rootPath, $argv->getParameterOption('--test-directory', 'tests'));
$isDecorated = (new ArgvInput())->getParameterOption('--colors', 'always') !== 'never';
$isDecorated = $argv->getParameterOption('--colors', 'always') !== 'never';
$output = new ConsoleOutput(ConsoleOutput::VERBOSITY_NORMAL, $isDecorated);
$container = Container::getInstance();
@ -38,5 +42,14 @@ use Symfony\Component\Console\Output\OutputInterface;
ValidatesEnvironment::in($testSuite);
// lets remove any arguments that PHPUnit does not understand
if ($argv->hasParameterOption('--test-directory')) {
foreach ($_SERVER['argv'] as $key => $value) {
if (strpos($value, '--test-directory') !== false) {
unset($_SERVER['argv'][$key]);
}
}
}
exit($container->get(Command::class)->run($_SERVER['argv']));
})();

View File

@ -18,18 +18,16 @@
],
"require": {
"php": "^7.3 || ^8.0",
"nunomaduro/collision": "^5.0",
"pestphp/pest-plugin": "^0.3",
"pestphp/pest-plugin-coverage": "^0.3",
"pestphp/pest-plugin-init": "^0.3",
"phpunit/phpunit": ">= 9.3.7 <= 9.4.2"
"nunomaduro/collision": "^5.4.0",
"pestphp/pest-plugin": "^1.0.0",
"phpunit/phpunit": ">= 9.3.7 <= 9.5.6"
},
"autoload": {
"psr-4": {
"Pest\\": "src/"
},
"files": [
"src/globals.php",
"src/Functions.php",
"src/Pest.php"
]
},
@ -42,9 +40,9 @@
]
},
"require-dev": {
"illuminate/console": "^7.16.1",
"illuminate/support": "^7.16.1",
"mockery/mockery": "^1.4.1",
"illuminate/console": "^8.47.0",
"illuminate/support": "^8.47.0",
"laravel/dusk": "^6.15.0",
"pestphp/pest-dev-tools": "dev-master"
},
"minimum-stability": "dev",
@ -57,8 +55,8 @@
"bin/pest"
],
"scripts": {
"lint": "rector process src && php-cs-fixer fix -v",
"test:lint": "php-cs-fixer fix -v --dry-run && rector process src --dry-run",
"lint": "php-cs-fixer fix -v",
"test:lint": "php-cs-fixer fix -v --dry-run",
"test:types": "phpstan analyse --ansi --memory-limit=0",
"test:unit": "php bin/pest --colors=always --exclude-group=integration",
"test:integration": "php bin/pest --colors=always --group=integration",
@ -72,10 +70,12 @@
},
"extra": {
"branch-alias": {
"dev-master": "0.4.x-dev"
"dev-master": "1.x-dev"
},
"pest": {
"plugins": [
"Pest\\Plugins\\Coverage",
"Pest\\Plugins\\Init",
"Pest\\Plugins\\Version"
]
},

View File

@ -7,15 +7,14 @@ parameters:
level: max
paths:
- src
excludes_analyse:
- src/globals.php
- scripts
checkMissingIterableValueType: true
checkGenericClassInNonGenericObjectType: false
reportUnmatchedIgnoredErrors: true
ignoreErrors:
- "#Undefined variable: \\$this#"
- "#type mixed is not subtype of native#"
- "#is not allowed to extend#"
- "#Language construct eval#"
- "# with null as default value#"
@ -24,10 +23,13 @@ parameters:
- "#Method Pest\\\\Support\\\\Reflection::getParameterClassName\\(\\) has a nullable return type declaration.#"
-
message: '#Call to an undefined method PHPUnit\\Framework\\Test::getName\(\)#'
path: src/TeamCity.php
path: src/Logging
-
message: '#invalid typehint type Pest\\Concerns\\TestCase#'
path: src/TeamCity.php
message: '#invalid typehint type Pest\\Concerns\\Testable#'
path: src/Logging
-
message: '#is not subtype of native type PHPUnit\\Framework\\Test#'
path: src/TeamCity.php
path: src/Logging
-
message: '#Call to an undefined method PHPUnit\\Framework\\Test::getPrintableTestCaseName\(\)#'
path: src/Logging

View File

@ -1,35 +0,0 @@
<?php
declare(strict_types=1);
use Rector\Core\Configuration\Option;
use Rector\Php70\Rector\StaticCall\StaticCallOnNonStaticToInstanceCallRector;
use Rector\Set\ValueObject\SetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$parameters = $containerConfigurator->parameters();
$parameters->set(Option::AUTO_IMPORT_NAMES, true);
$parameters->set(Option::SETS, [
SetList::ACTION_INJECTION_TO_CONSTRUCTOR_INJECTION,
SetList::ARRAY_STR_FUNCTIONS_TO_STATIC_CALL,
SetList::CODE_QUALITY,
SetList::PHP_53,
SetList::PHP_54,
SetList::PHP_56,
SetList::PHP_70,
SetList::PHP_71,
SetList::PHP_72,
SetList::PHP_73,
SetList::PHPSTAN,
SetList::PHPUNIT_CODE_QUALITY,
SetList::SOLID,
]);
$parameters->set(Option::PATHS, [__DIR__ . '/src', __DIR__ . '/tests']);
$parameters->set(Option::EXCLUDE_RECTORS, [
StaticCallOnNonStaticToInstanceCallRector::class,
]);
};

View File

@ -15,6 +15,7 @@ $globalsFilePath = implode(DIRECTORY_SEPARATOR, [
$compiledFilePath = implode(DIRECTORY_SEPARATOR, [dirname(__DIR__), 'compiled', 'globals.php']);
/* @phpstan-ignore-next-line */
@unlink($compiledFilePath);
$replace = function ($contents, $string, $by) {

View File

@ -5,7 +5,8 @@ declare(strict_types=1);
namespace Pest\Actions;
use NunoMaduro\Collision\Adapters\Phpunit\Printer;
use Pest\TeamCity;
use Pest\Logging\JUnit;
use Pest\Logging\TeamCity;
use PHPUnit\TextUI\DefaultResultPrinter;
/**
@ -32,6 +33,14 @@ final class AddsDefaults
$arguments[self::PRINTER] = new TeamCity($arguments['verbose'] ?? false, $arguments['colors'] ?? DefaultResultPrinter::COLOR_ALWAYS);
}
// Load our junit logger instead.
if (array_key_exists('junitLogfile', $arguments)) {
$arguments['listeners'][] = new JUnit(
$arguments['junitLogfile']
);
unset($arguments['junitLogfile']);
}
return $arguments;
}
}

View File

@ -5,7 +5,7 @@ declare(strict_types=1);
namespace Pest\Actions;
use Pest\Support\Str;
use PHPUnit\TextUI\Configuration\Configuration;
use function Pest\testDirectory;
use PHPUnit\Util\FileLoader;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
@ -21,6 +21,7 @@ final class LoadStructure
* @var array<int, string>
*/
private const STRUCTURE = [
'Expectations.php',
'Datasets.php',
'Helpers.php',
'Pest.php',
@ -32,7 +33,7 @@ final class LoadStructure
*/
public static function in(string $rootPath): void
{
$testsPath = $rootPath . DIRECTORY_SEPARATOR . 'tests';
$testsPath = $rootPath . DIRECTORY_SEPARATOR . testDirectory();
$load = function ($filename): bool {
return file_exists($filename) && (bool) FileLoader::checkAndLoad($filename);

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,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

@ -5,10 +5,10 @@ declare(strict_types=1);
namespace Pest\Concerns;
use Closure;
use Pest\Expectation;
use Pest\Support\ChainableClosure;
use Pest\Support\ExceptionTrace;
use Pest\TestSuite;
use PHPUnit\Util\Test;
use PHPUnit\Framework\ExecutionOrderDependency;
use Throwable;
/**
@ -17,7 +17,7 @@ use Throwable;
*
* @internal
*/
trait TestCase
trait Testable
{
/**
* The test case description. Contains the first
@ -34,6 +34,38 @@ trait TestCase
*/
private $__test;
/**
* Holds a global/shared beforeEach ("set up") closure if one has been
* defined.
*
* @var Closure|null
*/
private $beforeEach = null;
/**
* Holds a global/shared afterEach ("tear down") closure if one has been
* defined.
*
* @var Closure|null
*/
private $afterEach = null;
/**
* Holds a global/shared beforeAll ("set up before") closure if one has been
* defined.
*
* @var Closure|null
*/
private static $beforeAll = null;
/**
* Holds a global/shared afterAll ("tear down after") closure if one has
* been defined.
*
* @var Closure|null
*/
private static $afterAll = null;
/**
* Creates a new instance of the test case.
*/
@ -55,6 +87,86 @@ trait TestCase
$this->setGroups($groups);
}
/**
* Add dependencies to the test case and map them to instances of ExecutionOrderDependency.
*/
public function addDependencies(array $tests): void
{
$className = get_class($this);
$tests = array_map(function (string $test) use ($className): ExecutionOrderDependency {
if (strpos($test, '::') === false) {
$test = "{$className}::{$test}";
}
return new ExecutionOrderDependency($test, null, '');
}, $tests);
$this->setDependencies($tests);
}
/**
* Add a shared/"global" before all test hook that will execute **before**
* the test defined `beforeAll` hook(s).
*/
public function addBeforeAll(?Closure $hook): void
{
if (!$hook) {
return;
}
self::$beforeAll = (self::$beforeAll instanceof Closure)
? ChainableClosure::fromStatic(self::$beforeAll, $hook)
: $hook;
}
/**
* Add a shared/"global" after all test hook that will execute **before**
* the test defined `afterAll` hook(s).
*/
public function addAfterAll(?Closure $hook): void
{
if (!$hook) {
return;
}
self::$afterAll = (self::$afterAll instanceof Closure)
? ChainableClosure::fromStatic(self::$afterAll, $hook)
: $hook;
}
/**
* Add a shared/"global" before each test hook that will execute **before**
* the test defined `beforeEach` hook.
*/
public function addBeforeEach(?Closure $hook): void
{
$this->addHook('beforeEach', $hook);
}
/**
* Add a shared/"global" after each test hook that will execute **before**
* the test defined `afterEach` hook.
*/
public function addAfterEach(?Closure $hook): void
{
$this->addHook('afterEach', $hook);
}
/**
* Add a shared/global hook and compose them if more than one is passed.
*/
private function addHook(string $property, ?Closure $hook): void
{
if (!$hook) {
return;
}
$this->{$property} = ($this->{$property} instanceof Closure)
? ChainableClosure::from($this->{$property}, $hook)
: $hook;
}
/**
* Returns the test case name. Note that, in Pest
* we ignore withDataset argument as the description
@ -79,6 +191,10 @@ trait TestCase
$beforeAll = TestSuite::getInstance()->beforeAll->get(self::$__filename);
if (self::$beforeAll instanceof Closure) {
$beforeAll = ChainableClosure::fromStatic(self::$beforeAll, $beforeAll);
}
call_user_func(Closure::bind($beforeAll, null, self::class));
}
@ -89,21 +205,15 @@ trait TestCase
{
$afterAll = TestSuite::getInstance()->afterAll->get(self::$__filename);
if (self::$afterAll instanceof Closure) {
$afterAll = ChainableClosure::fromStatic(self::$afterAll, $afterAll);
}
call_user_func(Closure::bind($afterAll, null, self::class));
parent::tearDownAfterClass();
}
/**
* Creates a new expectation.
*
* @param mixed $value
*/
public function expect($value): Expectation
{
return new Expectation($value);
}
/**
* Gets executed before the test.
*/
@ -115,6 +225,10 @@ trait TestCase
$beforeEach = TestSuite::getInstance()->beforeEach->get(self::$__filename);
if ($this->beforeEach instanceof Closure) {
$beforeEach = ChainableClosure::from($this->beforeEach, $beforeEach);
}
$this->__callClosure($beforeEach, func_get_args());
}
@ -125,6 +239,10 @@ trait TestCase
{
$afterEach = TestSuite::getInstance()->afterEach->get(self::$__filename);
if ($this->afterEach instanceof Closure) {
$afterEach = ChainableClosure::from($this->afterEach, $afterEach);
}
$this->__callClosure($afterEach, func_get_args());
parent::tearDown();

View File

@ -90,8 +90,6 @@ final class Command extends BaseCommand
*/
$this->arguments = AddsDefaults::to($this->arguments);
LoadStructure::in($this->testSuite->rootPath);
$testRunner = new TestRunner($this->arguments['loader']);
$testSuite = $this->arguments['test'];
@ -127,6 +125,8 @@ final class Command extends BaseCommand
*/
public function run(array $argv, bool $exit = true): int
{
LoadStructure::in($this->testSuite->rootPath);
$result = parent::run($argv, false);
/*
@ -148,5 +148,7 @@ final class Command extends BaseCommand
$version = Container::getInstance()->get(Version::class);
$version->handleArguments(['--version']);
parent::showHelp();
(new Help($this->output))();
}
}

37
src/Console/Help.php Normal file
View File

@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Pest\Console;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @internal
*/
final class Help
{
/** @var array<int, string> */
private const HELP_MESSAGES = [
'<comment>Pest Options:</comment>',
' <info>--init</info> Initialise a standard Pest configuration',
' <info>--coverage</info> Enable coverage and output to standard output',
' <info>--min=<fg=cyan><N></></info> Set the minimum required coverage percentage (<N>), and fail if not met',
' <info>--group=<fg=cyan><name></></info> Only runs tests from the specified group(s)',
];
/** @var OutputInterface */
private $output;
public function __construct(OutputInterface $output)
{
$this->output = $output;
}
public function __invoke(): void
{
foreach (self::HELP_MESSAGES as $message) {
$this->output->writeln($message);
}
}
}

View File

@ -18,14 +18,14 @@ final class Datasets
/**
* Holds the datasets.
*
* @var array<string, \Closure|iterable<int, mixed>>
* @var array<int|string, Closure|iterable<int|string, mixed>>
*/
private static $datasets = [];
/**
* Sets the given.
*
* @param Closure|iterable<int, mixed> $data
* @param Closure|iterable<int|string, mixed> $data
*/
public static function set(string $name, $data): void
{
@ -37,7 +37,7 @@ final class Datasets
}
/**
* @return Closure|iterable<int, mixed>
* @return Closure|iterable<int|string, mixed>
*/
public static function get(string $name)
{
@ -51,36 +51,34 @@ final class Datasets
/**
* Resolves the current dataset to an array value.
*
* @param Traversable<int, mixed>|Closure|iterable<int, 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
@ -111,8 +168,10 @@ final class Datasets
{
$exporter = new Exporter();
$nameInsert = is_string($key) ? \sprintf('data set "%s" ', $key) : '';
if (is_int($key)) {
return \sprintf('(%s)', $exporter->shortenedRecursiveExport($data));
}
return \sprintf(' with %s(%s)', $nameInsert, $exporter->shortenedRecursiveExport($data));
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

@ -1,24 +0,0 @@
<?php
declare(strict_types=1);
namespace Pest\Exceptions;
use InvalidArgumentException;
use NunoMaduro\Collision\Contracts\RenderlessEditor;
use NunoMaduro\Collision\Contracts\RenderlessTrace;
use Symfony\Component\Console\Exception\ExceptionInterface;
/**
* @internal
*/
final class InvalidUsesPath extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{
/**
* Creates a new instance of invalid uses path.
*/
public function __construct(string $target)
{
parent::__construct(sprintf('The path `%s` is not valid.', $target));
}
}

View File

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Pest\Exceptions;
use InvalidArgumentException;
use NunoMaduro\Collision\Contracts\RenderlessEditor;
use NunoMaduro\Collision\Contracts\RenderlessTrace;
use Symfony\Component\Console\Exception\ExceptionInterface;
/**
* @internal
*/
final class MissingDependency extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{
/**
* Creates a new instance of missing dependency.
*/
public function __construct(string $feature, string $dependency)
{
parent::__construct(sprintf('The feature "%s" requires "%s".', $feature, $dependency));
}
}

View File

@ -4,16 +4,30 @@ declare(strict_types=1);
namespace Pest;
use BadMethodCallException;
use Pest\Concerns\Extendable;
use Pest\Concerns\RetrievesValues;
use Pest\Support\Arr;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use SebastianBergmann\Exporter\Exporter;
/**
* @internal
*
* @property Expectation $not Creates the opposite expectation.
* @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.
*
@ -23,10 +37,19 @@ final class Expectation
*/
public $value;
/**
* The exporter instance, if any.
*
* @readonly
*
* @var Exporter|null
*/
private $exporter;
/**
* Creates a new expectation.
*
* @param mixed $value
* @param TValue $value
*/
public function __construct($value)
{
@ -36,13 +59,56 @@ final class Expectation
/**
* Creates a new expectation.
*
* @param mixed $value
* @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.
*/
@ -51,6 +117,60 @@ final class Expectation
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
@ -384,6 +504,17 @@ final class Expectation
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.
*/
@ -408,10 +539,27 @@ final class Expectation
* Asserts that the value array has the provided $key.
*
* @param string|int $key
* @param mixed $value
*/
public function toHaveKey($key): Expectation
public function toHaveKey($key, $value = null): Expectation
{
Assert::assertArrayHasKey($key, $this->value);
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;
}
@ -490,6 +638,36 @@ final class Expectation
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.
@ -499,7 +677,19 @@ final class Expectation
public function toMatchObject($object): Expectation
{
foreach ((array) $object as $property => $value) {
$this->toHaveProperty($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;
@ -526,12 +716,49 @@ final class Expectation
}
/**
* Dynamically calls methods on the class without any arguments.
* Exports the given value.
*
* @return Expectation
* @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

@ -5,14 +5,17 @@ declare(strict_types=1);
namespace Pest\Factories;
use Closure;
use ParseError;
use Pest\Concerns;
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;
/**
* @internal
@ -59,9 +62,9 @@ final class TestCaseFactory
/**
* Holds the dataset, if any.
*
* @var Closure|iterable<int, mixed>|string|null
* @var array<Closure|iterable<int|string, mixed>|string>
*/
public $dataset;
public $datasets = [];
/**
* The FQN of the test case class.
@ -76,7 +79,8 @@ final class TestCaseFactory
* @var array <int, string>
*/
public $traits = [
Concerns\TestCase::class,
Concerns\Testable::class,
Concerns\Expectable::class,
];
/**
@ -110,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();
@ -139,6 +147,7 @@ final class TestCaseFactory
$proxies->proxy($this);
$chains->chain($this);
/* @phpstan-ignore-next-line */
return call_user_func(Closure::bind($factoryTest, $this, get_class($this)), ...func_get_args());
};
@ -151,19 +160,11 @@ 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);
}
/**
* Makes a fully qualified class name from the current filename.
*/
public function getClassName(): string
{
return $this->makeClassFromFilename($this->filename);
}
/**
* Makes a fully qualified class name from the given filename.
*/
@ -176,7 +177,7 @@ final class TestCaseFactory
}, $filename);
}
$filename = (string) realpath($filename);
$filename = str_replace('\\\\', '\\', addslashes((string) realpath($filename)));
$rootPath = TestSuite::getInstance()->rootPath;
$relativePath = str_replace($rootPath . DIRECTORY_SEPARATOR, '', $filename);
$relativePath = dirname(ucfirst($relativePath)) . DIRECTORY_SEPARATOR . basename($relativePath, '.php');
@ -184,8 +185,12 @@ final class TestCaseFactory
// Strip out any %-encoded octets.
$relativePath = (string) preg_replace('|%[a-fA-F0-9][a-fA-F0-9]|', '', $relativePath);
// Remove escaped quote sequences (maintain namespace)
$relativePath = str_replace(array_map(function (string $quote): string {
return sprintf('\\%s', $quote);
}, ['\'', '"']), '', $relativePath);
// Limit to A-Z, a-z, 0-9, '_', '-'.
$relativePath = (string) preg_replace('/[^A-Za-z0-9.\\\]/', '', $relativePath);
$relativePath = (string) preg_replace('/[^A-Za-z0-9\\\\]/', '', $relativePath);
$classFQN = 'P\\' . $relativePath;
if (class_exists($classFQN)) {
@ -202,15 +207,24 @@ final class TestCaseFactory
$namespace = implode('\\', $partsFQN);
$baseClass = sprintf('\%s', $this->class);
eval("
namespace $namespace;
if ('' === trim($className)) {
$className = 'InvalidTestName' . Str::random();
$classFQN .= $className;
}
final class $className extends $baseClass implements $hasPrintableTestCaseClassFQN {
$traitsCode
try {
eval("
namespace $namespace;
private static \$__filename = '$filename';
}
");
final class $className extends $baseClass implements $hasPrintableTestCaseClassFQN {
$traitsCode
private static \$__filename = '$filename';
}
");
} catch (ParseError $caught) {
throw new RuntimeException(sprintf('Unable to create test case for test file at %s', $filename), 1, $caught);
}
return $classFQN;
}

140
src/Functions.php Normal file
View File

@ -0,0 +1,140 @@
<?php
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.
*/
function beforeAll(Closure $closure): void
{
TestSuite::getInstance()->beforeAll->set($closure);
}
}
if (!function_exists('beforeEach')) {
/**
* Runs the given closure before each test in the current file.
*
* @return BeforeEachCall|TestCase|mixed
*/
function beforeEach(Closure $closure = null): BeforeEachCall
{
$filename = Backtrace::file();
return new BeforeEachCall(TestSuite::getInstance(), $filename, $closure);
}
}
if (!function_exists('dataset')) {
/**
* Registers the given dataset.
*
* @param Closure|iterable<int|string, mixed> $dataset
*/
function dataset(string $name, $dataset): void
{
Datasets::set($name, $dataset);
}
}
if (!function_exists('uses')) {
/**
* The uses function binds the given
* arguments to test closures.
*/
function uses(string ...$classAndTraits): UsesCall
{
$filename = Backtrace::file();
return new UsesCall($filename, $classAndTraits);
}
}
if (!function_exists('test')) {
/**
* Adds the given closure as a test. The first argument
* is the test description; the second argument is
* a closure that contains the test expectations.
*
* @return TestCall|TestCase|mixed
*/
function test(string $description = null, Closure $closure = null)
{
if ($description === null && TestSuite::getInstance()->test !== null) {
return new HigherOrderTapProxy(TestSuite::getInstance()->test);
}
$filename = Backtrace::testFile();
return new TestCall(TestSuite::getInstance(), $filename, $description, $closure);
}
}
if (!function_exists('it')) {
/**
* Adds the given closure as a test. The first argument
* is the test description; the second argument is
* a closure that contains the test expectations.
*
* @return TestCall|TestCase|mixed
*/
function it(string $description, Closure $closure = null): TestCall
{
$description = sprintf('it %s', $description);
return test($description, $closure);
}
}
if (!function_exists('afterEach')) {
/**
* Runs the given closure after each test in the current file.
*
* @return AfterEachCall|TestCase|mixed
*/
function afterEach(Closure $closure = null): AfterEachCall
{
$filename = Backtrace::file();
return new AfterEachCall(TestSuite::getInstance(), $filename, $closure);
}
}
if (!function_exists('afterAll')) {
/**
* Runs the given closure after all tests in the current file.
*/
function afterAll(Closure $closure): void
{
TestSuite::getInstance()->afterAll->set($closure);
}
}

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

@ -8,6 +8,8 @@ use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Pest\Exceptions\InvalidConsoleArgument;
use function Pest\testDirectory;
use Pest\TestSuite;
/**
* @internal
@ -19,7 +21,8 @@ final class PestDatasetCommand extends Command
*
* @var string
*/
protected $signature = 'pest:dataset {name : The name of the dataset}';
protected $signature = 'pest:dataset {name : The name of the dataset}
{--test-directory=tests : The name of the tests directory}';
/**
* The console command description.
@ -33,10 +36,13 @@ final class PestDatasetCommand extends Command
*/
public function handle(): void
{
/* @phpstan-ignore-next-line */
TestSuite::getInstance(base_path(), $this->option('test-directory'));
/** @var string $name */
$name = $this->argument('name');
$relativePath = sprintf('tests/Datasets/%s.php', ucfirst($name));
$relativePath = sprintf(testDirectory('Datasets/%s.php'), ucfirst($name));
/* @phpstan-ignore-next-line */
$target = base_path($relativePath);

View File

@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Pest\Laravel\Commands;
use Laravel\Dusk\Console\DuskCommand;
/**
* @internal
*/
final class PestDuskCommand extends DuskCommand
{
/**
* The console command name.
*
* @var string
*/
protected $signature = 'pest:dusk
{--browse : Open a browser instead of using headless mode}
{--without-tty : Disable output to TTY}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run the Dusk tests for the application with Pest';
/**
* Get the PHP binary to execute.
*
* @return array<string>
*/
protected function binary()
{
if ('phpdbg' === PHP_SAPI) {
return [PHP_BINARY, '-qrr', 'vendor/pestphp/pest/bin/pest'];
}
return [PHP_BINARY, 'vendor/pestphp/pest/bin/pest'];
}
}

View File

@ -8,7 +8,8 @@ use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Pest\Console\Thanks;
use Pest\Exceptions\InvalidConsoleArgument;
use Pest\Support\Str;
use function Pest\testDirectory;
use Pest\TestSuite;
/**
* @internal
@ -20,7 +21,7 @@ final class PestInstallCommand extends Command
*
* @var string
*/
protected $signature = 'pest:install';
protected $signature = 'pest:install {--test-directory=tests : The name of the tests directory}';
/**
* The console command description.
@ -35,15 +36,14 @@ final class PestInstallCommand extends Command
public function handle(): void
{
/* @phpstan-ignore-next-line */
$pest = base_path('tests/Pest.php');
/* @phpstan-ignore-next-line */
$helpers = base_path('tests/Helpers.php');
$stubs = $this->isLumen() ? 'stubs/Lumen' : 'stubs/Laravel';
TestSuite::getInstance(base_path(), $this->option('test-directory'));
foreach ([$pest, $helpers] as $file) {
if (File::exists($file)) {
throw new InvalidConsoleArgument(sprintf('%s already exist', $file));
}
/* @phpstan-ignore-next-line */
$pest = base_path(testDirectory('Pest.php'));
$stubs = 'stubs/Laravel';
if (File::exists($pest)) {
throw new InvalidConsoleArgument(sprintf('%s already exist', $pest));
}
File::copy(implode(DIRECTORY_SEPARATOR, [
@ -52,26 +52,10 @@ final class PestInstallCommand extends Command
'Pest.php',
]), $pest);
File::copy(implode(DIRECTORY_SEPARATOR, [
dirname(__DIR__, 3),
$stubs,
'Helpers.php',
]), $helpers);
$this->output->success('`tests/Pest.php` created successfully.');
$this->output->success('`tests/Helpers.php` created successfully.');
if (!(bool) $this->option('no-interaction')) {
(new Thanks($this->output))();
}
}
/**
* Determine if this is a Lumen application.
*/
private function isLumen(): bool
{
/* @phpstan-ignore-next-line */
return Str::startsWith(app()->version(), 'Lumen');
}
}

View File

@ -8,6 +8,8 @@ use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Pest\Exceptions\InvalidConsoleArgument;
use Pest\Support\Str;
use function Pest\testDirectory;
use Pest\TestSuite;
/**
* @internal
@ -19,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}';
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}';
/**
* The console command description.
@ -33,12 +35,16 @@ final class PestTestCommand extends Command
*/
public function handle(): void
{
/* @phpstan-ignore-next-line */
TestSuite::getInstance(base_path(), $this->option('test-directory'));
/** @var string $name */
$name = $this->argument('name');
$type = ((bool) $this->option('unit')) ? 'Unit' : 'Feature';
$type = ((bool) $this->option('unit')) ? 'Unit' : (((bool) $this->option('dusk')) ? 'Browser' : 'Feature');
$relativePath = sprintf('tests/%s/%s.php',
$relativePath = sprintf(
testDirectory('%s/%s.php'),
$type,
ucfirst($name)
);

View File

@ -5,7 +5,9 @@ declare(strict_types=1);
namespace Pest\Laravel;
use Illuminate\Support\ServiceProvider;
use Laravel\Dusk\Console\DuskCommand;
use Pest\Laravel\Commands\PestDatasetCommand;
use Pest\Laravel\Commands\PestDuskCommand;
use Pest\Laravel\Commands\PestInstallCommand;
use Pest\Laravel\Commands\PestTestCommand;
@ -22,6 +24,12 @@ final class PestServiceProvider extends ServiceProvider
PestTestCommand::class,
PestDatasetCommand::class,
]);
if (class_exists(DuskCommand::class)) {
$this->commands([
PestDuskCommand::class,
]);
}
}
}
}

430
src/Logging/JUnit.php Normal file
View File

@ -0,0 +1,430 @@
<?php
declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Pest\Logging;
use function class_exists;
use DOMDocument;
use DOMElement;
use Exception;
use function get_class;
use function method_exists;
use Pest\Concerns\Testable;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\ExceptionWrapper;
use PHPUnit\Framework\SelfDescribing;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestFailure;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\Warning;
use PHPUnit\Util\Filter;
use PHPUnit\Util\Printer;
use PHPUnit\Util\Xml;
use ReflectionClass;
use ReflectionException;
use function sprintf;
use function str_replace;
use Throwable;
use function trim;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class JUnit extends Printer implements TestListener
{
/**
* @var DOMDocument
*/
private $document;
/**
* @var DOMElement
*/
private $root;
/**
* @var DOMElement[]
*/
private $testSuites = [];
/**
* @var int[]
*/
private $testSuiteTests = [0];
/**
* @var int[]
*/
private $testSuiteAssertions = [0];
/**
* @var int[]
*/
private $testSuiteErrors = [0];
/**
* @var int[]
*/
private $testSuiteWarnings = [0];
/**
* @var int[]
*/
private $testSuiteFailures = [0];
/**
* @var int[]
*/
private $testSuiteSkipped = [0];
/**
* @var int[]|float[]
*/
private $testSuiteTimes = [0];
/**
* @var int
*/
private $testSuiteLevel = 0;
/**
* @var DOMElement|null
*/
private $currentTestCase;
public function __construct(string $out)
{
$this->document = new DOMDocument('1.0', 'UTF-8');
$this->document->formatOutput = true;
$this->root = $this->document->createElement('testsuites');
$this->document->appendChild($this->root);
parent::__construct($out);
}
/**
* Flush buffer and close output.
*/
public function flush(): void
{
$this->write($this->getXML());
parent::flush();
}
/**
* An error occurred.
*/
public function addError(Test $test, Throwable $t, float $time): void
{
$this->doAddFault($test, $t, 'error');
$this->testSuiteErrors[$this->testSuiteLevel]++;
}
/**
* A warning occurred.
*/
public function addWarning(Test $test, Warning $e, float $time): void
{
$this->doAddFault($test, $e, 'warning');
$this->testSuiteWarnings[$this->testSuiteLevel]++;
}
/**
* A failure occurred.
*/
public function addFailure(Test $test, AssertionFailedError $e, float $time): void
{
$this->doAddFault($test, $e, 'failure');
$this->testSuiteFailures[$this->testSuiteLevel]++;
}
/**
* Incomplete test.
*/
public function addIncompleteTest(Test $test, Throwable $t, float $time): void
{
$this->doAddSkipped();
}
/**
* Risky test.
*/
public function addRiskyTest(Test $test, Throwable $t, float $time): void
{
}
/**
* Skipped test.
*/
public function addSkippedTest(Test $test, Throwable $t, float $time): void
{
$this->doAddSkipped();
}
/** @phpstan-ignore-next-line */
public function startTestSuite(TestSuite $suite): void
{
$testSuite = $this->document->createElement('testsuite');
$testSuite->setAttribute('name', $suite->getName());
if (class_exists($suite->getName(), false)) {
try {
$class = new ReflectionClass($suite->getName());
if ($class->hasMethod('__getFileName')) {
$fileName = $class->getMethod('__getFileName')->invoke(null);
} else {
$fileName = $class->getFileName();
}
$testSuite->setAttribute('file', $fileName);
} catch (ReflectionException $e) {
// @ignoreException
}
}
if ($this->testSuiteLevel > 0) {
$this->testSuites[$this->testSuiteLevel]->appendChild($testSuite);
} else {
$this->root->appendChild($testSuite);
}
$this->testSuiteLevel++;
$this->testSuites[$this->testSuiteLevel] = $testSuite;
$this->testSuiteTests[$this->testSuiteLevel] = 0;
$this->testSuiteAssertions[$this->testSuiteLevel] = 0;
$this->testSuiteErrors[$this->testSuiteLevel] = 0;
$this->testSuiteWarnings[$this->testSuiteLevel] = 0;
$this->testSuiteFailures[$this->testSuiteLevel] = 0;
$this->testSuiteSkipped[$this->testSuiteLevel] = 0;
$this->testSuiteTimes[$this->testSuiteLevel] = 0;
}
/** @phpstan-ignore-next-line */
public function endTestSuite(TestSuite $suite): void
{
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'tests',
(string) $this->testSuiteTests[$this->testSuiteLevel]
);
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'assertions',
(string) $this->testSuiteAssertions[$this->testSuiteLevel]
);
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'errors',
(string) $this->testSuiteErrors[$this->testSuiteLevel]
);
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'warnings',
(string) $this->testSuiteWarnings[$this->testSuiteLevel]
);
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'failures',
(string) $this->testSuiteFailures[$this->testSuiteLevel]
);
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'skipped',
(string) $this->testSuiteSkipped[$this->testSuiteLevel]
);
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'time',
sprintf('%F', $this->testSuiteTimes[$this->testSuiteLevel])
);
if ($this->testSuiteLevel > 1) {
$this->testSuiteTests[$this->testSuiteLevel - 1] += $this->testSuiteTests[$this->testSuiteLevel];
$this->testSuiteAssertions[$this->testSuiteLevel - 1] += $this->testSuiteAssertions[$this->testSuiteLevel];
$this->testSuiteErrors[$this->testSuiteLevel - 1] += $this->testSuiteErrors[$this->testSuiteLevel];
$this->testSuiteWarnings[$this->testSuiteLevel - 1] += $this->testSuiteWarnings[$this->testSuiteLevel];
$this->testSuiteFailures[$this->testSuiteLevel - 1] += $this->testSuiteFailures[$this->testSuiteLevel];
$this->testSuiteSkipped[$this->testSuiteLevel - 1] += $this->testSuiteSkipped[$this->testSuiteLevel];
$this->testSuiteTimes[$this->testSuiteLevel - 1] += $this->testSuiteTimes[$this->testSuiteLevel];
}
$this->testSuiteLevel--;
}
/**
* A test started.
*
* @param Test|Testable $test
*/
public function startTest(Test $test): void
{
$usesDataprovider = false;
if (method_exists($test, 'usesDataProvider')) {
$usesDataprovider = $test->usesDataProvider();
}
$testCase = $this->document->createElement('testcase');
$testCase->setAttribute('name', $test->getName());
try {
$class = new ReflectionClass($test);
// @codeCoverageIgnoreStart
} catch (ReflectionException $e) {
// @phpstan-ignore-next-line
throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
}
// @codeCoverageIgnoreEnd
$methodName = $test->getName(!$usesDataprovider);
if ($class->hasMethod($methodName)) {
try {
$method = $class->getMethod($methodName);
// @codeCoverageIgnoreStart
} catch (ReflectionException $e) {
// @phpstan-ignore-next-line
throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
}
// @codeCoverageIgnoreEnd
$testCase->setAttribute('class', $class->getName());
$testCase->setAttribute('classname', str_replace('\\', '.', $class->getName()));
$fileName = $class->getFileName();
if ($fileName !== false) {
$testCase->setAttribute('file', $fileName);
}
$testCase->setAttribute('line', (string) $method->getStartLine());
}
if (TeamCity::isPestTest($test)) {
$testCase->setAttribute('class', $test->getPrintableTestCaseName());
$testCase->setAttribute('classname', str_replace('\\', '.', $test->getPrintableTestCaseName()));
// @phpstan-ignore-next-line
$testCase->setAttribute('file', $test->__getFileName());
}
$this->currentTestCase = $testCase;
}
/**
* A test ended.
*/
public function endTest(Test $test, float $time): void
{
$numAssertions = 0;
if (method_exists($test, 'getNumAssertions')) {
$numAssertions = $test->getNumAssertions();
}
$this->testSuiteAssertions[$this->testSuiteLevel] += $numAssertions;
if ($this->currentTestCase !== null) {
$this->currentTestCase->setAttribute(
'assertions',
(string) $numAssertions
);
$this->currentTestCase->setAttribute(
'time',
sprintf('%F', $time)
);
$this->testSuites[$this->testSuiteLevel]->appendChild(
$this->currentTestCase
);
}
$this->testSuiteTests[$this->testSuiteLevel]++;
$this->testSuiteTimes[$this->testSuiteLevel] += $time;
$testOutput = '';
if (method_exists($test, 'hasOutput') && method_exists($test, 'getActualOutput')) {
$testOutput = $test->hasOutput() ? $test->getActualOutput() : '';
}
if ($testOutput !== '') {
$systemOut = $this->document->createElement(
'system-out',
Xml::prepareString($testOutput)
);
if ($this->currentTestCase !== null) {
$this->currentTestCase->appendChild($systemOut);
}
}
$this->currentTestCase = null;
}
/**
* Returns the XML as a string.
*/
public function getXML(): string
{
$xml = $this->document->saveXML();
if ($xml === false) {
return '';
}
return $xml;
}
private function doAddFault(Test $test, Throwable $t, string $type): void
{
if ($this->currentTestCase === null) {
return;
}
if ($test instanceof SelfDescribing) {
$buffer = $test->toString() . "\n";
} else {
$buffer = '';
}
$buffer .= trim(
TestFailure::exceptionToString($t) . "\n" .
Filter::getFilteredStacktrace($t)
);
$fault = $this->document->createElement(
$type,
Xml::prepareString($buffer)
);
if ($t instanceof ExceptionWrapper) {
$fault->setAttribute('type', $t->getClassName());
} else {
$fault->setAttribute('type', get_class($t));
}
$this->currentTestCase->appendChild($fault);
}
private function doAddSkipped(): void
{
if ($this->currentTestCase === null) {
return;
}
$skipped = $this->document->createElement('skipped');
$this->currentTestCase->appendChild($skipped);
$this->testSuiteSkipped[$this->testSuiteLevel]++;
}
}

View File

@ -2,10 +2,10 @@
declare(strict_types=1);
namespace Pest;
namespace Pest\Logging;
use function getmypid;
use Pest\Concerns\TestCase;
use Pest\Concerns\Testable;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestResult;
@ -56,7 +56,7 @@ final class TeamCity extends DefaultResultPrinter
/** @phpstan-ignore-next-line */
public function startTestSuite(TestSuite $suite): void
{
$this->flowId = getmypid();
$this->flowId = (int) getmypid();
if (!$this->isSummaryTestCountPrinted) {
$this->printEvent(
@ -109,7 +109,7 @@ final class TeamCity extends DefaultResultPrinter
}
/**
* @param Test|TestCase $test
* @param Test|Testable $test
*/
public function startTest(Test $test): void
{
@ -121,13 +121,13 @@ final class TeamCity extends DefaultResultPrinter
$this->printEvent('testStarted', [
self::NAME => $test->getName(),
/* @phpstan-ignore-next-line */
// @phpstan-ignore-next-line
self::LOCATION_HINT => self::PROTOCOL . $test->toString(),
]);
}
/**
* @param Test|TestCase $test
* @param Test|Testable $test
*/
public function endTest(Test $test, float $time): void
{
@ -144,7 +144,7 @@ final class TeamCity extends DefaultResultPrinter
}
/**
* @param Test|TestCase $test
* @param Test|Testable $test
*/
public function addError(Test $test, Throwable $t, float $time): void
{
@ -154,7 +154,7 @@ final class TeamCity extends DefaultResultPrinter
/**
* @phpstan-ignore-next-line
*
* @param Test|TestCase $test
* @param Test|Testable $test
*/
public function addWarning(Test $test, Warning $e, float $time): void
{
@ -203,8 +203,11 @@ final class TeamCity extends DefaultResultPrinter
return (int) round($time * 1000);
}
private static function isPestTest(Test $test): bool
public static function isPestTest(Test $test): bool
{
return in_array(TestCase::class, class_uses($test), true);
/** @var array<string, string> $uses */
$uses = class_uses($test);
return in_array(Testable::class, $uses, true);
}
}

View File

@ -41,7 +41,7 @@ final class OppositeExpectation
continue;
}
$this->throwExpectationFailedExpection('toHaveKey', [$key]);
$this->throwExpectationFailedException('toHaveKey', [$key]);
}
return $this->original;
@ -62,7 +62,7 @@ final class OppositeExpectation
}
// @phpstan-ignore-next-line
$this->throwExpectationFailedExpection($name, $arguments);
$this->throwExpectationFailedException($name, $arguments);
}
/**
@ -78,16 +78,15 @@ final class OppositeExpectation
}
// @phpstan-ignore-next-line
$this->throwExpectationFailedExpection($name);
$this->throwExpectationFailedException($name);
}
/**
* Creates a new expectation failed exception
* with a nice readable message.
* Creates a new expectation failed exception with a nice readable message.
*
* @param array<int, mixed> $arguments
*/
private function throwExpectationFailedExpection(string $name, array $arguments = []): void
private function throwExpectationFailedException(string $name, array $arguments = []): void
{
$exporter = new Exporter();

View File

@ -7,15 +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 PHPUnit\Framework\ExecutionOrderDependency;
use SebastianBergmann\Exporter\Exporter;
/**
* @method \Pest\Expectation expect(mixed $value)
*
* @internal
*
* @mixin HigherOrderCallables
*/
final class TestCall
{
@ -59,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
@ -78,11 +82,13 @@ final class TestCall
* Runs the current test multiple times with
* each item of the given `iterable`.
*
* @param \Closure|iterable<int, 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;
}
@ -92,15 +98,9 @@ final class TestCall
*/
public function depends(string ...$tests): TestCall
{
$className = $this->testCaseFactory->getClassName();
$tests = array_map(function (string $test) use ($className): ExecutionOrderDependency {
return ExecutionOrderDependency::createFromDependsAnnotation($className, $test);
}, $tests);
$this->testCaseFactory
->factoryProxies
->add(Backtrace::file(), Backtrace::line(), 'setDependencies', [$tests]);
->add(Backtrace::file(), Backtrace::line(), 'addDependencies', [$tests]);
return $this;
}
@ -148,21 +148,37 @@ final class TestCall
? $conditionOrMessage
: $message;
if ($condition() !== false) {
$this->testCaseFactory
->chains
->add(Backtrace::file(), Backtrace::line(), 'markTestSkipped', [$message]);
}
$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
@ -173,7 +189,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

@ -4,7 +4,7 @@ declare(strict_types=1);
namespace Pest\PendingObjects;
use Pest\Exceptions\InvalidUsesPath;
use Closure;
use Pest\TestSuite;
/**
@ -12,6 +12,20 @@ use Pest\TestSuite;
*/
final class UsesCall
{
/**
* Contains a global before each hook closure to be executed.
*
* Array indices here matter. They are mapped as follows:
*
* - `0` => `beforeAll`
* - `1` => `beforeEach`
* - `2` => `afterEach`
* - `3` => `afterAll`
*
* @var array<int, Closure>
*/
private $hooks = [];
/**
* Holds the class and traits.
*
@ -54,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
{
@ -77,14 +91,13 @@ final class UsesCall
]);
}, $targets);
$this->targets = array_map(function ($target): string {
$isValid = is_dir($target) || file_exists($target);
if (!$isValid) {
throw new InvalidUsesPath($target);
$this->targets = array_reduce($targets, function (array $accumulator, string $target): array {
if (is_dir($target) || file_exists($target)) {
$accumulator[] = (string) realpath($target);
}
return (string) realpath($target);
}, $targets);
return $accumulator;
}, []);
}
/**
@ -97,11 +110,56 @@ final class UsesCall
return $this;
}
/**
* Sets the global beforeAll test hook.
*/
public function beforeAll(Closure $hook): UsesCall
{
$this->hooks[0] = $hook;
return $this;
}
/**
* Sets the global beforeEach test hook.
*/
public function beforeEach(Closure $hook): UsesCall
{
$this->hooks[1] = $hook;
return $this;
}
/**
* Sets the global afterEach test hook.
*/
public function afterEach(Closure $hook): UsesCall
{
$this->hooks[2] = $hook;
return $this;
}
/**
* Sets the global afterAll test hook.
*/
public function afterAll(Closure $hook): UsesCall
{
$this->hooks[3] = $hook;
return $this;
}
/**
* Dispatch the creation of uses.
*/
public function __destruct()
{
TestSuite::getInstance()->tests->use($this->classAndTraits, $this->groups, $this->targets);
TestSuite::getInstance()->tests->use(
$this->classAndTraits,
$this->groups,
$this->targets,
$this->hooks,
);
}
}

View File

@ -6,5 +6,10 @@ namespace Pest;
function version(): string
{
return '0.3.11';
return '1.10.0';
}
function testDirectory(string $file = ''): string
{
return TestSuite::getInstance()->testPath . '/' . $file;
}

View File

@ -22,7 +22,7 @@ final class Plugin
public static function uses(string ...$traits): void
{
self::$callables[] = function () use ($traits): void {
uses(...$traits)->in(TestSuite::getInstance()->rootPath . DIRECTORY_SEPARATOR . 'tests');
uses(...$traits)->in(TestSuite::getInstance()->rootPath . DIRECTORY_SEPARATOR . testDirectory());
};
}
}

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

@ -41,7 +41,6 @@ final class AfterEachRepository
return ChainableClosure::from(function (): void {
if (class_exists(Mockery::class)) {
/* @phpstan-ignore-next-line */
if ($container = Mockery::getContainer()) {
/* @phpstan-ignore-next-line */
$this->addToAssertionCount($container->mockery_getExpectationCount());

View File

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Pest\Repositories;
use Closure;
use Pest\Exceptions\ShouldNotHappen;
use Pest\Exceptions\TestAlreadyExist;
use Pest\Exceptions\TestCaseAlreadyInUse;
@ -18,13 +19,18 @@ use PHPUnit\Framework\TestCase;
*/
final class TestRepository
{
/**
* @var string
*/
private const SEPARATOR = '>>>';
/**
* @var array<string, TestCaseFactory>
*/
private $state = [];
/**
* @var array<string, array<int, array<int, string>>>
* @var array<string, array<int, array<int, string|Closure>>>
*/
private $uses = [];
@ -46,12 +52,13 @@ final class TestRepository
};
foreach ($this->uses as $path => $uses) {
[$classOrTraits, $groups] = $uses;
$setClassName = function (TestCaseFactory $testCase, string $key) use ($path, $classOrTraits, $groups, $startsWith): void {
[$filename] = explode('@', $key);
[$classOrTraits, $groups, $hooks] = $uses;
$setClassName = function (TestCaseFactory $testCase, string $key) use ($path, $classOrTraits, $groups, $startsWith, $hooks): void {
[$filename] = explode(self::SEPARATOR, $key);
if ((!is_dir($path) && $filename === $path) || (is_dir($path) && $startsWith($filename, $path))) {
foreach ($classOrTraits as $class) {
foreach ($classOrTraits as $class) { /** @var string $class */
if (class_exists($class)) {
if ($testCase->class !== TestCase::class) {
throw new TestCaseAlreadyInUse($testCase->class, $class, $filename);
@ -62,10 +69,12 @@ final class TestRepository
}
}
$testCase
->factoryProxies
// Consider set the real line here.
->add($filename, 0, 'addGroups', [$groups]);
// IDEA: Consider set the real lines on these.
$testCase->factoryProxies->add($filename, 0, 'addGroups', [$groups]);
$testCase->factoryProxies->add($filename, 0, 'addBeforeAll', [$hooks[0] ?? null]);
$testCase->factoryProxies->add($filename, 0, 'addBeforeEach', [$hooks[1] ?? null]);
$testCase->factoryProxies->add($filename, 0, 'addAfterEach', [$hooks[2] ?? null]);
$testCase->factoryProxies->add($filename, 0, 'addAfterAll', [$hooks[3] ?? null]);
}
};
@ -81,7 +90,7 @@ final class TestRepository
$state = count($onlyState) > 0 ? $onlyState : $this->state;
foreach ($state as $testFactory) {
/* @var TestCaseFactory $testFactory */
/** @var TestCaseFactory $testFactory */
$tests = $testFactory->build($testSuite);
foreach ($tests as $test) {
$each($test);
@ -92,11 +101,12 @@ final class TestRepository
/**
* Uses the given `$testCaseClass` on the given `$paths`.
*
* @param array<int, string> $classOrTraits
* @param array<int, string> $groups
* @param array<int, string> $paths
* @param array<int, string> $classOrTraits
* @param array<int, string> $groups
* @param array<int, string> $paths
* @param array<int, Closure> $hooks
*/
public function use(array $classOrTraits, array $groups, array $paths): void
public function use(array $classOrTraits, array $groups, array $paths, array $hooks): void
{
foreach ($classOrTraits as $classOrTrait) {
if (!class_exists($classOrTrait) && !trait_exists($classOrTrait)) {
@ -109,9 +119,10 @@ final class TestRepository
$this->uses[$path] = [
array_merge($this->uses[$path][0], $classOrTraits),
array_merge($this->uses[$path][1], $groups),
$this->uses[$path][2] + $hooks, // NOTE: array_merge will destroy numeric indices
];
} else {
$this->uses[$path] = [$classOrTraits, $groups];
$this->uses[$path] = [$classOrTraits, $groups, $hooks];
}
}
}
@ -125,10 +136,10 @@ 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;
$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;
}
}

View File

@ -12,13 +12,28 @@ use Closure;
final class ChainableClosure
{
/**
* Calls the given `$closure` and chains the the `$next` closure.
* Calls the given `$closure` and chains the `$next` closure.
*/
public static function from(Closure $closure, Closure $next): Closure
{
return function () use ($closure, $next): void {
/* @phpstan-ignore-next-line */
call_user_func_array(Closure::bind($closure, $this, get_class($this)), func_get_args());
/* @phpstan-ignore-next-line */
call_user_func_array(Closure::bind($next, $this, get_class($this)), func_get_args());
};
}
/**
* Call the given static `$closure` and chains the `$next` closure.
*/
public static function fromStatic(Closure $closure, Closure $next): Closure
{
return static function () use ($closure, $next): void {
/* @phpstan-ignore-next-line */
call_user_func_array(Closure::bind($closure, null, self::class), func_get_args());
/* @phpstan-ignore-next-line */
call_user_func_array(Closure::bind($next, null, self::class), func_get_args());
};
}
}

View File

@ -79,6 +79,7 @@ final class Container
if ($candidate === null) {
$type = $param->getType();
/* @phpstan-ignore-next-line */
if ($type !== null && $type->isBuiltin()) {
$candidate = $param->getName();
} else {

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

@ -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::bindCallable($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::bindCallable($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);
}
/**

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,7 +12,6 @@ use ReflectionException;
use ReflectionFunction;
use ReflectionNamedType;
use ReflectionParameter;
use ReflectionProperty;
/**
* @internal
@ -42,15 +41,25 @@ 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);
}
/**
* Infers the file name from the given closure.
*/

View File

@ -9,6 +9,25 @@ namespace Pest\Support;
*/
final class Str
{
/**
* Pool of alpha-numeric characters for generating (unsafe) random strings
* from.
*/
private const POOL = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
/**
* Create a (unsecure & non-cryptographically safe) random alpha-numeric
* string value.
*
* @param int $length the length of the resulting randomized string
*
* @see https://github.com/laravel/framework/blob/4.2/src/Illuminate/Support/Str.php#L240-L242
*/
public static function random(int $length = 16): string
{
return substr(str_shuffle(str_repeat(self::POOL, 5)), 0, $length);
}
/**
* Checks if the given `$target` starts with the given `$search`.
*/

View File

@ -66,6 +66,13 @@ final class TestSuite
*/
public $rootPath;
/**
* Holds the test path.
*
* @var string
*/
public $testPath;
/**
* Holds an instance of the test suite.
*
@ -76,7 +83,7 @@ final class TestSuite
/**
* Creates a new instance of the test suite.
*/
public function __construct(string $rootPath)
public function __construct(string $rootPath, string $testPath)
{
$this->beforeAll = new BeforeAllRepository();
$this->beforeEach = new BeforeEachRepository();
@ -85,15 +92,16 @@ final class TestSuite
$this->afterAll = new AfterAllRepository();
$this->rootPath = (string) realpath($rootPath);
$this->testPath = $testPath;
}
/**
* Returns the current instance of the test suite.
*/
public static function getInstance(string $rootPath = null): TestSuite
public static function getInstance(string $rootPath = null, string $testPath = null): TestSuite
{
if (is_string($rootPath)) {
self::$instance = new TestSuite($rootPath);
if (is_string($rootPath) && is_string($testPath)) {
self::$instance = new TestSuite($rootPath, $testPath);
foreach (Plugin::$callables as $callable) {
$callable();

View File

@ -1,119 +0,0 @@
<?php
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\HigherOrderTapProxy;
use Pest\TestSuite;
use PHPUnit\Framework\TestCase;
/**
* Runs the given closure before all tests in the current file.
*/
function beforeAll(Closure $closure): void
{
TestSuite::getInstance()->beforeAll->set($closure);
}
/**
* Runs the given closure before each test in the current file.
*
* @return BeforeEachCall|TestCase|mixed
*/
function beforeEach(Closure $closure = null): BeforeEachCall
{
$filename = Backtrace::file();
return new BeforeEachCall(TestSuite::getInstance(), $filename, $closure);
}
/**
* Registers the given dataset.
*
* @param Closure|iterable $dataset
*/
function dataset(string $name, $dataset): void
{
Datasets::set($name, $dataset);
}
/**
* The uses function binds the given
* arguments to test closures.
*/
function uses(string ...$classAndTraits): UsesCall
{
$filename = Backtrace::file();
return new UsesCall($filename, $classAndTraits);
}
/**
* Adds the given closure as a test. The first argument
* is the test description; the second argument is
* a closure that contains the test expectations.
*
* @return TestCall|TestCase|mixed
*/
function test(string $description = null, Closure $closure = null)
{
if ($description === null && TestSuite::getInstance()->test) {
return new HigherOrderTapProxy(TestSuite::getInstance()->test);
}
$filename = Backtrace::testFile();
return new TestCall(TestSuite::getInstance(), $filename, $description, $closure);
}
/**
* Adds the given closure as a test. The first argument
* is the test description; the second argument is
* a closure that contains the test expectations.
*
* @return TestCall|TestCase|mixed
*/
function it(string $description, Closure $closure = null): TestCall
{
$description = sprintf('it %s', $description);
return test($description, $closure);
}
/**
* Runs the given closure after each test in the current file.
*
* @return AfterEachCall|TestCase|mixed
*/
function afterEach(Closure $closure = null): AfterEachCall
{
$filename = Backtrace::file();
return new AfterEachCall(TestSuite::getInstance(), $filename, $closure);
}
/**
* Runs the given closure after all tests in the current file.
*/
function afterAll(Closure $closure = null): void
{
TestSuite::getInstance()->afterAll->set($closure);
}
/**
* Creates a new expectation.
*
* @param mixed $value the Value
*
* @return Expectation
*/
function expect($value)
{
return test()->expect($value);
}

10
stubs/Browser.php Normal file
View File

@ -0,0 +1,10 @@
<?php
use Laravel\Dusk\Browser;
it('has {name} page', function () {
$this->browse(function (Browser $browser) {
$browser->visit('/{name}')
->assertSee('{name}');
});
});

View File

@ -1,11 +0,0 @@
<?php
namespace Tests;
/**
* A basic assert example.
*/
function assertExample(): void
{
test()->assertTrue(true);
}

View File

@ -1,3 +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()
{
// ..
}

View File

@ -1,11 +0,0 @@
<?php
namespace Tests;
/**
* A basic assert example.
*/
function assertExample(): void
{
test()->assertTrue(true);
}

View File

@ -1,3 +0,0 @@
<?php
uses(TestCase::class)->in(__DIR__);

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()
{
// ..
}

View File

@ -5,13 +5,14 @@
colors="true"
>
<testsuites>
<testsuite name="Application Test Suite">
<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

@ -0,0 +1,5 @@
Pest Options:
--init Initialise a standard Pest configuration
--coverage Enable coverage and output to standard output
--min=<N> Set the minimum required coverage percentage (<N>), and fail if not met
--group=<name> Only runs tests from the specified group(s)

View File

@ -2,221 +2,6 @@
PASS Tests\CustomTestCase\ExecutedTest
✓ that gets executed
PASS Tests\Expect\not
✓ not property calls
PASS Tests\Expect\toBe
✓ expect true → toBeTrue → and false → toBeFalse
✓ strict comparisons
✓ failures
✓ not failures
PASS Tests\Expect\toBeArray
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeBool
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeCallable
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeDirectory
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeEmpty
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeFalse
✓ strict comparisons
✓ failures
✓ not failures
PASS Tests\Expect\toBeFile
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeFloat
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeGreatherThan
✓ passes
✓ failures
✓ not failures
PASS Tests\Expect\toBeGreatherThanOrEqual
✓ passes
✓ failures
✓ not failures
PASS Tests\Expect\toBeInfinite
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeInstanceOf
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeInt
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeIterable
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeLessThan
✓ passes
✓ failures
✓ not failures
PASS Tests\Expect\toBeLessThanOrEqual
✓ passes
✓ failures
✓ not failures
PASS Tests\Expect\toBeNAN
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeNull
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeNumeric
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeObject
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeReadableDirectory
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeReadableFile
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeResource
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeScalar
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeString
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeTrue
✓ strict comparisons
✓ failures
✓ not failures
PASS Tests\Expect\toBeWritableDirectory
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toBeWritableFile
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toContain
✓ passes strings
✓ passes arrays
✓ failures
✓ not failures
PASS Tests\Expect\toEndWith
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toEqual
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toEqualCanonicalizing
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toEqualWithDelta
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toHaveCount
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toHaveKey
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toHaveKeys
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toHaveProperty
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toMatch
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toMatchConstraint
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toMatchObject
✓ pass
✓ failures
✓ not failures
PASS Tests\Expect\toStartWith
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\AfterAll
✓ deletes file after all
@ -232,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
@ -255,8 +46,8 @@
✓ eager wrapped registered datasets with (1)
✓ eager wrapped registered datasets with (2)
✓ eager registered wrapped datasets did the job right
✓ named datasets with data set "one" (1)
✓ named datasets with data set "two" (2)
✓ named datasets with data set "one"
✓ named datasets with data set "two"
✓ named datasets did the job right
✓ lazy named datasets with (Bar Object (...))
✓ it creates unique test case names with ('Name 1', Pest\Plugin Object (), true) #1
@ -266,22 +57,370 @@
✓ 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
PASS Tests\Features\Exceptions
✓ it gives access the the underlying expectException
✓ it catch exceptions
✓ it catch exceptions and messages
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
PASS Tests\Features\Expect\HigherOrder\methodsAndProperties
✓ it can access methods and properties
✓ it can handle nested methods and properties
✓ it can start a new higher order expectation using the and syntax
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
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\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\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\toBeWritableDirectory
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toBeWritableFile
✓ pass
✓ failures
✓ not failures
PASS Tests\Features\Expect\toContain
✓ passes strings
✓ passes arrays
✓ failures
✓ not failures
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\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\Helpers
✓ it can set/get properties on $this
✓ it throws error if property do not exist
✓ it allows to call underlying protected/private methods
✓ it throws error if method do not exist
✓ it can forward unexpected calls to any global function
✓ it can use helpers from helpers file
PASS Tests\Features\HigherOrderTests
✓ it proxies calls to object
✓ it is capable doing multiple assertions
✓ it resolves expect callables correctly
✓ it can tap into the test
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
@ -291,10 +430,8 @@
✓ it can call chained macro method
✓ it will throw exception from call if no macro exists
PASS Tests\Features\Mocks
✓ it has bar
PASS Tests\Features\PendingHigherOrderTests
✓ get 'foo'
✓ get 'foo' → get 'bar' → expect true → toBeTrue
✓ get 'foo' → expect true → toBeTrue
@ -318,6 +455,43 @@
PASS Tests\Fixtures\ExampleTest
✓ it example 2
PASS Tests\Hooks\AfterAllTest
✓ global afterAll execution order
PASS Tests\Hooks\AfterEachTest
✓ global afterEach execution order
PASS Tests\Hooks\BeforeAllTest
✓ global beforeAll execution order
PASS Tests\Hooks\BeforeEachTest
✓ global beforeEach execution order
PASS Tests\PHPUnit\CustomAffixes\InvalidTestName
✓ it runs file names like `@#$%^&()-_=+.php`
PASS Tests\PHPUnit\CustomAffixes\ATestWithSpaces
✓ it runs file names like `A Test With Spaces.php`
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`
PASS Tests\PHPUnit\CustomAffixes\TestCaseWithQuotes
✓ it runs file names like `Test 'Case' With Quotes.php`
PASS Tests\PHPUnit\CustomAffixes\kebabcasespec
✓ it runs file names like `kebab-case-spec.php`
PASS Tests\PHPUnit\CustomAffixes\snakecasespec
✓ it runs file names like `snake_case_spec.php`
PASS Tests\PHPUnit\CustomTestCase\UsesPerDirectory
✓ closure was bound to CustomTestCase
@ -348,8 +522,15 @@
✓ it throws exception when `process isolation` is true
✓ it do not throws exception when `process isolation` is false
PASS Tests\Unit\Console\Help
✓ it outputs the help information when --help is used
PASS Tests\Unit\Datasets
✓ it show the names of named datasets in their description
✓ 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
@ -374,6 +555,9 @@
PASS Tests\Unit\TestSuite
✓ it does not allow to add the same test description twice
PASS Tests\Visual\Help
✓ visual snapshot of help command output
PASS Tests\Visual\SingleTestOrDirectory
✓ allows to run a single test
✓ allows to run a directory
@ -386,10 +570,16 @@
PASS Tests\Features\Depends
✓ first
✓ second
✓ it asserts true is true
✓ depends
✓ depends with ...params
✓ depends with defined arguments
✓ depends run test only once
✓ depends works with the correct test name
Tests: 7 skipped, 231 passed
PASS Tests\Features\DependsInheritance
✓ it is a test
✓ it uses correct parent class
Tests: 4 incompleted, 7 skipped, 365 passed

View File

@ -1,15 +0,0 @@
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect(['a' => 1, 'b', 'c' => 'world'])->toHaveKeys(['a', 'c']);
});
test('failures', function () {
expect(['a' => 1, 'b', 'c' => 'world'])->toHaveKeys(['a', 'd']);
})->throws(ExpectationFailedException::class);
test('not failures', function () {
expect(['a' => 1, 'hello' => 'world', 'c'])->not->toHaveKeys(['hello', 'c']);
})->throws(ExpectationFailedException::class);

View File

@ -6,7 +6,7 @@ beforeEach(function () use ($state) {
$this->state = $state;
});
afterEach(function () use ($state) {
afterEach(function () {
$this->state->bar = 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

@ -116,7 +116,7 @@ $namedDatasets = [
new Bar(),
];
test('lazy named datasets', function ($text) use ($state, $datasets) {
test('lazy named datasets', function ($text) {
expect(true)->toBeTrue();
})->with($namedDatasets);
@ -137,3 +137,89 @@ 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');
});

View File

@ -32,3 +32,7 @@ test('depends with defined arguments', function (string $first, string $second)
test('depends run test only once', function () use (&$runCounter) {
expect($runCounter)->toBe(2);
})->depends('first', 'second');
// Regression tests. See https://github.com/pestphp/pest/pull/216
it('asserts true is true')->assertTrue(true);
test('depends works with the correct test name')->assertTrue(true)->depends('it asserts true is true');

View File

@ -0,0 +1,22 @@
<?php
use PHPUnit\Framework\TestCase;
class InheritanceTest extends TestCase
{
public function foo()
{
return 'bar';
}
}
uses(InheritanceTest::class);
it('is a test', function () {
expect(true)->toBeTrue();
});
it('uses correct parent class', function () {
expect(get_parent_class($this))->toEqual(InheritanceTest::class);
expect($this->foo())->toEqual('bar');
})->depends('it is a test');

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,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);
});

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