Compare commits

...

173 Commits

Author SHA1 Message Date
27fbe3efcc docs: updates changelog 2020-08-06 21:18:26 +01:00
d0eb2f15cd chore: keeps phpunit 9.2 for pest 0.2 2020-08-06 21:15:46 +01:00
1241e929b1 docs: updates changelog 2020-07-01 20:26:18 +02:00
db7c4b174f refactor: thanks 2020-07-01 20:23:00 +02:00
460ce45349 Merge pull request #118 from owenvoke/feature/thanks
Add --thanks option plugin
2020-07-01 18:51:54 +02:00
8e203e914e Add test for --thanks 2020-07-01 10:27:12 +01:00
64a8ed04ff Add --thanks option plugin 2020-07-01 10:25:22 +01:00
234b6847ad Merge pull request #115 from owenvoke/feature/changelog
Add next section link to the CHANGELOG
2020-06-29 23:12:30 +02:00
933820c8d3 Add next section link to the CHANGELOG
See: https://github.com/pestphp/website/pull/66#discussion_r447211656
2020-06-29 21:45:59 +01:00
4e9587da59 Merge pull request #114 from rkozlov95/normalize-changelogs
docs: updates changelog
2020-06-29 01:25:01 +02:00
60a5db14ba docs: updates changelog 2020-06-29 02:23:49 +03:00
7ea3e02afa Merge pull request #112 from rkozlov95/add-pull-request-template
add pull request template
2020-06-28 01:48:18 +02:00
421c52fb74 add pull request template 2020-06-28 02:18:24 +03:00
a3644f7efa tests: fixes windows tests 2020-06-26 18:42:57 +02:00
c7326f430b chore: fixes required version of collision 2020-06-26 18:28:47 +02:00
9ea51caf3f feat: adds --version option 2020-06-26 18:17:11 +02:00
cb4c9563bd Merge pull request #109 from Gummibeer/patch-1
pass calls to overloaded method if possible
2020-06-21 18:53:12 +02:00
fac44d9afe revert to first approach by calling __call directly 2020-06-21 18:46:11 +02:00
6e27c6d85d fix tye check 2020-06-21 18:44:04 +02:00
9a0cfaf339 use shorter beforeEach chain syntax 2020-06-21 18:39:47 +02:00
321b3e8df3 use call_user_func_array instead of direct calling __call
add check for __callStatic
2020-06-21 18:31:09 +02:00
bff97418ed do not return $this 2020-06-21 18:27:43 +02:00
a47ad6a1d3 Merge branch 'master' of https://github.com/pestphp/pest into patch-1
# Conflicts:
#	tests/.snapshots/success.txt
2020-06-21 18:25:57 +02:00
74c14808cf rebuild success.txt 2020-06-21 18:24:49 +02:00
eff2d7f613 fix test and add exception test 2020-06-21 18:23:39 +02:00
e135979f34 revert null old-target logic 2020-06-21 18:22:34 +02:00
15edde8e87 docs: updates changelog 2020-06-21 17:43:28 +02:00
211f5c2433 tests: makes incomplete tests success 2020-06-21 17:40:41 +02:00
5d58d58f71 chore: updates phpstan config 2020-06-21 17:40:29 +02:00
d5a4008d3e chore: bumps dev dependencies 2020-06-21 17:40:17 +02:00
1bf802268f Merge pull request #103 from nuernbergerA/feature/depends
Add support for PHPUnit's @depends
2020-06-21 17:10:58 +02:00
807a4b004f Merge branch 'master' into feature/depends 2020-06-21 17:10:51 +02:00
53a8c7b05e add test for new macro behavior 2020-06-21 14:02:56 +02:00
ef5715ce10 ignore null return values and re-use old target 2020-06-21 14:02:42 +02:00
0c04882389 use long exception variable name 2020-06-21 13:08:06 +02:00
323c5f211f pass calls to overloaded method if possible
fix #108
2020-06-21 11:55:32 +02:00
f7a3fa15f4 Merge pull request #101 from fetzi/bugfix/dataset-name-creation
Fix dataset name creation with objects
2020-06-20 21:42:16 +02:00
6dd3ca20e4 Also handle multiple descriptions within whole dataset 2020-06-20 11:29:07 +02:00
d9ea378819 Only append numbers when data set desc is the same 2020-06-20 09:53:38 +02:00
6aa0356570 add more tests 2020-06-19 23:22:14 +02:00
45b0d5d899 feat(depends): adds phpdocs 2020-06-19 21:39:01 +02:00
5be1edd7b7 added missing return types 2020-06-19 21:25:38 +02:00
75f7ee0acf added feedback from @nunomaduro 2020-06-19 20:39:09 +02:00
d0a74931dd implemented support for PHPUnit's @depends 2020-06-19 19:50:54 +02:00
0738e113ad Fix dataset name creation with objects
fixes #98
2020-06-19 16:03:47 +02:00
283d8f3e03 docs: updates changelog 2020-06-17 18:57:54 +02:00
1c3e820283 Merge pull request #97 from fkraefft/fix-traits
Fix in Test Repository use method.
2020-06-17 18:47:00 +02:00
accd4eb7b4 Multiple global uses registered in the same path test added. 2020-06-17 11:57:08 -03:00
ae7991c7e9 Style fixes. 2020-06-17 11:56:24 -03:00
e9e72d607e vscode folder added to gitignore. 2020-06-17 11:55:48 -03:00
40766f9275 Fix in Test Repository use method. 2020-06-17 09:59:46 -03:00
a3fd60ce4d docs: updates changelog 2020-06-14 17:01:15 +02:00
f9a3e39902 tests: removes test coverage for now
Co-Authored-By: Johannes Pichler <fetzi@users.noreply.github.com>
2020-06-14 16:35:30 +02:00
06d707fb41 feat(container): makes it autowirable
Co-Authored-By: Johannes Pichler <fetzi@users.noreply.github.com>
2020-06-14 16:25:51 +02:00
a70c64d704 tests: removes unused file 2020-06-14 16:23:54 +02:00
3a78aaef8f fix(container): resolves dependencies without contructor
Co-Authored-By: Johannes Pichler <fetzi@users.noreply.github.com>
2020-06-14 16:15:05 +02:00
c79c0feec8 feat(namespaced-functions): updates stubs 2020-06-14 02:16:14 +02:00
39a5a94f3e feat(namespaced-helpers): udpates stubs 2020-06-14 01:03:35 +02:00
961bfcaff7 Merge pull request #80 from owenvoke/feature/problem-matchers
Add problem matcher output to CI
2020-06-12 14:47:45 +02:00
52ba5dbd00 Add problem matcher output to CI 2020-06-12 13:37:17 +01:00
518b056fb9 fix: do not force having tests folder 2020-06-12 02:12:51 +02:00
f9a936b4d9 tests: namespace helpers 2020-06-11 21:56:15 +02:00
4448761852 Merge pull request #78 from felixdorn/patch-1
Optimise debug_backtrace calls
2020-06-11 21:46:23 +02:00
1192d13e6b add memory optimisation for Backtrace::testFile() 2020-06-11 16:38:31 +02:00
57b982de48 fix ci build 2020-06-11 16:31:14 +02:00
a3366379e0 optimise debug_backtrace calls 2020-06-11 16:13:17 +02:00
cd8d8fce61 chore: skips visual tests on windows for now 2020-06-10 21:38:45 +02:00
4254d71039 tests: fixes visual testing on windows 2020-06-10 21:32:54 +02:00
bd48232c61 chore: runs tests on windows 2020-06-10 21:17:56 +02:00
70b3c7ea1d chore: adds init plugin 2020-06-07 20:16:26 +02:00
c186035a13 chore: fixes duplicated branch alias 2020-06-05 22:44:48 +02:00
2efed3ef80 Merge pull request #65 from fetzi/feature/add-container
Add basic container implementation
2020-06-05 22:39:57 +02:00
58f2581307 Merge branch 'master' into feature/add-container 2020-06-05 22:39:02 +02:00
6c4fd61db5 tests: fixes testing running in php 7.3 2020-06-05 20:51:57 +02:00
afbbc35984 tests: refactor visual testing 2020-06-05 20:49:14 +02:00
a13c19cc29 chore: fixes deps 2020-06-05 20:04:10 +02:00
7d7c5f1ab1 Merge pull request #61 from dimitrioskarvounaris/windows-gitbash
Fixes autoloading, plugins and tests on Windows
2020-06-05 20:01:55 +02:00
865f33bf80 // fixing type check 2020-06-05 19:45:58 +02:00
e33419545c // fixing once more, wrong code pasted :( 2020-06-05 19:42:07 +02:00
b93cd724c1 // tiny fix 2020-06-05 19:37:53 +02:00
40a5d067ec // fixing type checks 2020-06-05 19:35:13 +02:00
3640ab0945 // unnecessary linebreak 2020-06-05 19:30:35 +02:00
cb2336d220 // missing change 2020-06-05 19:29:43 +02:00
71fcb281b0 Merge branch 'windows-gitbash' of github.com:dimitrioskarvounaris/pest into windows-gitbash 2020-06-05 19:25:23 +02:00
d24830121e Reverting changes from c05df432 2020-06-05 19:24:56 +02:00
5a00a732e3 Merge branch 'master' into windows-gitbash 2020-06-05 18:37:24 +02:00
38584bec93 Updating success.txt snapshot 2020-06-05 18:31:40 +02:00
ffa3f1d683 Skip visual snapshot test on Windows 2020-06-05 18:26:52 +02:00
dff9bbc134 Fix file paths not being used properly
basename() will strip full path information on some systems.
What is needed is to use both dirname() & basename() on paths,
as recognized by all systems, and only afterwards do any
replacements.
2020-06-05 18:24:03 +02:00
f5f717f1ad chore: requires more than collision beta1 2020-06-05 18:18:06 +02:00
9bdd254007 tests: adapts to collision beta 2 2020-06-05 18:14:27 +02:00
6e18912ea6 Test to check if the full test path is shown 2020-06-05 17:38:59 +02:00
d35320c697 Compare filename correctly on all OS 2020-06-05 17:25:53 +02:00
fe11140fc2 Adding dom extension to CI 2020-06-05 16:23:12 +02:00
0d198f589d Fix changes in success snapshot 2020-06-05 16:23:12 +02:00
8a42d40506 traits from Autoload.php not loading on Windows
Windows requires realpath() so the case of the
paths and filenames are always identical
2020-06-05 16:23:11 +02:00
83797431fb in() does not handle absolute paths under Windows
This fixes plugins to be included incorrectly under Windows
2020-06-05 16:23:11 +02:00
c05df43217 Compare lines without involving linebreaks
Fixes tests failing under Windows environments
for any linebreak character differences
2020-06-05 16:23:11 +02:00
f6859eeb3b Launch pest as php subprocess 2020-06-05 16:23:11 +02:00
a0b8082631 Fix issue with case-insensitive windows paths 2020-06-05 16:23:11 +02:00
926d8ecb8d Call binary as php sub process 2020-06-05 16:23:11 +02:00
24f85354e2 Normalize Windows dir name in TestCaseFactory 2020-06-05 16:21:35 +02:00
163de28338 Make sure PHP is called before calling pest as sub process 2020-06-05 16:21:35 +02:00
3d2c83a501 Make sure test targets are sanitized in a windows-compatible way 2020-06-05 16:21:35 +02:00
b0c964d4d9 Don't use "reapath" in binary for cross-compatibility 2020-06-05 16:21:35 +02:00
20d2d9f3b7 Merge pull request #69 from octoper/master
Update Changelog action
2020-06-05 16:15:30 +02:00
6b7aa10e91 Update changelog.yml 2020-06-05 17:03:32 +03:00
067aa58817 Merge branch 'feature/add-container' of github.com:fetzi/pest into feature/add-container 2020-06-05 11:53:17 +02:00
337e751200 Update plugin interfaces and instantiate container 2020-06-05 11:52:23 +02:00
b20f208b55 Add basic container implementation 2020-06-05 11:51:33 +02:00
9899b3c3a4 Update plugin interfaces and instantiate container 2020-06-05 07:48:51 +02:00
6437db7aa0 Updated changelog action 2020-06-05 06:18:18 +03:00
7d38d4bd4f Updated changelog action 2020-06-05 06:16:03 +03:00
e8d426f574 Removes windows for now 2020-06-04 23:09:40 +02:00
bb711108a2 Merge pull request #68 from octoper/patch-1
Update CHANGELOG.md
2020-06-04 22:14:16 +02:00
a482341b99 Update CHANGELOG.md 2020-06-04 21:22:29 +03:00
f5ce472006 Merge pull request #66 from pestphp/feat/pending-higher-order-tests
feat: adds pending higher order tests
2020-06-04 19:40:18 +02:00
a53ff3e459 Merge pull request #67 from octoper/master
fixed changelog action
2020-06-04 16:31:38 +02:00
e15d77f3f6 Update changelog.yml 2020-06-04 17:03:47 +03:00
504128730c Update changelog.yml 2020-06-04 16:53:08 +03:00
098acaecc0 Merge pull request #1 from pestphp/master
Pulling changes from pestphp/pest
2020-06-04 16:50:19 +03:00
b2dd573a67 Merge pull request #64 from octoper/master
Created Update CHANGELOG action
2020-06-04 15:17:29 +02:00
84c9078bb7 Add basic container implementation 2020-06-04 11:58:28 +02:00
aa1917c28d feat(pending-higher-order-tests): adds code and tests 2020-06-04 01:34:03 +02:00
c81dce0f6d feat(pending-higher-order-tests): adds code and tests 2020-06-04 01:33:33 +02:00
249869c2db Updated update_changelog to changelog action 2020-06-03 17:37:48 +03:00
d59d8d6245 Created update_changelog action 2020-06-03 17:32:07 +03:00
b0680b7e2c chore: cs 2020-05-31 13:42:27 +02:00
c7fd21999b Merge pull request #51 from Jibbarth/feature/support-colors-never
Feature/support colors never
2020-05-31 13:39:55 +02:00
28d06663d3 Add tests for --colors=never option 2020-05-31 12:33:27 +02:00
73f56e58a5 Pass color and verbosity args to printer (fix #49) 2020-05-31 12:32:43 +02:00
76796ffc67 refacto: includes coverage plugin 2020-05-30 01:43:02 +02:00
01daf0316c refacto: removes unused code about coverage 2020-05-29 22:44:41 +02:00
1f2976c0e0 tests: types 2020-05-29 22:35:20 +02:00
2e7ed741b6 fix: keeps result from plugin to plugin 2020-05-29 22:33:05 +02:00
a0a4730ef8 Merge branch 'master' of https://github.com/pestphp/pest 2020-05-29 22:28:47 +02:00
5ed927d226 Merge pull request #43 from fetzi/plugins
Integrate pest-plugins with 2 interfaces
2020-05-29 22:08:39 +02:00
78cdd4da36 Update composer.json 2020-05-29 21:15:51 +02:00
332139e614 Merge pull request #37 from owenvoke/bugfix/windows
Fix Windows builds running Pest
2020-05-29 20:12:54 +02:00
b093e8ee29 Integrate pest-plugins with 2 interfaces
integrate pest-plugin package and remove core coverage stuff
2020-05-29 11:28:06 +02:00
937374431a Fix Windows builds running Pest 2020-05-28 08:46:05 +01:00
ddc08cf0f9 docs: updates changelog 2020-05-24 21:41:35 +02:00
88d2391d2e fix: colors on coverage 2020-05-24 21:40:10 +02:00
bd02196950 docs: updates changelog 2020-05-24 21:32:53 +02:00
4de6019206 Merge pull request #18 from michaeldyrynda/master
Add support for installing Pest into a Lumen application
2020-05-24 20:43:23 +02:00
85630b0aa2 Merge pull request #22 from pgrimaud/master
Fix typos
2020-05-24 20:03:20 +02:00
0fda39467c Merge pull request #24 from AlexMartinFR/patch-1
Update README.md
2020-05-24 20:02:36 +02:00
415f571910 fix: mockery tests being considered as risky 2020-05-24 20:00:30 +02:00
8284219035 Update README.md
Typo.
2020-05-24 19:35:35 +02:00
d0d34c7872 Fix typos 2020-05-24 12:37:33 +02:00
2869f11ae5 use ->in(__DIR__) in base Pest.php file 2020-05-24 13:36:17 +09:30
340c7ca04e Merge pull request #20 from aniplaylist/patch-1
Fix typo in beforeAll() PHPDoc block
2020-05-24 00:48:21 +02:00
81a646d64e Fix typo in beforeAll() PHPDoc block 2020-05-23 23:01:03 +02:00
c23f2e4bd6 fix errors from type checks 2020-05-23 21:09:28 +09:30
4496e9d9ee Add support for installing Pest into a Lumen application
This entails creating Laravel and Lumen-specific stubs, and ensuring
that the appropriate stubs are copied as part of the pest install.
2020-05-23 20:52:15 +09:30
ce14ffd49a chore: fixes duplicated name on workflow 2020-05-21 23:25:43 +02:00
c18c481628 chore: updates names in github actions workflow 2020-05-21 23:13:32 +02:00
0695ea5d33 chore: runs formats testing in ubuntu only 2020-05-21 23:00:16 +02:00
2e321f5465 chore: fixes build 2020-05-21 22:49:46 +02:00
cbeec31bfc chore: adds windows build 2020-05-21 22:46:46 +02:00
69f6a22121 docs: updates changelog 2020-05-21 22:22:34 +02:00
9a179d2891 chore: coding style 2020-05-21 21:48:47 +02:00
6c4be0190e feat: adds plugin uses api 2020-05-21 21:44:05 +02:00
5c6bb43d8d docs: updates readme badges 2020-05-20 01:30:05 +02:00
e536c28e34 docs: updates readme 2020-05-16 22:58:45 +02:00
67bb23cda3 Update README.md 2020-05-16 22:57:48 +02:00
59398cfcf8 docs: updates license 2020-05-16 22:37:50 +02:00
182377abe3 docs: adds twitter link 2020-05-16 22:34:00 +02:00
242e74964b docs: updates readme banner 2020-05-16 22:24:20 +02:00
9a2c7e45f7 docs: updates discord link 2020-05-15 18:19:56 +02:00
99205c4aa8 docs: updates changelog 2020-05-15 02:15:32 +02:00
1268384fb3 Merge pull request #7 from pestphp/feat/helpers
feat(helpers): adds helpers file
2020-05-15 02:12:12 +02:00
c97fd17120 feat(helpers): adds helpers file 2020-05-14 23:03:56 +02:00
68 changed files with 1257 additions and 490 deletions

10
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@ -0,0 +1,10 @@
| Q | A
| ------------- | ---
| Bug fix? | yes/no
| New feature? | yes/no
| Fixed tickets | #... <!-- #-prefixed issue number(s), if any -->
<!--
- Replace this comment by a description of what your PR is solving.
-->

54
.github/workflows/changelog.yml vendored Normal file
View File

@ -0,0 +1,54 @@
name: Changelog
on:
push:
branches: [ master ]
paths:
- CHANGELOG.md
pull_request:
branches: [ master ]
paths:
- CHANGELOG.md
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Checkout website repository
uses: actions/checkout@v2
with:
token: ${{ secrets.CHANGELOG_KEY }}
repository: pestphp/website
path: pestphp-website
- name: Read CHANGELOG.md
id: package
uses: juliangruber/read-file-action@v1
with:
path: ./CHANGELOG.md
- name: Add file headers
uses: DamianReeves/write-file-action@v1.0
with:
path: ./CHANGELOG.md
contents: |
---
title: Changelog
description: Changelog
extends: _layouts.documentation
section: content
---
${{ steps.package.outputs.content }}
Next section: [Upgrade Guide →](/docs/upgrade-guide)
write-mode: overwrite
- name: Copy CHANGELOG to website repository
run: cp CHANGELOG.md pestphp-website/source/docs/changelog.md
- name: Create Pull Request
uses: peter-evans/create-pull-request@v2
with:
token: ${{ secrets.CHANGELOG_KEY }}
commit-message: Update changelog.md
committer: GitHub Action <noreply@github.com>
author: ${{ github.actor }} <${{ github.actor }}@users.noreply.github.com>
title: 'Update changelog.md'
path: ./pestphp-website

View File

@ -1,18 +1,19 @@
name: Continuous Integration
name: Formats
on: ['push', 'pull_request']
jobs:
ci:
runs-on: ubuntu-latest
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
php: [7.3, 7.4]
os: [ubuntu-latest]
php: [7.4]
dependency-version: [prefer-lowest, prefer-stable]
name: CI - PHP ${{ matrix.php }} (${{ matrix.dependency-version }})
name: Formats P${{ matrix.php }} - ${{ matrix.os }} - ${{ matrix.dependency-version }}
steps:
@ -29,7 +30,7 @@ jobs:
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: mbstring, zip
extensions: dom, mbstring, zip
tools: prestissimo
coverage: pcov
@ -43,9 +44,3 @@ jobs:
- name: Type Checks
run: vendor/bin/phpstan analyse --ansi
- name: Unit Tests
run: bin/pest --colors=always --exclude-group=integration
- name: Integration Tests
run: bin/pest --colors=always --group=integration

48
.github/workflows/tests.yml vendored Normal file
View File

@ -0,0 +1,48 @@
name: Tests
on: ['push', 'pull_request']
jobs:
ci:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
php: [7.3, 7.4]
dependency-version: [prefer-lowest, prefer-stable]
name: Tests P${{ matrix.php }} - ${{ matrix.os }} - ${{ matrix.dependency-version }}
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Cache dependencies
uses: actions/cache@v1
with:
path: ~/.composer/cache/files
key: dependencies-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }}
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: dom, mbstring, zip
coverage: none
- name: Install Composer dependencies
run: composer update --${{ matrix.dependency-version }} --no-interaction --prefer-dist
- name: Unit Tests
run: php bin/pest --colors=always --exclude-group=integration
- name: Integration Tests
run: php bin/pest --colors=always --group=integration
- name: Setup problem matchers for PHP
run: echo "::add-matcher::${{ runner.tool_cache }}/php.json"
- name: Setup problem matchers for Pest
run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"

1
.gitignore vendored
View File

@ -8,3 +8,4 @@ coverage.xml
.temp/coverage.php
*.swp
*.swo
.vscode/

View File

@ -6,6 +6,66 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased]
## [v0.2.4 (2020-08-06)](https://github.com/pestphp/pest/compare/v0.2.3...v0.2.4)
### Changed
- uses `"phpunit/phpunit": "~9.2.0"` as dependency ([d0eb2f1](https://github.com/pestphp/pest/commit/d0eb2f15cd44b558ebb47002a7ff5b7af6fbbc07))
## [v0.2.3 (2020-07-01)](https://github.com/pestphp/pest/compare/v0.2.2...v0.2.3)
### Added
- `--init` and `pest:install` artisan command output changes ([#118](https://github.com/pestphp/pest/pull/118), [db7c4b1](https://github.com/pestphp/pest/commit/db7c4b174f0974969450dda71dcd649ef0c073a3))
- `--version` option to view the current version of Pest ([9ea51ca](https://github.com/pestphp/pest/commit/9ea51caf3f74569debb1e465992e9ea916cb80fe))
## [v0.2.2 (2020-06-21)](https://github.com/pestphp/pest/compare/v0.2.1...v0.2.2)
### Added
- `depends` phpunit feature ([#103](https://github.com/pestphp/pest/pull/103))
### Fixes
- datasets name conflit ([#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
- Multiple `uses` in the same path override previous `uses` ([#97](https://github.com/pestphp/pest/pull/97))
## [v0.2.0 (2020-06-14)](https://github.com/pestphp/pest/compare/v0.1.5...v0.2.0)
### Adds
- `--init` option to install Pest on a new blank project ([70b3c7e](https://github.com/pestphp/pest/commit/70b3c7ea1ddb031f3bbfaabdc28d56270608ebbd))
- pending higher orders tests aka tests without description ([aa1917c](https://github.com/pestphp/pest/commit/aa1917c28d9b69c2bd1d51f986c4f61318ee7e16))
### Fixed
- `--verbose` and `--colors` options not being used by printers ([#51](https://github.com/pestphp/pest/pull/51))
- missing support on windows ([#61](https://github.com/pestphp/pest/pull/61))
### Changed
- `helpers.php` stub provides now namespaced functions
- functions provided by plugins are now namespaced functions:
```php
use function Pest\Faker\faker;
it('foo', function () {
$name = faker()->name;
});
```
## [v0.1.5 (2020-05-24)](https://github.com/pestphp/pest/compare/v0.1.4...v0.1.5)
### Fixed
- Missing default decorated output on coverage ([88d2391](https://github.com/pestphp/pest/commit/88d2391d2e6fe9c9416462734b9b523cb418f469))
## [v0.1.4 (2020-05-24)](https://github.com/pestphp/pest/compare/v0.1.3...v0.1.4)
### Added
- Support to Lumen on artisan commands ([#18](https://github.com/pestphp/pest/pull/18))
### Fixed
- Mockery tests without assertions being considered risky ([415f571](https://github.com/pestphp/pest/commit/415f5719101b30c11d87f74810a71686ef2786c6))
## [v0.1.3 (2020-05-21)](https://github.com/pestphp/pest/compare/v0.1.2...v0.1.3)
### Added
- `Plugin::uses()` method for making traits globally available ([6c4be01](https://github.com/pestphp/pest/commit/6c4be0190e9493702a976b996bbbf5150cc6bb53))
## [v0.1.2 (2020-05-15)](https://github.com/pestphp/pest/compare/v0.1.1...v0.1.2)
### Added
- Support to custom helpers ([#7](https://github.com/pestphp/pest/pull/7))
## [v0.1.1 (2020-05-14)](https://github.com/pestphp/pest/compare/v0.1.0...v0.1.1)
### Added
- `test` function without any arguments returns the current test case ([6fc55be](https://github.com/pestphp/pest/commit/6fc55becc8aecff685a958617015be1a4c118b01))

View File

@ -1,17 +1,18 @@
<p align="center">
<img src="https://next.pestphp.com/assets/img/og.png" width="600" alt="PEST Preview">
<img src="https://raw.githubusercontent.com/pestphp/art/master/readme.png" width="600" alt="PEST">
<p align="center">
<a href="https://github.com/pestphp/pest/actions"><img src="https://github.com/pest/pestphp/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/pestphp/pest"><img src="https://poser.pugx.org/pestphp/pest/d/total.svg" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/pestphp/pest"><img src="https://poser.pugx.org/pestphp/pest/v/stable.svg" alt="Latest Version"></a>
<a href="https://packagist.org/packages/pestphp/pest"><img src="https://poser.pugx.org/pestphp/pest/license.svg" alt="License"></a>
<a href="https://github.com/pestphp/pest/actions"><img alt="GitHub Workflow Status (master)" src="https://img.shields.io/github/workflow/status/pestphp/pest/Continuous Integration/master"></a>
<a href="https://packagist.org/packages/pestphp/pest"><img alt="Total Downloads" src="https://img.shields.io/packagist/dt/pestphp/pest"></a>
<a href="https://packagist.org/packages/pestphp/pest"><img alt="Latest Version" src="https://img.shields.io/packagist/v/pestphp/pest"></a>
<a href="https://packagist.org/packages/pestphp/pest"><img alt="License" src="https://img.shields.io/packagist/l/pestphp/pest"></a>
</p>
</p>
------
**Pest** it's an elegant PHP Testing Framework with a focus on simplicity. It was carefully crafted to bring the joy of testing to PHP.
**Pest** is an elegant PHP Testing Framework with a focus on simplicity. It was carefully crafted to bring the joy of testing to PHP.
- Explore the docs: **[pestphp.com »](https://pestphp.com)**
- Join the Discord Server: **[discord.gg/4UMHUb5 »](https://discord.gg/4UMHUb5)**
- Follow us on Twitter: **[@pestphp »](https://twitter.com/pestphp)**
- Join us on the Discord Server: **[discord.gg/bMAJv82 »](https://discord.gg/bMAJv82)**
Pest was created by **[Nuno Maduro](https://twitter.com/enunomaduro)** and is open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**.
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)**.

View File

@ -1,31 +1,39 @@
#!/usr/bin/env php
<?php declare(strict_types=1);
use NunoMaduro\Collision\Provider;
use Pest\Actions\ValidatesEnvironment;
use Pest\Console\Command;
use Pest\Support\Container;
use Pest\TestSuite;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
(static function () {
// Used when Pest is required using composer.
$vendorPath = realpath(__DIR__ . '/../../../../vendor/autoload.php');
$vendorPath = dirname(__DIR__, 4) . '/vendor/autoload.php';
// Used when Pest maintainers are running Pest tests.
$localPath = realpath(__DIR__ . '/../vendor/autoload.php');
$localPath = dirname(__DIR__) . '/vendor/autoload.php';
if ($vendorPath) {
if (file_exists($vendorPath)) {
include_once $vendorPath;
} else {
include_once $localPath;
}
(new \NunoMaduro\Collision\Provider)->register();
(new Provider())->register();
$rootPath = getcwd();
$testSuite = TestSuite::getInstance($rootPath);
$output = new ConsoleOutput(ConsoleOutput::VERBOSITY_NORMAL, true);
$container = Container::getInstance();
$container->add(TestSuite::class, $testSuite);
$container->add(OutputInterface::class, $output);
ValidatesEnvironment::in($testSuite);
exit((new Command($testSuite, new ConsoleOutput()))->run($_SERVER['argv']));
exit($container->get(Command::class)->run($_SERVER['argv']));
})();

View File

@ -18,8 +18,11 @@
],
"require": {
"php": "^7.3",
"nunomaduro/collision": "^5.0",
"phpunit/phpunit": "^9.1.4",
"nunomaduro/collision": "^5.0.0-BETA3",
"pestphp/pest-plugin": "^0.2",
"pestphp/pest-plugin-coverage": "^0.2",
"pestphp/pest-plugin-init": "^0.2",
"phpunit/phpunit": "~9.2.0",
"sebastian/environment": "^5.1"
},
"autoload": {
@ -28,24 +31,28 @@
},
"files": [
"src/globals.php",
"src/Pest.php",
"compiled/globals.php"
]
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/PHPUnit/"
}
},
"files": [
"tests/Autoload.php"
]
},
"require-dev": {
"ergebnis/phpstan-rules": "^0.14.4",
"ergebnis/phpstan-rules": "^0.15.0",
"friendsofphp/php-cs-fixer": "^2.16.3",
"illuminate/console": "^7.10.3",
"illuminate/support": "^7.10.3",
"mockery/mockery": "^1.3.1",
"phpstan/phpstan": "^0.12.25",
"illuminate/console": "^7.16.1",
"illuminate/support": "^7.16.1",
"mockery/mockery": "^1.4.0",
"phpstan/phpstan": "^0.12.30",
"phpstan/phpstan-strict-rules": "^0.12.2",
"rector/rector": "^0.7.25",
"symfony/var-dumper": "^5.0.8",
"rector/rector": "^0.7.37",
"symfony/var-dumper": "^5.1.2",
"thecodingmachine/phpstan-strict-rules": "^0.12.0"
},
"minimum-stability": "dev",
@ -61,10 +68,10 @@
"compile": "@php ./scripts/compile.php",
"lint": "rector process src && php-cs-fixer fix -v",
"test:lint": "php-cs-fixer fix -v --dry-run && rector process src --dry-run",
"test:types": "phpstan analyse --ansi",
"test:unit": "bin/pest --colors=always --exclude-group=integration",
"test:integration": "bin/pest --colors=always --group=integration",
"test:integration:snapshots": "REBUILD_SNAPSHOTS=true bin/pest --colors=always",
"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",
"update:snapshots": "REBUILD_SNAPSHOTS=true php bin/pest --colors=always",
"test": [
"@test:lint",
"@test:types",
@ -73,6 +80,14 @@
]
},
"extra": {
"branch-alias": {
"dev-master": "0.2.x-dev"
},
"pest": {
"plugins": [
"Pest\\Plugins\\Version"
]
},
"laravel": {
"providers": [
"Pest\\Laravel\\PestServiceProvider"

View File

@ -15,8 +15,9 @@ parameters:
reportUnmatchedIgnoredErrors: true
ignoreErrors:
- "#Undefined variable: \\$this#"
- "#is not allowed to extend#"
- "#Language construct eval#"
- "# with null as default value#"
- "#Using \\$this in static method#"
- "#has parameter \\$closure with default value.#"
- "#has parameter \\$description with default value.#"

View File

@ -1,79 +0,0 @@
<?php
declare(strict_types=1);
namespace Pest\Actions;
use Pest\Console\Coverage;
use Pest\Support\Str;
use Pest\TestSuite;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
/**
* @internal
*/
final class AddsCoverage
{
/**
* @var string
*/
private const COVERAGE_OPTION = 'coverage';
/**
* @var string
*/
private const MIN_OPTION = 'min';
/**
* Holds the coverage related options.
*
* @var array<int, string>
*/
private const OPTIONS = [self::COVERAGE_OPTION, self::MIN_OPTION];
/**
* If any, adds the coverage params to the given original arguments.
*
* @param array<int, string> $originals
*
* @return array<int, string>
*/
public static function from(TestSuite $testSuite, array $originals): array
{
$arguments = array_merge([''], array_values(array_filter($originals, function ($original): bool {
foreach (self::OPTIONS 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)) {
$testSuite->coverage = true;
$originals[] = '--coverage-php';
$originals[] = Coverage::getPath();
}
if ($input->getOption(self::MIN_OPTION) !== null) {
/* @phpstan-ignore-next-line */
$testSuite->coverageMin = (float) $input->getOption(self::MIN_OPTION);
}
return $originals;
}
}

View File

@ -21,7 +21,7 @@ final class AddsDefaults
public static function to(array $arguments): array
{
if (!array_key_exists('printer', $arguments)) {
$arguments['printer'] = new Printer();
$arguments['printer'] = new Printer(null, $arguments['verbose'] ?? false, $arguments['colors'] ?? 'always');
}
return $arguments;

View File

@ -22,6 +22,7 @@ final class LoadStructure
*/
private const STRUCTURE = [
'Datasets.php',
'Helpers.php',
'Pest.php',
'Datasets',
];

View File

@ -19,7 +19,6 @@ final class ValidatesEnvironment
*/
private const NEEDED_FILES = [
'composer.json',
'tests',
];
/**

View File

@ -129,16 +129,25 @@ trait TestCase
/**
* Runs the test.
*
* @return mixed
*
* @throws \Throwable
*/
public function __test(): void
public function __test()
{
$this->__callClosure($this->__test, func_get_args());
return $this->__callClosure($this->__test, func_get_args());
}
private function __callClosure(Closure $closure, array $arguments): void
/**
* @return mixed
*
* @throws \Throwable
*/
private function __callClosure(Closure $closure, array $arguments)
{
ExceptionTrace::ensure(function () use ($closure, $arguments) {
call_user_func_array(Closure::bind($closure, $this, get_class($this)), $arguments);
return ExceptionTrace::ensure(function () use ($closure, $arguments) {
return call_user_func_array(Closure::bind($closure, $this, get_class($this)), $arguments);
});
}

View File

@ -4,11 +4,13 @@ declare(strict_types=1);
namespace Pest\Console;
use Pest\Actions\AddsCoverage;
use Pest\Actions\AddsDefaults;
use Pest\Actions\AddsTests;
use Pest\Actions\LoadStructure;
use Pest\Actions\ValidatesConfiguration;
use Pest\Contracts\Plugins\AddsOutput;
use Pest\Contracts\Plugins\HandlesArguments;
use Pest\Plugin\Loader;
use Pest\TestSuite;
use PHPUnit\Framework\TestSuite as BaseTestSuite;
use PHPUnit\TextUI\Command as BaseCommand;
@ -54,9 +56,14 @@ final class Command extends BaseCommand
protected function handleArguments(array $argv): void
{
/*
* First, let's handle pest is own `--coverage` param.
* First, let's call all plugins that want to handle arguments
*/
$argv = AddsCoverage::from($this->testSuite, $argv);
$plugins = Loader::getPlugins(HandlesArguments::class);
/** @var HandlesArguments $plugin */
foreach ($plugins as $plugin) {
$argv = $plugin->handleArguments($argv);
}
/*
* Next, as usual, let's send the console arguments to PHPUnit.
@ -81,6 +88,8 @@ 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'];
@ -102,7 +111,6 @@ final class Command extends BaseCommand
$this->arguments['test'] = $testSuite;
}
LoadStructure::in($this->testSuite->rootPath);
AddsTests::to($testSuite, $this->testSuite);
return $testRunner;
@ -119,25 +127,14 @@ final class Command extends BaseCommand
{
$result = parent::run($argv, false);
if ($result === 0 && $this->testSuite->coverage) {
if (!Coverage::isAvailable()) {
$this->output->writeln(
"\n <fg=white;bg=red;options=bold> ERROR </> No code coverage driver is available.</>",
);
exit(1);
}
/*
* Let's call all plugins that want to add output after test execution
*/
$plugins = Loader::getPlugins(AddsOutput::class);
$coverage = Coverage::report($this->output);
$result = (int) ($coverage < $this->testSuite->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->testSuite->coverageMin, 1)
));
}
/** @var AddsOutput $plugin */
foreach ($plugins as $plugin) {
$result = $plugin->addOutput($result);
}
exit($result);

View File

@ -1,167 +0,0 @@
<?php
declare(strict_types=1);
namespace Pest\Console;
use Pest\Exceptions\ShouldNotHappen;
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 \SebastianBergmann\CodeCoverage\CodeCoverage $codeCoverage */
$codeCoverage = require $reportPath;
unlink($reportPath);
$totalWidth = (new Terminal())->getWidth();
$dottedLineLength = $totalWidth <= 70 ? $totalWidth : 70;
$totalCoverage = $codeCoverage->getReport()->getLineExecutedPercent();
$output->writeln(
sprintf(
' <fg=white;options=bold>Cov: </><fg=default>%s</>',
$totalCoverage
)
);
$output->writeln('');
/** @var Directory<File|Directory> $report */
$report = $codeCoverage->getReport();
foreach ($report->getIterator() as $file) {
if (!$file instanceof File) {
continue;
}
$dirname = dirname($file->getId());
$basename = basename($file->getId(), '.php');
$name = $dirname === '.' ? $basename : implode(DIRECTORY_SEPARATOR, [
$dirname,
$basename,
]);
$rawName = $dirname === '.' ? $basename : implode(DIRECTORY_SEPARATOR, [
$dirname,
$basename,
]);
$linesExecutedTakenSize = 0;
if ($file->getLineExecutedPercent() != '0.00%') {
$linesExecutedTakenSize = strlen($uncoveredLines = trim(implode(', ', self::getMissingCoverage($file)))) + 1;
$name .= sprintf(' <fg=red>%s</>', $uncoveredLines);
}
$percentage = $file->getNumExecutableLines() === 0
? '100.0'
: number_format((float) $file->getLineExecutedPercent(), 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 (float) $totalCoverage;
}
/**
* 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] = sprintf('%s..%s', $from, $line);
return $array;
}
$array[$lastKey] = sprintf('%s..%s', $array[$lastKey], $line);
return $array;
};
$array = [];
foreach (array_filter($file->getCoverageData(), 'is_array') as $line => $tests) {
$array = $eachLine($array, $tests, $line);
}
return $array;
}
}

66
src/Console/Thanks.php Normal file
View File

@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Pest\Console;
use Symfony\Component\Console\Helper\SymfonyQuestionHelper;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
/**
* @internal
*/
final class Thanks
{
/** @var array<int, string> */
private const FUNDING_MESSAGES = [
'',
' - Star or contribute to Pest:',
' <options=bold>https://github.com/pestphp/pest</>',
' - Tweet something about Pest on Twitter:',
' <options=bold>https://twitter.com/pestphp</>',
' - Sponsor the creator:',
' <options=bold>https://github.com/sponsors/nunomaduro</>',
];
/** @var OutputInterface */
private $output;
public function __construct(OutputInterface $output)
{
$this->output = $output;
}
/**
* Asks the user to support Pest.
*/
public function __invoke(): void
{
$wantsToSupport = (new SymfonyQuestionHelper())->ask(
new ArrayInput([]),
$this->output,
new ConfirmationQuestion(
'Can you quickly <options=bold>star our GitHub repository</>? 🙏🏻',
true,
)
);
if ($wantsToSupport === true) {
if (PHP_OS_FAMILY == 'Darwin') {
exec('open https://github.com/pestphp/pest');
}
if (PHP_OS_FAMILY == 'Windows') {
exec('start https://github.com/pestphp/pest');
}
if (PHP_OS_FAMILY == 'Linux') {
exec('xdg-open https://github.com/pestphp/pest');
}
}
foreach (self::FUNDING_MESSAGES as $message) {
$this->output->writeln($message);
}
}
}

View File

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Pest\Contracts\Plugins;
/**
* @internal
*/
interface AddsOutput
{
/**
* Allows to add custom output after the test suite was executed.
*/
public function addOutput(int $testReturnCode): int;
}

View File

@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace Pest\Contracts\Plugins;
/**
* @internal
*/
interface HandlesArguments
{
/**
* Allows to handle custom command line arguments.
*
* PLEASE NOTE: it is necessary to remove any custom argument from the array
* because otherwise the application will complain about them
*
* @param array<int, string> $arguments
*
* @return array<int, string> the updated list of arguments
*/
public function handleArguments(array $arguments): array;
}

View File

@ -74,12 +74,30 @@ final class Datasets
$data = iterator_to_array($data);
}
$namedData = [];
$dataSetDescriptions = [];
$dataSetValues = [];
foreach ($data as $values) {
$values = is_array($values) ? $values : [$values];
$name = $description . self::getDataSetDescription($values);
$namedData[$name] = $values;
$dataSetDescriptions[] = $description . self::getDataSetDescription($values);
$dataSetValues[] = $values;
}
foreach (array_count_values($dataSetDescriptions) as $descriptionToCheck => $count) {
if ($count > 1) {
$index = 1;
foreach ($dataSetDescriptions as $i => $dataSetDescription) {
if ($dataSetDescription === $descriptionToCheck) {
$dataSetDescriptions[$i] .= sprintf(' #%d', $index++);
}
}
}
}
$namedData = [];
foreach ($dataSetDescriptions as $i => $dataSetDescription) {
$namedData[$dataSetDescription] = $dataSetValues[$i];
}
return $namedData;

View File

@ -8,6 +8,7 @@ use Closure;
use Pest\Concerns;
use Pest\Contracts\HasPrintableTestCaseName;
use Pest\Datasets;
use Pest\Exceptions\ShouldNotHappen;
use Pest\Support\HigherOrderMessageCollection;
use Pest\Support\NullClosure;
use Pest\TestSuite;
@ -39,9 +40,10 @@ final class TestCaseFactory
/**
* Holds the test description.
*
* @readonly
* If the description is null, means that it
* will be created with the given assertions.
*
* @var string
* @var string|null
*/
public $description;
@ -104,7 +106,7 @@ final class TestCaseFactory
/**
* Creates a new anonymous test case pending object.
*/
public function __construct(string $filename, string $description, Closure $closure = null)
public function __construct(string $filename, string $description = null, Closure $closure = null)
{
$this->filename = $filename;
$this->description = $description;
@ -122,14 +124,22 @@ final class TestCaseFactory
*/
public function build(TestSuite $testSuite): array
{
if ($this->description === null) {
throw ShouldNotHappen::fromMessage('Description can not be empty.');
}
$chains = $this->chains;
$proxies = $this->proxies;
$factoryTest = $this->test;
$test = function () use ($chains, $proxies, $factoryTest): void {
/**
* @return mixed
*/
$test = function () use ($chains, $proxies, $factoryTest) {
$proxies->proxy($this);
$chains->chain($this);
call_user_func(Closure::bind($factoryTest, $this, get_class($this)), ...func_get_args());
return call_user_func(Closure::bind($factoryTest, $this, get_class($this)), ...func_get_args());
};
$className = $this->makeClassFromFilename($this->filename);
@ -152,16 +162,25 @@ final class TestCaseFactory
*/
public function makeClassFromFilename(string $filename): string
{
if ('\\' === DIRECTORY_SEPARATOR) {
// In case Windows, strtolower drive name, like in UsesCall.
$filename = (string) preg_replace_callback('~^(?P<drive>[a-z]+:\\\)~i', function ($match): string {
return strtolower($match['drive']);
}, $filename);
}
$filename = (string) realpath($filename);
$rootPath = TestSuite::getInstance()->rootPath;
$relativePath = str_replace($rootPath . DIRECTORY_SEPARATOR, '', $filename);
$relativePath = dirname(ucfirst($relativePath)) . DIRECTORY_SEPARATOR . basename($relativePath, '.php');
$relativePath = str_replace(DIRECTORY_SEPARATOR, '\\', $relativePath);
// Strip out any %-encoded octets.
$relativePath = (string) preg_replace('|%[a-fA-F0-9][a-fA-F0-9]|', '', $relativePath);
// Limit to A-Z, a-z, 0-9, '_', '-'.
$relativePath = (string) preg_replace('/[^A-Za-z0-9.\/]/', '', $relativePath);
$classFQN = 'P\\' . basename(ucfirst(str_replace(DIRECTORY_SEPARATOR, '\\', $relativePath)), '.php');
$relativePath = (string) preg_replace('/[^A-Za-z0-9.\\\]/', '', $relativePath);
$classFQN = 'P\\' . $relativePath;
if (class_exists($classFQN)) {
return $classFQN;
}

View File

@ -7,6 +7,7 @@ namespace Pest\Laravel\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Pest\Exceptions\InvalidConsoleArgument;
use Pest\Support\Str;
/**
* @internal
@ -33,18 +34,41 @@ final class PestInstallCommand extends Command
public function handle(): void
{
/* @phpstan-ignore-next-line */
$target = base_path('tests/Pest.php');
$pest = base_path('tests/Pest.php');
/* @phpstan-ignore-next-line */
$helpers = base_path('tests/Helpers.php');
$stubs = $this->isLumen() ? 'stubs/Lumen' : 'stubs/Laravel';
if (File::exists($target)) {
throw new InvalidConsoleArgument(sprintf('%s already exist', $target));
foreach ([$pest, $helpers] as $file) {
if (File::exists($file)) {
throw new InvalidConsoleArgument(sprintf('%s already exist', $file));
}
}
File::copy(implode(DIRECTORY_SEPARATOR, [
dirname(__DIR__, 3),
'stubs',
$stubs,
'Pest.php',
]), $target);
]), $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.');
(new \Pest\Console\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

@ -9,12 +9,22 @@ use Pest\Factories\TestCaseFactory;
use Pest\Support\Backtrace;
use Pest\Support\NullClosure;
use Pest\TestSuite;
use SebastianBergmann\Exporter\Exporter;
/**
* @internal
*/
final class TestCall
{
/**
* Holds the test suite.
*
* @readonly
*
* @var TestSuite
*/
private $testSuite;
/**
* Holds the test case factory.
*
@ -24,14 +34,23 @@ final class TestCall
*/
private $testCaseFactory;
/**
* If test call is descriptionLess.
*
* @readonly
*
* @var bool
*/
private $descriptionLess = false;
/**
* Creates a new instance of a pending test call.
*/
public function __construct(TestSuite $testSuite, string $filename, string $description, Closure $closure = null)
public function __construct(TestSuite $testSuite, string $filename, string $description = null, Closure $closure = null)
{
$this->testCaseFactory = new TestCaseFactory($filename, $description, $closure);
$testSuite->tests->set($this->testCaseFactory);
$this->testSuite = $testSuite;
$this->descriptionLess = $description === null;
}
/**
@ -65,6 +84,18 @@ final class TestCall
return $this;
}
/**
* Sets the test depends.
*/
public function depends(string ...$tests): TestCall
{
$this->testCaseFactory
->factoryProxies
->add(Backtrace::file(), Backtrace::line(), 'setDependencies', [$tests]);
return $this;
}
/**
* Makes the test suite only this test case.
*/
@ -76,7 +107,7 @@ final class TestCall
}
/**
* Sets the test groups(s).
* Sets the test group(s).
*/
public function group(string ...$groups): TestCall
{
@ -128,6 +159,23 @@ final class TestCall
->chains
->add(Backtrace::file(), Backtrace::line(), $name, $arguments);
if ($this->descriptionLess) {
$exporter = new Exporter();
if ($this->testCaseFactory->description !== null) {
$this->testCaseFactory->description .= ' → ';
}
$this->testCaseFactory->description .= sprintf('%s %s', $name, $exporter->shortenedRecursiveExport($arguments));
}
return $this;
}
/**
* Adds the current test case factory
* to the tests repository.
*/
public function __destruct()
{
$this->testSuite->tests->set($this->testCaseFactory);
}
}

View File

@ -59,7 +59,17 @@ final class UsesCall
public function in(string ...$targets): void
{
$targets = array_map(function ($path): string {
return $path[0] === DIRECTORY_SEPARATOR
$startChar = DIRECTORY_SEPARATOR;
if ('\\' === DIRECTORY_SEPARATOR || preg_match('~\A[A-Z]:(?![^/\\\\])~i', $path) > 0) {
$path = (string) preg_replace_callback('~^(?P<drive>[a-z]+:\\\)~i', function ($match): string {
return strtolower($match['drive']);
}, $path);
$startChar = strtolower((string) preg_replace('~^([a-z]+:\\\).*$~i', '$1', __DIR__));
}
return 0 === strpos($path, $startChar)
? $path
: implode(DIRECTORY_SEPARATOR, [
dirname($this->filename),
@ -68,12 +78,12 @@ final class UsesCall
}, $targets);
$this->targets = array_map(function ($target): string {
$realTarget = realpath($target);
if ($realTarget === false) {
$isValid = is_dir($target) || file_exists($target);
if (!$isValid) {
throw new InvalidUsesPath($target);
}
return $realTarget;
return (string) realpath($target);
}, $targets);
}

10
src/Pest.php Normal file
View File

@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Pest;
function version(): string
{
return '0.2.2';
}

28
src/Plugin.php Normal file
View File

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Pest;
final class Plugin
{
/**
* The lazy callables to be executed
* once the test suite boots.
*
* @var array<int, callable>
*
* @internal
*/
public static $callables = [];
/**
* Lazy loads an `uses` call on the context of plugins.
*/
public static function uses(string ...$traits): void
{
self::$callables[] = function () use ($traits): void {
uses(...$traits)->in(TestSuite::getInstance()->rootPath . DIRECTORY_SEPARATOR . 'tests');
};
}
}

39
src/Plugins/Version.php Normal file
View File

@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Pest\Plugins;
use Pest\Contracts\Plugins\HandlesArguments;
use function Pest\version;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @internal
*/
final class Version implements HandlesArguments
{
/**
* @var OutputInterface
*/
private $output;
/**
* Creates a new instance of the plugin.
*/
public function __construct(OutputInterface $output)
{
$this->output = $output;
}
public function handleArguments(array $arguments): array
{
if (in_array('--version', $arguments, true)) {
$this->output->writeln(
sprintf('Pest %s', version()),
);
}
return $arguments;
}
}

View File

@ -41,6 +41,12 @@ 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());
}
Mockery::close();
}
}, $afterEach);

View File

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Pest\Repositories;
use Pest\Exceptions\ShouldNotHappen;
use Pest\Exceptions\TestAlreadyExist;
use Pest\Exceptions\TestCaseAlreadyInUse;
use Pest\Exceptions\TestCaseClassOrTraitNotFound;
@ -54,7 +55,6 @@ final class TestRepository
if ($testCase->class !== \PHPUnit\Framework\TestCase::class) {
throw new TestCaseAlreadyInUse($testCase->class, $class, $filename);
}
$testCase->class = $class;
} elseif (trait_exists($class)) {
$testCase->traits[] = $class;
@ -104,15 +104,26 @@ final class TestRepository
}
foreach ($paths as $path) {
if (array_key_exists($path, $this->uses)) {
$this->uses[$path] = [
array_merge($this->uses[$path][0], $classOrTraits),
array_merge($this->uses[$path][1], $groups),
];
} else {
$this->uses[$path] = [$classOrTraits, $groups];
}
}
}
/**
* Sets a test case by the given filename and description.
*/
public function set(TestCaseFactory $test): void
{
if ($test->description === null) {
throw ShouldNotHappen::fromMessage('Trying to create a test without description.');
}
if (array_key_exists(sprintf('%s@%s', $test->filename, $test->description), $this->state)) {
throw new TestAlreadyExist($test->filename, $test->description);
}

View File

@ -4,17 +4,48 @@ declare(strict_types=1);
namespace Pest\Support;
use Pest\Exceptions\ShouldNotHappen;
/**
* @internal
*/
final class Backtrace
{
/**
* @var string
*/
private const FILE = 'file';
private const BACKTRACE_OPTIONS = DEBUG_BACKTRACE_IGNORE_ARGS;
/**
* Returns the current test file.
*/
public static function testFile(): string
{
$current = null;
foreach (debug_backtrace(self::BACKTRACE_OPTIONS) as $trace) {
if (Str::endsWith($trace[self::FILE], (string) realpath('vendor/phpunit/phpunit/src/Util/FileLoader.php'))) {
break;
}
$current = $trace;
}
if ($current === null) {
throw ShouldNotHappen::fromMessage('Test file not found.');
}
return $current[self::FILE];
}
/**
* Returns the filename that called the current function/method.
*/
public static function file(): string
{
return debug_backtrace()[1]['file'];
return debug_backtrace(self::BACKTRACE_OPTIONS)[1][self::FILE];
}
/**
@ -22,7 +53,7 @@ final class Backtrace
*/
public static function dirname(): string
{
return dirname(debug_backtrace()[1]['file']);
return dirname(debug_backtrace(self::BACKTRACE_OPTIONS)[1][self::FILE]);
}
/**
@ -30,6 +61,6 @@ final class Backtrace
*/
public static function line(): int
{
return debug_backtrace()[1]['line'];
return debug_backtrace(self::BACKTRACE_OPTIONS)[1]['line'];
}
}

101
src/Support/Container.php Normal file
View File

@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
namespace Pest\Support;
use Pest\Exceptions\ShouldNotHappen;
use ReflectionClass;
use ReflectionParameter;
/**
* @internal
*/
final class Container
{
/**
* @var self
*/
private static $instance;
/**
* @var array<string, mixed>
*/
private $instances = [];
/**
* Gets a new or already existing container.
*/
public static function getInstance(): self
{
if (static::$instance === null) {
static::$instance = new static();
}
return static::$instance;
}
/**
* Gets a dependency from the container.
*
* @return object
*/
public function get(string $id)
{
if (array_key_exists($id, $this->instances)) {
return $this->instances[$id];
}
$this->instances[$id] = $this->build($id);
return $this->instances[$id];
}
/**
* Adds the given instance to the container.
*
* @param mixed $instance
*/
public function add(string $id, $instance): void
{
$this->instances[$id] = $instance;
}
/**
* Tries to build the given instance.
*/
private function build(string $id): object
{
/** @phpstan-ignore-next-line */
$reflectionClass = new ReflectionClass($id);
if ($reflectionClass->isInstantiable()) {
$constructor = $reflectionClass->getConstructor();
if ($constructor !== null) {
$params = array_map(
function (ReflectionParameter $param) use ($id) {
$candidate = null;
if ($param->getType() !== null && $param->getType()->isBuiltin()) {
$candidate = $param->getName();
} elseif ($param->getClass() !== null) {
$candidate = $param->getClass()->getName();
} else {
throw ShouldNotHappen::fromMessage(sprintf('The type of `$%s` in `%s` cannot be determined.', $id, $param->getName()));
}
return $this->get($candidate);
},
$constructor->getParameters()
);
return $reflectionClass->newInstanceArgs($params);
}
return $reflectionClass->newInstance();
}
throw ShouldNotHappen::fromMessage(sprintf('A dependency with the name `%s` cannot be resolved.', $id));
}
}

View File

@ -17,11 +17,15 @@ final class ExceptionTrace
/**
* Ensures the given closure reports
* the good execution context.
*
* @return mixed
*
* @throws \Throwable
*/
public static function ensure(Closure $closure): void
public static function ensure(Closure $closure)
{
try {
$closure();
return $closure();
} catch (Throwable $throwable) {
if (Str::startsWith($message = $throwable->getMessage(), self::UNDEFINED_METHOD)) {
$message = str_replace(self::UNDEFINED_METHOD, 'Call to undefined method ', $message);

View File

@ -78,7 +78,9 @@ final class HigherOrderMessage
if ($throwable->getMessage() === sprintf(self::UNDEFINED_METHOD, $this->methodName)) {
/** @var \ReflectionClass $reflection */
$reflection = (new ReflectionClass($target))->getParentClass();
$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));
}

View File

@ -27,11 +27,19 @@ final class Reflection
{
$reflectionClass = new ReflectionClass($object);
try {
$reflectionMethod = $reflectionClass->getMethod($method);
$reflectionMethod->setAccessible(true);
return $reflectionMethod->invoke($object, ...$args);
} catch (ReflectionException $exception) {
if (method_exists($object, '__call')) {
return $object->__call($method, $args);
}
throw $exception;
}
}
/**

View File

@ -30,20 +30,6 @@ final class TestSuite
*/
public $tests;
/**
* Whether should show the coverage or not.
*
* @var bool
*/
public $coverage = false;
/**
* The minimum coverage.
*
* @var float
*/
public $coverageMin = 0.0;
/**
* Holds the before each repository.
*
@ -97,7 +83,7 @@ final class TestSuite
$this->afterEach = new AfterEachRepository();
$this->afterAll = new AfterAllRepository();
$this->rootPath = $rootPath;
$this->rootPath = (string) realpath($rootPath);
}
/**
@ -106,7 +92,13 @@ final class TestSuite
public static function getInstance(string $rootPath = null): TestSuite
{
if (is_string($rootPath)) {
return self::$instance ?? self::$instance = new TestSuite($rootPath);
self::$instance = new TestSuite($rootPath);
foreach (Plugin::$callables as $callable) {
$callable();
}
return self::$instance;
}
if (self::$instance === null) {

View File

@ -13,7 +13,7 @@ use Pest\TestSuite;
use PHPUnit\Framework\TestCase;
/**
* Runs the given closure after all tests in the current file.
* Runs the given closure before all tests in the current file.
*/
function beforeAll(Closure $closure): void
{
@ -66,7 +66,7 @@ function test(string $description = null, Closure $closure = null)
return new HigherOrderTapProxy(TestSuite::getInstance()->test);
}
$filename = Backtrace::file();
$filename = Backtrace::testFile();
return new TestCall(TestSuite::getInstance(), $filename, $description, $closure);
}
@ -80,9 +80,9 @@ function test(string $description = null, Closure $closure = null)
*/
function it(string $description, Closure $closure = null): TestCall
{
$filename = Backtrace::file();
$description = sprintf('it %s', $description);
return new TestCall(TestSuite::getInstance(), $filename, sprintf('it %s', $description), $closure);
return test($description, $closure);
}
/**

11
stubs/Laravel/Helpers.php Normal file
View File

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

11
stubs/Lumen/Helpers.php Normal file
View File

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

3
stubs/Lumen/Pest.php Normal file
View File

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

17
stubs/Lumen/phpunit.xml Normal file
View File

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

View File

@ -0,0 +1,7 @@
PASS Tests\Fixtures\DirectoryWithTests\ExampleTest
✓ it example 1
PASS Tests\Fixtures\ExampleTest
✓ it example 2
Tests: 2 passed

View File

@ -0,0 +1,4 @@
PASS Tests\Fixtures\DirectoryWithTests\ExampleTest
✓ it example 1
Tests: 1 passed

View File

@ -0,0 +1,60 @@
PASS Tests\Playground
✓ basic
Tests: 1 passed
Time: 0.20s
Cov: 6.49%
Actions/AddsDefaults ........................................... 0.0 %
Actions/AddsTests .............................................. 0.0 %
Actions/LoadStructure .......................................... 0.0 %
Actions/ValidatesConfiguration ................................. 0.0 %
Actions/ValidatesEnvironment ................................... 0.0 %
Concerns/TestCase 40..54, 71..88, 123..126, 147 ............... 44.4 %
Console/Command ................................................ 0.0 %
Contracts/HasPrintableTestCaseName ............................. 0.0 %
Contracts/Plugins/AddsOutput ................................ 100.0 %
Contracts/Plugins/HandlesArguments .......................... 100.0 %
Datasets ....................................................... 0.0 %
Exceptions/AfterAllAlreadyExist ................................ 0.0 %
Exceptions/AfterEachAlreadyExist ............................... 0.0 %
Exceptions/AttributeNotSupportedYet ............................ 0.0 %
Exceptions/BeforeEachAlreadyExist .............................. 0.0 %
Exceptions/DatasetAlreadyExist ................................. 0.0 %
Exceptions/DatasetDoesNotExist ................................. 0.0 %
Exceptions/FileOrFolderNotFound ................................ 0.0 %
Exceptions/InvalidConsoleArgument .............................. 0.0 %
Exceptions/InvalidPestCommand .................................. 0.0 %
Exceptions/InvalidUsesPath ..................................... 0.0 %
Exceptions/ShouldNotHappen ..................................... 0.0 %
Exceptions/TestAlreadyExist .................................... 0.0 %
Exceptions/TestCaseAlreadyInUse ................................ 0.0 %
Exceptions/TestCaseClassOrTraitNotFound ........................ 0.0 %
Factories/TestCaseFactory 111..133, 141..204 ................... 8.2 %
Laravel/Commands/PestDatasetCommand ............................ 0.0 %
Laravel/Commands/PestInstallCommand ............................ 0.0 %
Laravel/Commands/PestTestCommand ............................... 0.0 %
Laravel/PestServiceProvider .................................... 0.0 %
PendingObjects/AfterEachCall ................................... 0.0 %
PendingObjects/BeforeEachCall .................................. 0.0 %
PendingObjects/TestCall ........................................ 0.0 %
PendingObjects/UsesCall ........................................ 0.0 %
Plugin ......................................................... 0.0 %
Repositories/AfterAllRepository ................................ 0.0 %
Repositories/AfterEachRepository 28..33 ....................... 60.0 %
Repositories/BeforeAllRepository ............................... 0.0 %
Repositories/BeforeEachRepository 26..31 ...................... 20.0 %
Repositories/TestRepository .................................... 0.0 %
Support/Backtrace .............................................. 0.0 %
Support/ChainableClosure .................................... 100.0 %
Support/Container .............................................. 0.0 %
Support/ExceptionTrace 25..32 ................................. 28.6 %
Support/HigherOrderMessage ..................................... 0.0 %
Support/HigherOrderMessageCollection 24..25, 33, 43 ........... 50.0 %
Support/HigherOrderTapProxy .................................... 0.0 %
Support/NullClosure ......................................... 100.0 %
Support/Reflection ............................................. 0.0 %
Support/Str .................................................... 0.0 %
TestSuite 80..87, 95..101, 105 ................................ 20.0 %
globals ........................................................ 0.0 %

View File

@ -0,0 +1,5 @@
PASS Tests\Fixtures\DirectoryWithTests\ExampleTest
it example 1
Tests: 1 passed

View File

@ -0,0 +1,5 @@
 PASS  Tests\Fixtures\DirectoryWithTests\ExampleTest
✓ it example 1
Tests: 1 passed

View File

@ -1,5 +1,5 @@
PASS Tests\CustomTestCase\PhpunitTest
PASS Tests\CustomTestCase\ExecutedTest
✓ that gets executed
PASS Tests\Features\AfterAll
@ -24,7 +24,7 @@
✓ it sets arrays
✓ it gets bound to test case object with ('a')
✓ it gets bound to test case object with ('b')
✓ it truncates the description with (' fooo fooo fooo fooo fooo fooo fooo f...oo fooo')
✓ it truncates the description with ('FoooFoooFoooFoooFoooFoooFoooF...ooFooo')
✓ lazy datasets with (1)
✓ lazy datasets with (2)
✓ lazy datasets did the job right
@ -40,10 +40,25 @@
✓ eager wrapped registered datasets with (1)
✓ eager wrapped registered datasets with (2)
✓ eager registered wrapped datasets did the job right
✓ lazy named datasets with ( bar object (...))
✓ lazy named datasets with (Bar Object (...))
✓ it creates unique test case names with ('Name 1', Pest\Plugin Object (), true) #1
✓ it creates unique test case names with ('Name 1', Pest\Plugin Object (), true) #2
✓ it creates unique test case names with ('Name 1', Pest\Plugin Object (), false)
✓ it creates unique test case names with ('Name 2', Pest\Plugin Object (), false)
✓ 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
PASS Tests\Features\Depends
✓ first
✓ second
✓ depends
✓ depends with ...params
✓ depends with defined arguments
✓ depends run test only once
PASS Tests\Features\Exceptions
✓ it gives access the the underlying expect exception
✓ it gives access the the underlying expectException
✓ it catch exceptions
✓ it catch exceptions and messages
@ -53,40 +68,48 @@
✓ it allows to call underlying protected/private methods
✓ it throws error if method do not exist
PASS Tests\Features\HigherOrderMessages
PASS Tests\Features\HigherOrderTests
✓ it proxies calls to object
PASS Tests\Features\It
✓ it is a test
✓ it is a higher order message test
PASS Tests\Features\Macro
✓ 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 'bar' → assertTrue true
✓ get 'foo' → assertTrue true
WARN Tests\Features\Skip
✓ it do not skips
s it skips with truthy
s it skips with truthy condition by default
s it skips with message → skipped because bar
s it skips with truthy closure condition
- it skips with truthy
- it skips with truthy condition by default
- it skips with message → skipped because bar
- it skips with truthy closure condition
✓ it do not skips with falsy closure condition
s it skips with condition and messsage → skipped because foo
- it skips with condition and message → skipped because foo
PASS Tests\Features\Test
✓ a test
✓ higher order message test
PASS Tests\Fixtures\DirectoryWithTests\ExampleTest
✓ it example
✓ it example 1
PASS Tests\Fixtures\ExampleTest
✓ it example
✓ it example 2
PASS Tests\PHPUnit\CustomTestCase\UsesPerDirectory
✓ closure was bound to custom test case
✓ closure was bound to CustomTestCase
PASS Tests\PHPUnit\CustomTestCaseInSubFolders\SubFolder\SubFolder\UsesPerSubDirectory
✓ closure was bound to custom test case
✓ closure was bound to CustomTestCase
PASS Tests\PHPUnit\CustomTestCaseInSubFolders\SubFolder2\UsesPerFile
✓ custom traits can be used
@ -95,9 +118,9 @@
PASS Tests\Playground
✓ basic
PASS Tests\Unit\Actions\AddsCoverage
✓ it adds coverage if --coverage exist
✓ it adds coverage if --min exist
PASS Tests\Plugins\Traits
✓ it allows global uses
✓ it allows multiple global uses registered in the same path
PASS Tests\Unit\Actions\AddsDefaults
✓ it sets defaults
@ -112,12 +135,22 @@
✓ it throws exception when `process isolation` is true
✓ it do not throws exception when `process isolation` is false
PASS Tests\Unit\Console\Coverage
✓ it generates coverage based on file input
PASS Tests\Unit\Plugins\Version
✓ it outputs the version when --version is used
✓ it do not outputs version when --version is not used
PASS Tests\Unit\Support\Backtrace
✓ it gets file name from called file
PASS Tests\Unit\Support\Container
✓ it exists
✓ it gets an instance
✓ autowire
✓ it creates an instance and resolves parameters
✓ it creates an instance and resolves also sub parameters
✓ it can resolve builtin value types
✓ it cannot resolve a parameter without type
PASS Tests\Unit\Support\Reflection
✓ it gets file name from closure
✓ it gets property values
@ -128,9 +161,11 @@
PASS Tests\Visual\SingleTestOrDirectory
✓ allows to run a single test
✓ allows to run a directory
✓ it has ascii chars
✓ it disable decorating printer when colors is set to never
WARN Tests\Visual\Success
s visual snapshot of test suite on success
- visual snapshot of test suite on success
Tests: 6 skipped, 69 passed
Time: 2.63s
Tests: 6 skipped, 96 passed
Time: 3.43s

View File

@ -3,3 +3,22 @@
if (class_exists(NunoMaduro\Collision\Provider::class)) {
(new NunoMaduro\Collision\Provider())->register();
}
trait PluginTrait
{
public function assertPluginTraitGotRegistered(): void
{
assertTrue(true);
}
}
trait SecondPluginTrait
{
public function assertSecondPluginTraitGotRegistered(): void
{
assertTrue(true);
}
}
Pest\Plugin::uses(PluginTrait::class);
Pest\Plugin::uses(SecondPluginTrait::class);

View File

@ -3,6 +3,7 @@
use Pest\Datasets;
use Pest\Exceptions\DatasetAlreadyExist;
use Pest\Exceptions\DatasetDoesNotExist;
use Pest\Plugin;
it('throws exception if dataset does not exist', function () {
$this->expectException(DatasetDoesNotExist::class);
@ -106,3 +107,21 @@ $namedDatasets = [
test('lazy named datasets', function ($text) use ($state, $datasets) {
assertTrue(true);
})->with($namedDatasets);
$counter = 0;
it('creates unique test case names', function (string $name, Plugin $plugin, bool $bool) use (&$counter) {
assertTrue(true);
$counter++;
})->with([
['Name 1', new Plugin(), true],
['Name 1', new Plugin(), true],
['Name 1', new Plugin(), false],
['Name 2', new Plugin(), false],
['Name 2', new Plugin(), true],
['Name 1', new Plugin(), true],
]);
it('creates unique test case names - count', function () use (&$counter) {
assertEquals(6, $counter);
});

View File

@ -0,0 +1,40 @@
<?php
$runCounter = 0;
test('first', function () use (&$runCounter) {
assertTrue(true);
$runCounter++;
return 'first';
});
test('second', function () use (&$runCounter) {
assertTrue(true);
$runCounter++;
return 'second';
});
test('depends', function () {
assertEquals(
['first', 'second'],
func_get_args()
);
})->depends('first', 'second');
test('depends with ...params', function (string ...$params) {
assertEquals(
['first', 'second'],
$params
);
})->depends('first', 'second');
test('depends with defined arguments', function (string $first, string $second) {
assertEquals('first', $first);
assertEquals('second', $second);
})->depends('first', 'second');
test('depends run test only once', function () use (&$runCounter) {
assertEquals(2, $runCounter);
})->depends('first', 'second');

16
tests/Features/Macro.php Normal file
View File

@ -0,0 +1,16 @@
<?php
use Illuminate\Support\Traits\Macroable;
use PHPUnit\Framework\TestCase;
uses(Macroable::class);
beforeEach()->macro('bar', function () {
assertInstanceOf(TestCase::class, $this);
});
it('can call chained macro method')->bar();
it('will throw exception from call if no macro exists')
->throws(BadMethodCallException::class)
->foo();

View File

@ -1,15 +1,17 @@
<?php
use function Tests\mock;
interface Foo
{
public function bar(): int;
}
it('has bar', function () {
$mock = Mockery::mock(Foo::class);
$mock = mock(Foo::class);
$mock->shouldReceive('bar')
->times(1)
->andReturn(2);
assertEquals(2, $mock->bar());
$mock->bar();
});

View File

@ -0,0 +1,29 @@
<?php
use PHPUnit\Framework\TestCase;
uses(Gettable::class);
/**
* @return TestCase|Gettable
*/
function get(string $route)
{
return test()->get($route);
}
trait Gettable
{
/**
* @return TestCase|Gettable
*/
public function get(string $route)
{
assertNotEmpty($route);
return $this;
}
}
get('foo')->get('bar')->assertTrue(true);
get('foo')->assertTrue(true);

View File

@ -24,6 +24,6 @@ it('do not skips with falsy closure condition')
->skip(function () { return false; })
->assertTrue(true);
it('skips with condition and messsage')
it('skips with condition and message')
->skip(true, 'skipped because foo')
->assertTrue(false);

View File

@ -1,3 +1,3 @@
<?php
it('example')->assertTrue(true);
it('example 1')->assertTrue(true);

View File

@ -1,3 +1,3 @@
<?php
it('example')->assertTrue(true);
it('example 2')->assertTrue(true);

11
tests/Helpers.php Normal file
View File

@ -0,0 +1,11 @@
<?php
namespace Tests;
use Mockery;
use Mockery\MockInterface;
function mock(string $class): MockInterface
{
return Mockery::mock($class);
}

View File

@ -7,7 +7,7 @@ namespace Tests\CustomTestCase;
use function PHPUnit\Framework\assertTrue;
use PHPUnit\Framework\TestCase;
class PhpunitTest extends TestCase
class ExecutedTest extends TestCase
{
public static $executed = false;
@ -16,8 +16,8 @@ class PhpunitTest extends TestCase
{
self::$executed = true;
$this->assertTrue(true);
assertTrue(true);
}
}
// register_shutdown_function(fn () => assertTrue(PhpunitTest::$executed));
// register_shutdown_function(fn () => assertTrue(ExecutedTest::$executed));

5
tests/Plugins/Traits.php Normal file
View File

@ -0,0 +1,5 @@
<?php
it('allows global uses')->assertPluginTraitGotRegistered();
it('allows multiple global uses registered in the same path')->assertSecondPluginTraitGotRegistered();

View File

@ -1,32 +0,0 @@
<?php
use Pest\Actions\AddsCoverage;
use Pest\TestSuite;
it('adds coverage if --coverage exist', function () {
$testSuite = new TestSuite(getcwd());
assertFalse($testSuite->coverage);
$arguments = AddsCoverage::from($testSuite, []);
assertEquals([], $arguments);
assertFalse($testSuite->coverage);
$arguments = AddsCoverage::from($testSuite, ['--coverage']);
assertEquals(['--coverage-php', \Pest\Console\Coverage::getPath()], $arguments);
assertTrue($testSuite->coverage);
});
it('adds coverage if --min exist', function () {
$testSuite = new TestSuite(getcwd());
assertEquals($testSuite->coverageMin, 0.0);
assertFalse($testSuite->coverage);
AddsCoverage::from($testSuite, []);
assertEquals($testSuite->coverageMin, 0.0);
AddsCoverage::from($testSuite, ['--min=2']);
assertEquals($testSuite->coverageMin, 2.0);
AddsCoverage::from($testSuite, ['--min=2.4']);
assertEquals($testSuite->coverageMin, 2.4);
});

View File

@ -1,24 +0,0 @@
<?php
use Pest\Console\Coverage;
it('generates coverage based on file input', function () {
assertEquals([
'4..6', '102',
], Coverage::getMissingCoverage(new class() {
public function getCoverageData(): array
{
return [
1 => ['foo'],
2 => ['bar'],
4 => [],
5 => [],
6 => [],
7 => null,
100 => null,
101 => ['foo'],
102 => [],
];
}
}));
});

View File

@ -0,0 +1,20 @@
<?php
use Pest\Plugins\Version;
use Symfony\Component\Console\Output\BufferedOutput;
it('outputs the version when --version is used', function () {
$output = new BufferedOutput();
$plugin = new Version($output);
$plugin->handleArguments(['foo', '--version']);
assertStringContainsString('Pest 0.2.2', $output->fetch());
});
it('do not outputs version when --version is not used', function () {
$output = new BufferedOutput();
$plugin = new Version($output);
$plugin->handleArguments(['foo', 'bar']);
assertEquals('', $output->fetch());
});

View File

@ -0,0 +1,69 @@
<?php
use Pest\Exceptions\ShouldNotHappen;
use Pest\Support\Container;
use Pest\TestSuite;
uses()->group('container');
beforeEach(function () {
$this->container = new Container();
});
it('exists')
->assertTrue(class_exists(Container::class));
it('gets an instance', function () {
$this->container->add(Container::class, $this->container);
assertSame($this->container, $this->container->get(Container::class));
});
test('autowire', function () {
assertInstanceOf(Container::class, $this->container->get(Container::class));
});
it('creates an instance and resolves parameters', function () {
$this->container->add(Container::class, $this->container);
$instance = $this->container->get(ClassWithDependency::class);
assertInstanceOf(ClassWithDependency::class, $instance);
});
it('creates an instance and resolves also sub parameters', function () {
$this->container->add(Container::class, $this->container);
$instance = $this->container->get(ClassWithSubDependency::class);
assertInstanceOf(ClassWithSubDependency::class, $instance);
});
it('can resolve builtin value types', function () {
$this->container->add('rootPath', getcwd());
$instance = $this->container->get(TestSuite::class);
assertInstanceOf(TestSuite::class, $instance);
});
it('cannot resolve a parameter without type', function () {
$this->container->get(ClassWithoutTypeParameter::class);
})->throws(ShouldNotHappen::class);
class ClassWithDependency
{
public function __construct(Container $container)
{
}
}
class ClassWithSubDependency
{
public function __construct(ClassWithDependency $param)
{
}
}
class ClassWithoutTypeParameter
{
public function __construct($param)
{
}
}

View File

@ -2,31 +2,56 @@
use Symfony\Component\Process\Process;
$run = function (string $target) {
$process = new Process(['./bin/pest', $target], dirname(__DIR__, 2));
$run = function (string $target, $decorated = false) {
$process = new Process(['php', 'bin/pest', $target], dirname(__DIR__, 2));
$process->run();
return preg_replace('#\\x1b[[][^A-Za-z]*[A-Za-z]#', '', $process->getOutput());
return $decorated ? $process->getOutput() : preg_replace('#\\x1b[[][^A-Za-z]*[A-Za-z]#', '', $process->getOutput());
};
test('allows to run a single test', function () use ($run) {
assertStringContainsString(<<<EOF
PASS Tests\Fixtures\DirectoryWithTests\ExampleTest
it example
$snapshot = function ($name) {
$testsPath = dirname(__DIR__);
Tests: 1 passed
EOF, $run('tests/Fixtures/DirectoryWithTests/ExampleTest.php'));
});
return file_get_contents(implode(DIRECTORY_SEPARATOR, [
$testsPath,
'.snapshots',
"$name.txt",
]));
};
test('allows to run a directory', function () use ($run) {
assertStringContainsString(<<<EOF
PASS Tests\Fixtures\DirectoryWithTests\ExampleTest
it example
test('allows to run a single test', function () use ($run, $snapshot) {
assertStringContainsString(
$snapshot('allows-to-run-a-single-test'),
$run('tests/Fixtures/DirectoryWithTests/ExampleTest.php'));
})->skip(PHP_OS_FAMILY === 'Windows');
PASS Tests\Fixtures\ExampleTest
it example
test('allows to run a directory', function () use ($run, $snapshot) {
assertStringContainsString(
$snapshot('allows-to-run-a-directory'),
$run('tests/Fixtures')
);
})->skip(PHP_OS_FAMILY === 'Windows');
Tests: 2 passed
EOF, $run('tests/Fixtures'));
});
it('has ascii chars', function () use ($run, $snapshot) {
assertStringContainsString(
$snapshot('has-ascii-chars'),
$run('tests/Fixtures/DirectoryWithTests/ExampleTest.php', true)
);
})->skip(PHP_OS_FAMILY === 'Windows');
it('disable decorating printer when colors is set to never', function () use ($snapshot) {
$process = new Process([
'php',
'./bin/pest',
'--colors=never',
'tests/Fixtures/DirectoryWithTests/ExampleTest.php',
], dirname(__DIR__, 2));
$process->run();
$output = $process->getOutput();
assertStringContainsString(
$snapshot('disable-decorating-printer'),
$output
);
})->skip(PHP_OS_FAMILY === 'Windows');

View File

@ -9,7 +9,7 @@ test('visual snapshot of test suite on success', function () {
]);
$output = function () use ($testsPath) {
$process = (new Symfony\Component\Process\Process(['./bin/pest'], dirname($testsPath), ['EXCLUDE' => 'integration', 'REBUILD_SNAPSHOTS' => false]));
$process = (new Symfony\Component\Process\Process(['php', 'bin/pest'], dirname($testsPath), ['EXCLUDE' => 'integration', 'REBUILD_SNAPSHOTS' => false]));
$process->run();
@ -24,4 +24,5 @@ test('visual snapshot of test suite on success', function () {
array_pop($output);
assertStringContainsString(implode("\n", $output), file_get_contents($snapshot));
}
})->skip(!getenv('REBUILD_SNAPSHOTS') && getenv('EXCLUDE'));
})->skip(!getenv('REBUILD_SNAPSHOTS') && getenv('EXCLUDE'))
->skip(PHP_OS_FAMILY === 'Windows');