diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 162521a..0000000 --- a/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -*.swp -.idea -vendor/ -Vagrantfile -provisioning/ -.vagrant/ -hhi/ -composer.lock diff --git a/.hhconfig b/.hhconfig deleted file mode 100644 index 9d5430d..0000000 --- a/.hhconfig +++ /dev/null @@ -1,2 +0,0 @@ -assume_php = false -user_attributes = Test Setup SuiteProvider TearDown Skip Data DataProvider diff --git a/LICENSE b/LICENSE deleted file mode 100644 index fda51f2..0000000 --- a/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2014 Brian Scaturro - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is furnished -to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/README.md b/README.md deleted file mode 100644 index 07c58bb..0000000 --- a/README.md +++ /dev/null @@ -1,397 +0,0 @@ -HackUnit -======== - -Testing framework written in and for [Hack.](http://hacklang.org) - -[![Gitter](https://badges.gitter.im/HackPack/HackUnit.svg)](https://gitter.im/HackPack/HackUnit?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) - -### But Why?! -There are already many testing frameworks available, such as [PHPUnit](https://phpunit.de/) and [behat.](http://behat.org) Why should you use this one? - -*Because you like Hack specific features!* - -With HackUnit, you can easily run your tests using cooperative async with the built in `async` keyword. - -With HackUnit, you can easily iterate through your test data in an async way using the `yield` keyword. - -With HackUnit, you indicate test methods using [annotations.](http://docs.hhvm.com/manual/en/hack.attributes.php) - -The original goal of HackUnit was to write a testing framework using Hack's strict mode. The project will stay consistent with this goal as more features are added. - -Install -------- - -Install HackUnit using [Composer](https://getcomposer.org): - -```bash -composer require --dev hackpack/hackunit -``` - -Usage ------ - -HackUnit can be run from the command line using the included executable script `bin/hackunit`. By default, this will be symlinked in your `vendor/bin` directory. - -Thus, the most common way to invoke HackUnit is: -```bash -vendor/bin/hackunit path1 [path2] ... -``` -where `path1`, `path2`, etc... are each base paths/files to scan for test suites. If any specified path is a directory, the directory will be recursively scanned. - -Some command line options exist to alter the behavior of HackUnit: - -* `--exclude="path/to/exclude"` : Do not scan the file or any file under the path provided. This option may be given multiple times to exclude multiple paths/files. - -Test Suites ------------ -To define a test suite, create a class and [annotate](http://docs.hhvm.com/manual/en/hack.attributes.php) the appropriate methods. - -You may inspect HackUnit’s test files for concrete examples. - -### Tests - -Individual test methods are defined using the -`<>` [attribute](http://docs.hhvm.com/manual/en/hack.attributes.php). -Execution order of the tests is not guaranteed. - -Each test method MUST accept exactly 1 parameter, with the type hint of `HackPack\HackUnit\Contract\Assert`. -If you mark a method as a test and the signature does not match, the test will not be run. - -Test methods may be instance methods, or they may be class (static) methods. - -```php -namespace My\Namespace\Test; - -use HackPack\HackUnit\Contract\Assert; - -class MySuite -{ - <> - public function testSomething(Assert $assert) : void - { - // Do some testing here! - $assert->int(2)->not()->eq(3); - $assert - ->whenCalled(() ==> {throw new \Exception(‘bad error)}) - ->willThrowClassWithMessage(\Exception::class, ‘bad error’) - ; - } -} -``` - -### Async - -Running your tests async is as easy as adding the async keyword to your test method. - -```php -namespace My\Namespace\Test; - -use HackPack\HackUnit\Contract\Assert; - -class MyAsyncSuite -{ - <> - public async function testSomething(Assert $assert) : Awaitable - { - // Make some async DB calls here as part of your test! - $user = await get_user(); - - // Or maybe an async curl call - $result = await get_external_user($user->id, 'api password'); - - $assert->string($result['user_name'])->is('expected username'); - } -} -``` - -All such `async` tests are run using cooperative multitasking (see the [async documentation](http://docs.hhvm.com/hack/async/introduction)), allowing your entire test suite to run faster if your tests perform real I/O operations (DB calls, network calls, etc...). - -### Setup - -You may have HackUnit run some methods before each individual test method is run and/or before any test method is run for the suite. To do so, mark the appropriate method with the `<>` [attribute](http://docs.hhvm.com/manual/en/hack.attributes.php). Multiple setup methods may be declared, but the execution order is not guaranteed. - -Each setup method (both suite and test) MUST require exactly 0 parameters. If you mark a method as setup and it requires a parameter, it will not be executed and a parse error will be shown in the report. - -```php -class MySuite -{ - <> - public function setUpSuite() : void - { - // Suite level Setup methods must be class (static) methods - // Perform tasks before any tests in this suite are run - } - - <> - public function setUpTest() : void - { - // Perform tasks just before each test in this suite is run - } - - <> - public function setUpTestAgain() : void - { - // Multiple set up methods may be defined - // If there are no parameters to the setup attribute, the method is treated like a test setup - } -} -``` - -Suite setup methods are run once, before any of the test methods in the class are run. - -Test setup methods are run just before each test method is run (and thus are potentially run multiple times). - -### Teardown -You may have HackUnit run some methods after each individual test method is run and/or after all test methods are run for the suite. To do so, mark the appropriate method with the `<>` [attribute](http://docs.hhvm.com/manual/en/hack.attributes.php). Multiple teardown methods may be declared, but the execution order is not guaranteed. - -Each teardown method (both suite and test) MUST require exactly 0 parameters. If you mark a method as teardown and it requires a parameter, it will not be executed and a parse error will be shown in the report. - -```php -class MySuite -{ - <> - public static function cleanUpAfterSuite() : void - { - // Suite level TearDown methods must be class (static) methods - // Perform tasks after all tests in this suite are run - } - - <> - public function cleanUpAfterTest() : void - { - // Perform tasks just after each test in this suite is run - } - - <> - public function cleanUpMoarStuff() : void - { - // This is also a ‘test’ teardown method - } -} -``` - -Suite tear down methods are run once, after all of the test methods in the class are run. - -Test tear down methods are run just after each test method is run (and thus are potentially run multiple times). - -### Suite Providers -Your test suite may require parameters to be passed to the constructor. To tell HackUnit how to construct your test suite, you must define at least one Suite Provider. A Suite Provider is marked with the `<>` attribute. - -You may define multiple Suite Providers for a single test suite. To do so, you must label each one by passing in one string parameter to the attribute (i.e., `<>`). There are no restrictions on the name of a provider except that each provider name must be unique. - -To use a particular Suite Provider for a particular test, you must pass the name of the Suite Provider to the Test attribute. - -```php -class SuiteWithProviders -{ - <> - public static function() : this - { - $someDependency = new TestDoubleOne(); - return new static($someDependency); - } - - <> - public static function() : this - { - $someDependency = new TestDoubleTwo(); - return new static($someDependency); - } - - <> - public function testOne(Assert $assert) : void - { - // Do some assertions using TestDoubleOne - } - - <> - public function testTwo(Assert $assert) : void - { - // Do some assertions using TestDoubleTwo - } -} -``` - -Assertions ----------- - -All test methods must accept exactly one parameter of type `HackPack\HackUnit\Contract\Assert` which should be used to make testable assertions. This object is used to build assertions that will be checked and reported by HackUnit. - -In all examples below, `$assert` contains an instance of `HackPack\HackUnit\Contract\Assert`. - -### Bool Assertions - -To make assertions about `bool` type variables, call `$assert->bool($myBool)->is($expected)`. - -### Numeric Assertions - -To make assertions about `int` and `float` type variables, call `$assert->int($myInt)` and `$assert->float($myFloat)` respectively. The resulting object contains the following methods to actually perform the appropriate assertion. - -* `$assert->int($myInt)->eq($expected);` : Assert that `$myInt` is identical to `$expected` -* `$assert->int($myInt)->gt($expected);` : Assert that `$myInt` is greater than `$expected` -* `$assert->int($myInt)->lt($expected);` : Assert that `$myInt` is less than `$expected` -* `$assert->int($myInt)->gte($expected);` : Assert that `$myInt` is greater than or equal to `$expected` -* `$assert->int($myInt)->lte($expected);` : Assert that `$myInt` is less than or equal to `$expected` - -All of the above may be modified with a call to `not()` before the assertion to negate the meaning of the assertion. For example: - -``` - $assert->int($myInt)->not()->eq($expected); -``` - -*Note*: This library only allows assertions to compare identical numeric types. `$assert->int(1)->eq(1.0);` produces a type error. - -### String Assertions - -To make assertions about `string` type variables, call `$assert->string($myString)`. The resulting object contains the following methods to actually perform the appropriate assertion. - -* `$assert->string($myString)->is($expected)` : Assert that `$myString === $expected` -* `$assert->string($myString)->hasLength($int)` : Assert that the string has a length of `$int` -* `$assert->string($myString)->matches($pattern)` : Assert that the regular expression contained in `$pattern` matches the string -* `$assert->string($myString)->contains($subString)` : Assert that `$subString` is a substring of `$myString` -* `$assert->string($myString)->containedBy($superString)` : Assert that `$myString` is a substring of `$superString` - -All of the above assertions may be negated by calling `not()` before making the assertion. For example: - -``` - $assert->string($myString)->not()->containedBy($superString); -``` - -### Collection Assertions - -To make assertions about collections and arrays, call `$assert->container($context)`. The resulting object contains the following methods to perform assertions. - -* `$assert->container($context)->isEmpty();` : Assert that the context has no elements -* `$assert->container($context)->contains($value);` : Assert that the context contains the value given -* `$assert->container($context)->containsAny($list);` : Assert that the context contains at least one element in the list provided -* `$assert->container($context)->containsAll($list);` : Assert that the context contains all elements in the list provided -* `$assert->container($context)->containsOnly($list);` : Assert that the context contains all elements in the list provided and no more - -All of the `contains*` assertions above accept an optional second parameter which must be a callable. The callable will be used to compare the elements in the context with the element(s) provided. If the elements passed to the callable should be treated as equivalent, the callable should return `true`, otherwise it should return `false`. - -#### Keyed Collections - -If the keys of the container are important for the assertions, you should use `$assert->keyedContainer($context)`. The resulting object contains the following methods to perform assertions. - -* `$assert->container($context)->contains($key, $value);` : Assert that the value contained in the context at the key provided matches the value provided -* `$assert->container($context)->containsKey($key);` : Assert that the context contains the provided key -* `$assert->container($context)->containsAny($list);` : Assert that the context contains at least one element in the list provided where both the key and value must be considered equivalent -* `$assert->container($context)->containsAll($list);` : Assert that the context contains all elements in the list provided where both the key and value must be considered equivalent -* `$assert->container($context)->containsOnly($list);` : Assert that the context contains all elements in the list provided and no more where both the key and value must be considered equivalent - -All of the assertions above accept an optional second (or third in the case of `contains`) parameter which must be a callable. The callable will be used to compare the values of the elements in the context with the element(s) provided. If the values passed to the callable should be treated as equivalent, the callable should return `true`, otherwise it should return `false`. - -### Mixed Assertions - -To make generic assertions about a variable of any type, call `$assert->mixed($context)`. The resulting object contains the following methods to actually perform the appropriate assertion. - -* `$assert->mixed($context)->isNull();` : Assert that `$context === null` -* `$assert->mixed($context)->isBool();` : Assert that `$context` is of type `bool` -* `$assert->mixed($context)->isInt();` : Assert that `$context` is of type `int` -* `$assert->mixed($context)->isFloat();` : Assert that `$context` is of type `float` -* `$assert->mixed($context)->isString();` : Assert that `$context` is of type `string` -* `$assert->mixed($context)->isArray();` : Assert that `$context` is of type `array` -* `$assert->mixed($context)->isObject();` : Assert that `$context` is of type `object` -* `$assert->mixed($context)->isTypeOf($className)` : Assert that `$context instanceof $className` -* `$assert->mixed($context)->looselyEquals($expected)` : Assert that `$context == $expected` *note the loose comparison* -* `$assert->mixed($context)->identicalTo($expected)` : Assert that `$context === $expected` *note the strict comparison* - -Skipping Tests -------------- -There are two ways to skip execution of a particular test method: - -1. Add the attribute `<>` to the test method or the test suite. If the `<>` attribute is added to the suite, all tests in that class will be skipped. -1. Invoke the `skip()` method of the `Assert` object passed to your test method. - -```php -use \HackPack\HackUnit\Contract\Assert; - -<> -class SkippedSuite -{ - // All methods here would be skipped -} - -class MySuite -{ - <> - public function skippedTest(Assertion $assert) : void - { - // This will not be run and the test will be marked skip in the report. - } - - <> - public function skipFromMiddleOfTest(Assert $assert) : void - { - // This will be run - $assert->skip(); - // This will not be run and the test will be marked skip in the report. - } -} -``` - -Data Providers --------------- - -You may mark some methods as providing a list of data that should be iterated and passed to a test method. To do this, mark the data providing method with the `<>` attribute. You must name your data provider as shown to allow HackUnit to know which data provider should be used for each test that consumes data. - -```php -class TestThatUsesData { - - <> - public static function loadCsvValues(): AsyncIterator> - { - $asynCsvLoader = new AsyncCsvLoader('/path/to/data.csv'); - foreach($asyncCsvLoader await as $line) { - yield $line; - } - } - - <> - public function testCsvValues(Assert $assert, array $line): void - { - // Do assertions using the data from the csv file. - } - - <> - public static function count(): Traversable - { - return Vector{1, 2, 3, 4, 5}; - } - - <> - public function countingTest(Assert $assert, int $count): void - { - // This test will be run five times, once for each of the values in the vector above. - } -} -``` - -The example above demonstrates defining both async and non-async data providers. Special note should be taken of the return values. - -* Async data providers _MUST_ return `AsyncIterator`. -* Non-async data providers _MUST_ return `Traversable`. -* The consumer of a data provider _MUST_ accept exactly `dataType` as the second parameter. - -In the example above, a `MalformedSuite` error would occur if the csv consumer function had the signature `public function testCsvValues(Assert $assert, Traversable): void`. Even though an `array` is a type of `Traversable`, the HackUnit parser compares the string representation of the types to ensure invalid data is never passed to the test methods. - -How HackUnit loads tests ------------------------- -All files inside the base path(s) specified from the command line will be scanned for class definitions using Fred Emmott's [Definition Finder](https://github.com/fredemmott/definition-finder) library. Those files will then be loaded and reflection is used to determine which classes are test suites, and which methods perform each task in the suite. - -Thanks [Fred!](https://github.com/fredemmott) - -Strict mode all the files! --------------------------- - -Well... not quite. - -Top level code must use `// partial` mode, so the `bin/hackunit` file is not in strict mode. The rest of the project is, with one exception. Test suite files must be dynamically loaded after being scanned for test suites. The only way I can see to perform this dynamic inclusion is to use `include_once` inside of a class method, which is disallowed in strict mode. This one exception is marked with a `/* HH_FIXME */` comment, which disables the type checker for that one line. - -Running HackUnit's tests ------------------------- -HackUnit is tested with HackUnit. From the project directory run: - -``` -hhvm /path/to/composer.phar test -``` diff --git a/bin/hackunit b/bin/hackunit deleted file mode 100755 index 2eefd62..0000000 --- a/bin/hackunit +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env hhvm -build()->run(); diff --git a/circle.yml b/circle.yml deleted file mode 100644 index 5bfd28d..0000000 --- a/circle.yml +++ /dev/null @@ -1,14 +0,0 @@ -machine: - services: - - docker - -dependencies: - override: - - docker info - - docker pull hhvm/hhvm:3.15-lts-latest - - docker pull kilahm/composer-hhvm:3.15.1 - - docker run --rm -v "$(pwd)":"$(pwd)" --workdir="$(pwd)" kilahm/composer-hhvm:3.15.1 install - -test: - override: - - docker run -v "$(pwd)":"$(pwd)" --workdir="$(pwd)" -e "CIRCLE_TEST_REPORTS=$CIRCLE_TEST_REPORTS" hhvm/hhvm:3.15-lts-latest hhvm -c test/self-test.ini test/self-test.php diff --git a/composer.json b/composer.json deleted file mode 100644 index 5aaf767..0000000 --- a/composer.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "name": "hackpack/hackunit", - "description": "An xUnit testing framework for Hack", - "type": "library", - "keywords": [ - "testing", - "xunit", - "hack", - "hhvm", - "hacklang" - ], - "license": "MIT", - "authors": [ - { - "name": "Brian Scaturro", - "email": "scaturrob@gmail.com", - "role": "Creator" - }, - { - "name": "Isaac Leinweber", - "email": "brotchen@gmail.com", - "role": "Developer" - } - ], - "minimum-stability": "dev", - "require": { - "hhvm": "^3.11", - "facebook/definition-finder": "^1.0" - }, - "autoload": { - "psr-4": { - "HackPack\\HackUnit\\": "src/" - }, - "files": [ - "src/Event/Listeners.php" - ] - }, - "autoload-dev": { - "psr-4": { - "HackPack\\HackUnit\\Tests\\": "test" - } - }, - "bin": [ - "bin/hackunit" - ], - "scripts": { - "test": [ - "hhvm test/self-test.php" - ], - "format": "hh_format src; hh_format test;" - } -} diff --git a/docker-test.sh b/docker-test.sh deleted file mode 100755 index cd2481e..0000000 --- a/docker-test.sh +++ /dev/null @@ -1,3 +0,0 @@ -#! /usr/bin/env sh - -exec docker run -v "$(pwd)":"$(pwd)" --workdir="$(pwd)" --rm hhvm/hhvm:3.15-lts-latest hhvm -c test/self-test.ini test/self-test.php diff --git a/images/arrow-down.png b/images/arrow-down.png new file mode 100644 index 0000000..5c55c6a Binary files /dev/null and b/images/arrow-down.png differ diff --git a/images/octocat-small.png b/images/octocat-small.png new file mode 100644 index 0000000..57c1e44 Binary files /dev/null and b/images/octocat-small.png differ diff --git a/index.html b/index.html new file mode 100644 index 0000000..0a7a826 --- /dev/null +++ b/index.html @@ -0,0 +1,504 @@ + + + + + + Hackunit by HackPack + + + + + + + + +
+
+

Hackunit

+

xUnit testing framework written in hacklang

+ + + +

This project is maintained by HackPack

+ + +
+
+

+HackUnit

+ +

Testing framework written in and for Hack.

+ +

Gitter

+ +

+But Why?!

+ +

There are already many testing frameworks available, such as PHPUnit and behat. Why should you use this one?

+ +

Because you like Hack specific features!

+ +

With HackUnit, you can easily run your tests using cooperative async with the built in async keyword.

+ +

With HackUnit, you can easily iterate through your test data in an async way using the yield keyword.

+ +

With HackUnit, you indicate test methods using annotations.

+ +

The original goal of HackUnit was to write a testing framework using Hack's strict mode. The project will stay consistent with this goal as more features are added.

+ +

+Install

+ +

Install HackUnit using Composer:

+ +
composer require --dev hackpack/hackunit
+ +

+Usage

+ +

HackUnit can be run from the command line using the included executable script bin/hackunit. By default, this will be symlinked in your vendor/bin directory.

+ +

Thus, the most common way to invoke HackUnit is:

+ +
vendor/bin/hackunit path1 [path2] ...
+ +

where path1, path2, etc... are each base paths/files to scan for test suites. If any specified path is a directory, the directory will be recursively scanned.

+ +

Some command line options exist to alter the behavior of HackUnit:

+ +
    +
  • +--exclude="path/to/exclude" : Do not scan the file or any file under the path provided. This option may be given multiple times to exclude multiple paths/files.
  • +
+ +

+Test Suites

+ +

To define a test suite, create a class and annotate the appropriate methods.

+ +

You may inspect HackUnit’s test files for concrete examples.

+ +

+Tests

+ +

Individual test methods are defined using the +<<Test>> attribute. +Execution order of the tests is not guaranteed.

+ +

Each test method MUST accept exactly 1 parameter, with the type hint of HackPack\HackUnit\Contract\Assert. +If you mark a method as a test and the signature does not match, the test will not be run.

+ +

Test methods may be instance methods, or they may be class (static) methods.

+ +
namespace My\Namespace\Test;
+
+use HackPack\HackUnit\Contract\Assert;
+
+class MySuite
+{
+    <<Test>>
+    public function testSomething(Assert $assert) : void
+    {
+      // Do some testing here!
+      $assert->int(2)->not()->eq(3);
+      $assert
+          ->whenCalled(() ==> {throw new \Exception(‘bad error)})
+          ->willThrowClassWithMessage(\Exception::class, ‘bad error’)
+          ;
+    }
+}
+ +

+Async

+ +

Running your tests async is as easy as adding the async keyword to your test method.

+ +
namespace My\Namespace\Test;
+
+use HackPack\HackUnit\Contract\Assert;
+
+class MyAsyncSuite
+{
+    <<Test>>
+    public async function testSomething(Assert $assert) : Awaitable<void>
+    {
+        // Make some async DB calls here as part of your test!
+        $user = await get_user();
+
+        // Or maybe an async curl call
+        $result = await get_external_user($user->id, 'api password');
+
+        $assert->string($result['user_name'])->is('expected username');
+    }
+}
+ +

All such async tests are run using cooperative multitasking (see the async documentation), allowing your entire test suite to run faster if your tests perform real I/O operations (DB calls, network calls, etc...).

+ +

+Setup

+ +

You may have HackUnit run some methods before each individual test method is run and/or before any test method is run for the suite. To do so, mark the appropriate method with the <<Setup>> attribute. Multiple setup methods may be declared, but the execution order is not guaranteed.

+ +

Each setup method (both suite and test) MUST require exactly 0 parameters. If you mark a method as setup and it requires a parameter, it will not be executed and a parse error will be shown in the report.

+ +
class MySuite
+{
+    <<Setup(‘suite’)>>
+    public function setUpSuite() : void
+    {
+      // Suite level Setup methods must be class (static) methods
+      // Perform tasks before any tests in this suite are run
+    }
+
+    <<Setup(‘test’)>>
+    public function setUpTest() : void
+    {
+      // Perform tasks just before each test in this suite is run
+    }
+
+    <<Setup>>
+    public function setUpTestAgain() : void
+    {
+      // Multiple set up methods may be defined
+      // If there are no parameters to the setup attribute, the method is treated like a test setup
+    }
+}
+ +

Suite setup methods are run once, before any of the test methods in the class are run.

+ +

Test setup methods are run just before each test method is run (and thus are potentially run multiple times).

+ +

+Teardown

+ +

You may have HackUnit run some methods after each individual test method is run and/or after all test methods are run for the suite. To do so, mark the appropriate method with the <<TearDown>> attribute. Multiple teardown methods may be declared, but the execution order is not guaranteed.

+ +

Each teardown method (both suite and test) MUST require exactly 0 parameters. If you mark a method as teardown and it requires a parameter, it will not be executed and a parse error will be shown in the report.

+ +
class MySuite
+{
+    <<TearDown(‘suite’)>>
+    public static function cleanUpAfterSuite() : void
+    {
+      // Suite level TearDown methods must be class (static) methods
+      // Perform tasks after all tests in this suite are run
+    }
+
+    <<TearDown(‘test’)>>
+    public function cleanUpAfterTest() : void
+    {
+      // Perform tasks just after each test in this suite is run
+    }
+
+    <<TearDown>>
+    public function cleanUpMoarStuff() : void
+    {
+      // This is also a ‘test’ teardown method
+    }
+}
+ +

Suite tear down methods are run once, after all of the test methods in the class are run.

+ +

Test tear down methods are run just after each test method is run (and thus are potentially run multiple times).

+ +

+Suite Providers

+ +

Your test suite may require parameters to be passed to the constructor. To tell HackUnit how to construct your test suite, you must define at least one Suite Provider. A Suite Provider is marked with the <<SuiteProvider>> attribute.

+ +

You may define multiple Suite Providers for a single test suite. To do so, you must label each one by passing in one string parameter to the attribute (i.e., <<SuiteProvider('name of provider')>>). There are no restrictions on the name of a provider except that each provider name must be unique.

+ +

To use a particular Suite Provider for a particular test, you must pass the name of the Suite Provider to the Test attribute.

+ +
class SuiteWithProviders
+{
+    <<SuiteProvider('One')>>
+    public static function() : this
+    {
+        $someDependency = new TestDoubleOne();
+        return new static($someDependency);
+    }
+
+    <<SuiteProvider('Two')>>
+    public static function() : this
+    {
+        $someDependency = new TestDoubleTwo();
+        return new static($someDependency);
+    }
+
+    <<Test('One')>>
+    public function testOne(Assert $assert) : void
+    {
+        // Do some assertions using TestDoubleOne
+    }
+
+    <<Test('Two')>>
+    public function testTwo(Assert $assert) : void
+    {
+        // Do some assertions using TestDoubleTwo
+    }
+}
+ +

+Assertions

+ +

All test methods must accept exactly one parameter of type HackPack\HackUnit\Contract\Assert which should be used to make testable assertions. This object is used to build assertions that will be checked and reported by HackUnit.

+ +

In all examples below, $assert contains an instance of HackPack\HackUnit\Contract\Assert.

+ +

+Bool Assertions

+ +

To make assertions about bool type variables, call $assert->bool($myBool)->is($expected).

+ +

+Numeric Assertions

+ +

To make assertions about int and float type variables, call $assert->int($myInt) and $assert->float($myFloat) respectively. The resulting object contains the following methods to actually perform the appropriate assertion.

+ +
    +
  • +$assert->int($myInt)->eq($expected); : Assert that $myInt is identical to $expected +
  • +
  • +$assert->int($myInt)->gt($expected); : Assert that $myInt is greater than $expected +
  • +
  • +$assert->int($myInt)->lt($expected); : Assert that $myInt is less than $expected +
  • +
  • +$assert->int($myInt)->gte($expected); : Assert that $myInt is greater than or equal to $expected +
  • +
  • +$assert->int($myInt)->lte($expected); : Assert that $myInt is less than or equal to $expected +
  • +
+ +

All of the above may be modified with a call to not() before the assertion to negate the meaning of the assertion. For example:

+ +
 $assert->int($myInt)->not()->eq($expected);
+
+ +

Note: This library only allows assertions to compare identical numeric types. $assert->int(1)->eq(1.0); produces a type error.

+ +

+String Assertions

+ +

To make assertions about string type variables, call $assert->string($myString). The resulting object contains the following methods to actually perform the appropriate assertion.

+ +
    +
  • +$assert->string($myString)->is($expected) : Assert that $myString === $expected +
  • +
  • +$assert->string($myString)->hasLength($int) : Assert that the string has a length of $int +
  • +
  • +$assert->string($myString)->matches($pattern) : Assert that the regular expression contained in $pattern matches the string
  • +
  • +$assert->string($myString)->contains($subString) : Assert that $subString is a substring of $myString +
  • +
  • +$assert->string($myString)->containedBy($superString) : Assert that $myString is a substring of $superString +
  • +
+ +

All of the above assertions may be negated by calling not() before making the assertion. For example:

+ +
 $assert->string($myString)->not()->containedBy($superString);
+
+ +

+Collection Assertions

+ +

To make assertions about collections and arrays, call $assert->container($context). The resulting object contains the following methods to perform assertions.

+ +
    +
  • +$assert->container($context)->isEmpty(); : Assert that the context has no elements
  • +
  • +$assert->container($context)->contains($value); : Assert that the context contains the value given
  • +
  • +$assert->container($context)->containsAny($list); : Assert that the context contains at least one element in the list provided
  • +
  • +$assert->container($context)->containsAll($list); : Assert that the context contains all elements in the list provided
  • +
  • +$assert->container($context)->containsOnly($list); : Assert that the context contains all elements in the list provided and no more
  • +
+ +

All of the contains* assertions above accept an optional second parameter which must be a callable. The callable will be used to compare the elements in the context with the element(s) provided. If the elements passed to the callable should be treated as equivalent, the callable should return true, otherwise it should return false.

+ +

+Keyed Collections

+ +

If the keys of the container are important for the assertions, you should use $assert->keyedContainer($context). The resulting object contains the following methods to perform assertions.

+ +
    +
  • +$assert->container($context)->contains($key, $value); : Assert that the value contained in the context at the key provided matches the value provided
  • +
  • +$assert->container($context)->containsKey($key); : Assert that the context contains the provided key
  • +
  • +$assert->container($context)->containsAny($list); : Assert that the context contains at least one element in the list provided where both the key and value must be considered equivalent
  • +
  • +$assert->container($context)->containsAll($list); : Assert that the context contains all elements in the list provided where both the key and value must be considered equivalent
  • +
  • +$assert->container($context)->containsOnly($list); : Assert that the context contains all elements in the list provided and no more where both the key and value must be considered equivalent
  • +
+ +

All of the assertions above accept an optional second (or third in the case of contains) parameter which must be a callable. The callable will be used to compare the values of the elements in the context with the element(s) provided. If the values passed to the callable should be treated as equivalent, the callable should return true, otherwise it should return false.

+ +

+Mixed Assertions

+ +

To make generic assertions about a variable of any type, call $assert->mixed($context). The resulting object contains the following methods to actually perform the appropriate assertion.

+ +
    +
  • +$assert->mixed($context)->isNull(); : Assert that $context === null +
  • +
  • +$assert->mixed($context)->isBool(); : Assert that $context is of type bool +
  • +
  • +$assert->mixed($context)->isInt(); : Assert that $context is of type int +
  • +
  • +$assert->mixed($context)->isFloat(); : Assert that $context is of type float +
  • +
  • +$assert->mixed($context)->isString(); : Assert that $context is of type string +
  • +
  • +$assert->mixed($context)->isArray(); : Assert that $context is of type array +
  • +
  • +$assert->mixed($context)->isObject(); : Assert that $context is of type object +
  • +
  • +$assert->mixed($context)->isTypeOf($className) : Assert that $context instanceof $className +
  • +
  • +$assert->mixed($context)->looselyEquals($expected) : Assert that $context == $expected note the loose comparison +
  • +
  • +$assert->mixed($context)->identicalTo($expected) : Assert that $context === $expected note the strict comparison +
  • +
+ +

+Skipping Tests

+ +

There are two ways to skip execution of a particular test method:

+ +
    +
  1. Add the attribute <<Skip>> to the test method or the test suite. If the <<Skip>> attribute is added to the suite, all tests in that class will be skipped.
  2. +
  3. Invoke the skip() method of the Assert object passed to your test method.
  4. +
+ +
use \HackPack\HackUnit\Contract\Assert;
+
+<<Skip>>
+class SkippedSuite
+{
+    // All methods here would be skipped
+}
+
+class MySuite
+{
+    <<Test, Skip>>
+    public function skippedTest(Assertion $assert) : void
+    {
+        // This will not be run and the test will be marked skip in the report.
+    }
+
+    <<Test>>
+    public function skipFromMiddleOfTest(Assert $assert) : void
+    {
+        // This will be run
+        $assert->skip();
+        // This will not be run and the test will be marked skip in the report.
+    }
+}
+ +

+Data Providers

+ +

You may mark some methods as providing a list of data that should be iterated and passed to a test method. To do this, mark the data providing method with the <<DataProvider('name')>> attribute. You must name your data provider as shown to allow HackUnit to know which data provider should be used for each test that consumes data.

+ +
class TestThatUsesData {
+
+  <<DataProvider('csv values')>>
+  public static function loadCsvValues(): AsyncIterator<array<string>>
+  {
+    $asynCsvLoader = new AsyncCsvLoader('/path/to/data.csv');
+    foreach($asyncCsvLoader await as $line) {
+      yield $line;
+    }
+  }
+
+  <<Test, Data('csv values')>>
+  public function testCsvValues(Assert $assert, array<string> $line): void
+  {
+    // Do assertions using the data from the csv file.
+  }
+
+  <<DataProvider('simple count')>>
+  public static function count(): Traversable<int>
+  {
+    return Vector{1, 2, 3, 4, 5};
+  }
+
+  <<Test, Data('simple count')>>
+  public function countingTest(Assert $assert, int $count): void
+  {
+    // This test will be run five times, once for each of the values in the vector above.
+  }
+}
+ +

The example above demonstrates defining both async and non-async data providers. Special note should be taken of the return values.

+ +
    +
  • Async data providers MUST return AsyncIterator<dataType>.
  • +
  • Non-async data providers MUST return Traversable<dataType>.
  • +
  • The consumer of a data provider MUST accept exactly dataType as the second parameter.
  • +
+ +

In the example above, a MalformedSuite error would occur if the csv consumer function had the signature public function testCsvValues(Assert $assert, Traversable<string>): void. Even though an array<string> is a type of Traversable<string>, the HackUnit parser compares the string representation of the types to ensure invalid data is never passed to the test methods.

+ +

+How HackUnit loads tests

+ +

All files inside the base path(s) specified from the command line will be scanned for class definitions using Fred Emmott's Definition Finder library. Those files will then be loaded and reflection is used to determine which classes are test suites, and which methods perform each task in the suite.

+ +

Thanks Fred!

+ +

+Strict mode all the files!

+ +

Well... not quite.

+ +

Top level code must use // partial mode, so the bin/hackunit file is not in strict mode. The rest of the project is, with one exception. Test suite files must be dynamically loaded after being scanned for test suites. The only way I can see to perform this dynamic inclusion is to use include_once inside of a class method, which is disallowed in strict mode. This one exception is marked with a /* HH_FIXME */ comment, which disables the type checker for that one line.

+ +

+Running HackUnit's tests

+ +

HackUnit is tested with HackUnit. From the project directory run:

+ +
hhvm /path/to/composer.phar test
+
+
+ +
+ + + + diff --git a/javascripts/scale.fix.js b/javascripts/scale.fix.js new file mode 100644 index 0000000..08716c0 --- /dev/null +++ b/javascripts/scale.fix.js @@ -0,0 +1,20 @@ +fixScale = function(doc) { + + var addEvent = 'addEventListener', + type = 'gesturestart', + qsa = 'querySelectorAll', + scales = [1, 1], + meta = qsa in doc ? doc[qsa]('meta[name=viewport]') : []; + + function fix() { + meta.content = 'width=device-width,minimum-scale=' + scales[0] + ',maximum-scale=' + scales[1]; + doc.removeEventListener(type, fix, true); + } + + if ((meta = meta[meta.length - 1]) && addEvent in doc) { + fix(); + scales = [.25, 1.6]; + doc[addEvent](type, fix, true); + } + +}; \ No newline at end of file diff --git a/params.json b/params.json new file mode 100644 index 0000000..f4f6884 --- /dev/null +++ b/params.json @@ -0,0 +1,6 @@ +{ + "name": "Hackunit", + "tagline": "xUnit testing framework written in hacklang", + "body": "HackUnit\r\n========\r\n\r\nTesting framework written in and for [Hack.](http://hacklang.org)\r\n\r\n[![Gitter](https://badges.gitter.im/HackPack/HackUnit.svg)](https://gitter.im/HackPack/HackUnit?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)\r\n\r\n### But Why?!\r\nThere are already many testing frameworks available, such as [PHPUnit](https://phpunit.de/) and [behat.](http://behat.org) Why should you use this one?\r\n\r\n*Because you like Hack specific features!*\r\n\r\nWith HackUnit, you can easily run your tests using cooperative async with the built in `async` keyword.\r\n\r\nWith HackUnit, you can easily iterate through your test data in an async way using the `yield` keyword.\r\n\r\nWith HackUnit, you indicate test methods using [annotations.](http://docs.hhvm.com/manual/en/hack.attributes.php)\r\n\r\nThe original goal of HackUnit was to write a testing framework using Hack's strict mode. The project will stay consistent with this goal as more features are added.\r\n\r\nInstall\r\n-------\r\n\r\nInstall HackUnit using [Composer](https://getcomposer.org):\r\n\r\n```bash\r\ncomposer require --dev hackpack/hackunit\r\n```\r\n\r\nUsage\r\n-----\r\n\r\nHackUnit can be run from the command line using the included executable script `bin/hackunit`. By default, this will be symlinked in your `vendor/bin` directory.\r\n\r\nThus, the most common way to invoke HackUnit is:\r\n```bash\r\nvendor/bin/hackunit path1 [path2] ...\r\n```\r\nwhere `path1`, `path2`, etc... are each base paths/files to scan for test suites. If any specified path is a directory, the directory will be recursively scanned.\r\n\r\nSome command line options exist to alter the behavior of HackUnit:\r\n\r\n* `--exclude=\"path/to/exclude\"` : Do not scan the file or any file under the path provided. This option may be given multiple times to exclude multiple paths/files.\r\n\r\nTest Suites\r\n-----------\r\nTo define a test suite, create a class and [annotate](http://docs.hhvm.com/manual/en/hack.attributes.php) the appropriate methods.\r\n\r\nYou may inspect HackUnit’s test files for concrete examples.\r\n\r\n### Tests\r\n\r\nIndividual test methods are defined using the\r\n`<>` [attribute](http://docs.hhvm.com/manual/en/hack.attributes.php).\r\nExecution order of the tests is not guaranteed.\r\n\r\nEach test method MUST accept exactly 1 parameter, with the type hint of `HackPack\\HackUnit\\Contract\\Assert`.\r\nIf you mark a method as a test and the signature does not match, the test will not be run.\r\n\r\nTest methods may be instance methods, or they may be class (static) methods.\r\n\r\n```php\r\nnamespace My\\Namespace\\Test;\r\n\r\nuse HackPack\\HackUnit\\Contract\\Assert;\r\n\r\nclass MySuite\r\n{\r\n <>\r\n public function testSomething(Assert $assert) : void\r\n {\r\n // Do some testing here!\r\n $assert->int(2)->not()->eq(3);\r\n $assert\r\n ->whenCalled(() ==> {throw new \\Exception(‘bad error)})\r\n ->willThrowClassWithMessage(\\Exception::class, ‘bad error’)\r\n ;\r\n }\r\n}\r\n```\r\n\r\n### Async\r\n\r\nRunning your tests async is as easy as adding the async keyword to your test method.\r\n\r\n```php\r\nnamespace My\\Namespace\\Test;\r\n\r\nuse HackPack\\HackUnit\\Contract\\Assert;\r\n\r\nclass MyAsyncSuite\r\n{\r\n <>\r\n public async function testSomething(Assert $assert) : Awaitable\r\n {\r\n // Make some async DB calls here as part of your test!\r\n $user = await get_user();\r\n\r\n // Or maybe an async curl call\r\n $result = await get_external_user($user->id, 'api password');\r\n\r\n $assert->string($result['user_name'])->is('expected username');\r\n }\r\n}\r\n```\r\n\r\nAll such `async` tests are run using cooperative multitasking (see the [async documentation](http://docs.hhvm.com/hack/async/introduction)), allowing your entire test suite to run faster if your tests perform real I/O operations (DB calls, network calls, etc...).\r\n\r\n### Setup\r\n\r\nYou may have HackUnit run some methods before each individual test method is run and/or before any test method is run for the suite. To do so, mark the appropriate method with the `<>` [attribute](http://docs.hhvm.com/manual/en/hack.attributes.php). Multiple setup methods may be declared, but the execution order is not guaranteed.\r\n\r\nEach setup method (both suite and test) MUST require exactly 0 parameters. If you mark a method as setup and it requires a parameter, it will not be executed and a parse error will be shown in the report.\r\n\r\n```php\r\nclass MySuite\r\n{\r\n <>\r\n public function setUpSuite() : void\r\n {\r\n // Suite level Setup methods must be class (static) methods\r\n // Perform tasks before any tests in this suite are run\r\n }\r\n\r\n <>\r\n public function setUpTest() : void\r\n {\r\n // Perform tasks just before each test in this suite is run\r\n }\r\n\r\n <>\r\n public function setUpTestAgain() : void\r\n {\r\n // Multiple set up methods may be defined\r\n // If there are no parameters to the setup attribute, the method is treated like a test setup\r\n }\r\n}\r\n```\r\n\r\nSuite setup methods are run once, before any of the test methods in the class are run.\r\n\r\nTest setup methods are run just before each test method is run (and thus are potentially run multiple times).\r\n\r\n### Teardown\r\nYou may have HackUnit run some methods after each individual test method is run and/or after all test methods are run for the suite. To do so, mark the appropriate method with the `<>` [attribute](http://docs.hhvm.com/manual/en/hack.attributes.php). Multiple teardown methods may be declared, but the execution order is not guaranteed.\r\n\r\nEach teardown method (both suite and test) MUST require exactly 0 parameters. If you mark a method as teardown and it requires a parameter, it will not be executed and a parse error will be shown in the report.\r\n\r\n```php\r\nclass MySuite\r\n{\r\n <>\r\n public static function cleanUpAfterSuite() : void\r\n {\r\n // Suite level TearDown methods must be class (static) methods\r\n // Perform tasks after all tests in this suite are run\r\n }\r\n\r\n <>\r\n public function cleanUpAfterTest() : void\r\n {\r\n // Perform tasks just after each test in this suite is run\r\n }\r\n\r\n <>\r\n public function cleanUpMoarStuff() : void\r\n {\r\n // This is also a ‘test’ teardown method\r\n }\r\n}\r\n```\r\n\r\nSuite tear down methods are run once, after all of the test methods in the class are run.\r\n\r\nTest tear down methods are run just after each test method is run (and thus are potentially run multiple times).\r\n\r\n### Suite Providers\r\nYour test suite may require parameters to be passed to the constructor. To tell HackUnit how to construct your test suite, you must define at least one Suite Provider. A Suite Provider is marked with the `<>` attribute.\r\n\r\nYou may define multiple Suite Providers for a single test suite. To do so, you must label each one by passing in one string parameter to the attribute (i.e., `<>`). There are no restrictions on the name of a provider except that each provider name must be unique.\r\n\r\nTo use a particular Suite Provider for a particular test, you must pass the name of the Suite Provider to the Test attribute.\r\n\r\n```php\r\nclass SuiteWithProviders\r\n{\r\n <>\r\n public static function() : this\r\n {\r\n $someDependency = new TestDoubleOne();\r\n return new static($someDependency);\r\n }\r\n\r\n <>\r\n public static function() : this\r\n {\r\n $someDependency = new TestDoubleTwo();\r\n return new static($someDependency);\r\n }\r\n\r\n <>\r\n public function testOne(Assert $assert) : void\r\n {\r\n // Do some assertions using TestDoubleOne\r\n }\r\n\r\n <>\r\n public function testTwo(Assert $assert) : void\r\n {\r\n // Do some assertions using TestDoubleTwo\r\n }\r\n}\r\n```\r\n\r\nAssertions\r\n----------\r\n\r\nAll test methods must accept exactly one parameter of type `HackPack\\HackUnit\\Contract\\Assert` which should be used to make testable assertions. This object is used to build assertions that will be checked and reported by HackUnit.\r\n\r\nIn all examples below, `$assert` contains an instance of `HackPack\\HackUnit\\Contract\\Assert`.\r\n\r\n### Bool Assertions\r\n\r\nTo make assertions about `bool` type variables, call `$assert->bool($myBool)->is($expected)`.\r\n\r\n### Numeric Assertions\r\n\r\nTo make assertions about `int` and `float` type variables, call `$assert->int($myInt)` and `$assert->float($myFloat)` respectively. The resulting object contains the following methods to actually perform the appropriate assertion.\r\n\r\n* `$assert->int($myInt)->eq($expected);` : Assert that `$myInt` is identical to `$expected`\r\n* `$assert->int($myInt)->gt($expected);` : Assert that `$myInt` is greater than `$expected`\r\n* `$assert->int($myInt)->lt($expected);` : Assert that `$myInt` is less than `$expected`\r\n* `$assert->int($myInt)->gte($expected);` : Assert that `$myInt` is greater than or equal to `$expected`\r\n* `$assert->int($myInt)->lte($expected);` : Assert that `$myInt` is less than or equal to `$expected`\r\n\r\nAll of the above may be modified with a call to `not()` before the assertion to negate the meaning of the assertion. For example:\r\n\r\n```\r\n $assert->int($myInt)->not()->eq($expected);\r\n```\r\n\r\n*Note*: This library only allows assertions to compare identical numeric types. `$assert->int(1)->eq(1.0);` produces a type error.\r\n\r\n### String Assertions\r\n\r\nTo make assertions about `string` type variables, call `$assert->string($myString)`. The resulting object contains the following methods to actually perform the appropriate assertion.\r\n\r\n* `$assert->string($myString)->is($expected)` : Assert that `$myString === $expected`\r\n* `$assert->string($myString)->hasLength($int)` : Assert that the string has a length of `$int`\r\n* `$assert->string($myString)->matches($pattern)` : Assert that the regular expression contained in `$pattern` matches the string\r\n* `$assert->string($myString)->contains($subString)` : Assert that `$subString` is a substring of `$myString`\r\n* `$assert->string($myString)->containedBy($superString)` : Assert that `$myString` is a substring of `$superString`\r\n\r\nAll of the above assertions may be negated by calling `not()` before making the assertion. For example:\r\n\r\n```\r\n $assert->string($myString)->not()->containedBy($superString);\r\n```\r\n\r\n### Collection Assertions\r\n\r\nTo make assertions about collections and arrays, call `$assert->container($context)`. The resulting object contains the following methods to perform assertions.\r\n\r\n* `$assert->container($context)->isEmpty();` : Assert that the context has no elements\r\n* `$assert->container($context)->contains($value);` : Assert that the context contains the value given\r\n* `$assert->container($context)->containsAny($list);` : Assert that the context contains at least one element in the list provided\r\n* `$assert->container($context)->containsAll($list);` : Assert that the context contains all elements in the list provided\r\n* `$assert->container($context)->containsOnly($list);` : Assert that the context contains all elements in the list provided and no more\r\n\r\nAll of the `contains*` assertions above accept an optional second parameter which must be a callable. The callable will be used to compare the elements in the context with the element(s) provided. If the elements passed to the callable should be treated as equivalent, the callable should return `true`, otherwise it should return `false`.\r\n\r\n#### Keyed Collections\r\n\r\nIf the keys of the container are important for the assertions, you should use `$assert->keyedContainer($context)`. The resulting object contains the following methods to perform assertions.\r\n\r\n* `$assert->container($context)->contains($key, $value);` : Assert that the value contained in the context at the key provided matches the value provided\r\n* `$assert->container($context)->containsKey($key);` : Assert that the context contains the provided key\r\n* `$assert->container($context)->containsAny($list);` : Assert that the context contains at least one element in the list provided where both the key and value must be considered equivalent\r\n* `$assert->container($context)->containsAll($list);` : Assert that the context contains all elements in the list provided where both the key and value must be considered equivalent\r\n* `$assert->container($context)->containsOnly($list);` : Assert that the context contains all elements in the list provided and no more where both the key and value must be considered equivalent\r\n\r\nAll of the assertions above accept an optional second (or third in the case of `contains`) parameter which must be a callable. The callable will be used to compare the values of the elements in the context with the element(s) provided. If the values passed to the callable should be treated as equivalent, the callable should return `true`, otherwise it should return `false`.\r\n\r\n### Mixed Assertions\r\n\r\nTo make generic assertions about a variable of any type, call `$assert->mixed($context)`. The resulting object contains the following methods to actually perform the appropriate assertion.\r\n\r\n* `$assert->mixed($context)->isNull();` : Assert that `$context === null`\r\n* `$assert->mixed($context)->isBool();` : Assert that `$context` is of type `bool`\r\n* `$assert->mixed($context)->isInt();` : Assert that `$context` is of type `int`\r\n* `$assert->mixed($context)->isFloat();` : Assert that `$context` is of type `float`\r\n* `$assert->mixed($context)->isString();` : Assert that `$context` is of type `string`\r\n* `$assert->mixed($context)->isArray();` : Assert that `$context` is of type `array`\r\n* `$assert->mixed($context)->isObject();` : Assert that `$context` is of type `object`\r\n* `$assert->mixed($context)->isTypeOf($className)` : Assert that `$context instanceof $className`\r\n* `$assert->mixed($context)->looselyEquals($expected)` : Assert that `$context == $expected` *note the loose comparison*\r\n* `$assert->mixed($context)->identicalTo($expected)` : Assert that `$context === $expected` *note the strict comparison*\r\n\r\nSkipping Tests\r\n-------------\r\nThere are two ways to skip execution of a particular test method:\r\n\r\n1. Add the attribute `<>` to the test method or the test suite. If the `<>` attribute is added to the suite, all tests in that class will be skipped.\r\n1. Invoke the `skip()` method of the `Assert` object passed to your test method.\r\n\r\n```php\r\nuse \\HackPack\\HackUnit\\Contract\\Assert;\r\n\r\n<>\r\nclass SkippedSuite\r\n{\r\n // All methods here would be skipped\r\n}\r\n\r\nclass MySuite\r\n{\r\n <>\r\n public function skippedTest(Assertion $assert) : void\r\n {\r\n // This will not be run and the test will be marked skip in the report.\r\n }\r\n\r\n <>\r\n public function skipFromMiddleOfTest(Assert $assert) : void\r\n {\r\n // This will be run\r\n $assert->skip();\r\n // This will not be run and the test will be marked skip in the report.\r\n }\r\n}\r\n```\r\n\r\nData Providers\r\n--------------\r\n\r\nYou may mark some methods as providing a list of data that should be iterated and passed to a test method. To do this, mark the data providing method with the `<>` attribute. You must name your data provider as shown to allow HackUnit to know which data provider should be used for each test that consumes data.\r\n\r\n```php\r\nclass TestThatUsesData {\r\n\r\n <>\r\n public static function loadCsvValues(): AsyncIterator>\r\n {\r\n $asynCsvLoader = new AsyncCsvLoader('/path/to/data.csv');\r\n foreach($asyncCsvLoader await as $line) {\r\n yield $line;\r\n }\r\n }\r\n\r\n <>\r\n public function testCsvValues(Assert $assert, array $line): void\r\n {\r\n // Do assertions using the data from the csv file.\r\n }\r\n\r\n <>\r\n public static function count(): Traversable\r\n {\r\n return Vector{1, 2, 3, 4, 5};\r\n }\r\n\r\n <>\r\n public function countingTest(Assert $assert, int $count): void\r\n {\r\n // This test will be run five times, once for each of the values in the vector above.\r\n }\r\n}\r\n```\r\n\r\nThe example above demonstrates defining both async and non-async data providers. Special note should be taken of the return values.\r\n\r\n* Async data providers _MUST_ return `AsyncIterator`.\r\n* Non-async data providers _MUST_ return `Traversable`.\r\n* The consumer of a data provider _MUST_ accept exactly `dataType` as the second parameter.\r\n\r\nIn the example above, a `MalformedSuite` error would occur if the csv consumer function had the signature `public function testCsvValues(Assert $assert, Traversable): void`. Even though an `array` is a type of `Traversable`, the HackUnit parser compares the string representation of the types to ensure invalid data is never passed to the test methods.\r\n\r\nHow HackUnit loads tests\r\n------------------------\r\nAll files inside the base path(s) specified from the command line will be scanned for class definitions using Fred Emmott's [Definition Finder](https://github.com/fredemmott/definition-finder) library. Those files will then be loaded and reflection is used to determine which classes are test suites, and which methods perform each task in the suite.\r\n\r\nThanks [Fred!](https://github.com/fredemmott)\r\n\r\nStrict mode all the files!\r\n--------------------------\r\n\r\nWell... not quite.\r\n\r\nTop level code must use `// partial` mode, so the `bin/hackunit` file is not in strict mode. The rest of the project is, with one exception. Test suite files must be dynamically loaded after being scanned for test suites. The only way I can see to perform this dynamic inclusion is to use `include_once` inside of a class method, which is disallowed in strict mode. This one exception is marked with a `/* HH_FIXME */` comment, which disables the type checker for that one line.\r\n\r\nRunning HackUnit's tests\r\n------------------------\r\nHackUnit is tested with HackUnit. From the project directory run:\r\n\r\n```\r\nhhvm /path/to/composer.phar test\r\n```\r\n", + "note": "Don't delete this file! It's used internally to help with page regeneration." +} \ No newline at end of file diff --git a/src/Assert.php b/src/Assert.php deleted file mode 100644 index d75c4ae..0000000 --- a/src/Assert.php +++ /dev/null @@ -1,110 +0,0 @@ - $failureListeners, - Vector $skipListeners, - Vector $successListeners, - ): this { - return new static($failureListeners, $skipListeners, $successListeners); - } - - public function __construct( - private Vector $failureListeners, - private Vector $skipListeners, - private Vector $successListeners, - ) {} - - public function bool(bool $context): Contract\Assertion\BoolAssertion { - return new Assertion\BoolAssertion( - $context, - $this->failureListeners, - $this->successListeners, - ); - } - - public function int(int $context): Contract\Assertion\NumericAssertion { - return new Assertion\NumericAssertion( - $context, - $this->failureListeners, - $this->successListeners, - ); - } - - public function float( - float $context, - ): Contract\Assertion\NumericAssertion { - return new Assertion\NumericAssertion( - $context, - $this->failureListeners, - $this->successListeners, - ); - } - - public function string(string $context): Contract\Assertion\StringAssertion { - return new Assertion\StringAssertion( - $context, - $this->failureListeners, - $this->successListeners, - ); - } - - public function whenCalled( - (function(): void) $context, - ): Contract\Assertion\CallableAssertion { - return new Assertion\CallableAssertion( - $context, - $this->failureListeners, - $this->successListeners, - ); - } - - public function mixed(mixed $context): Contract\Assertion\MixedAssertion { - return new Assertion\MixedAssertion( - $context, - $this->failureListeners, - $this->successListeners, - ); - } - - public function container( - Container $context, - ): Contract\Assertion\ContainerAssertion { - return new Assertion\ContainerAssertion( - $context, - $this->failureListeners, - $this->successListeners, - ); - } - - public function keyedContainer( - KeyedContainer $context, - ): Contract\Assertion\KeyedContainerAssertion { - return new Assertion\KeyedContainerAssertion( - $context, - $this->failureListeners, - $this->successListeners, - ); - } - - public function skip( - string $reason, - ?Util\TraceItem $traceItem = null, - ): void { - if ($traceItem === null) { - $stack = Util\Trace::generate(); - $traceItem = shape( - 'file' => $stack[0]['file'], - 'line' => $stack[0]['line'], - 'function' => $stack[1]['function'], - 'class' => $stack[1]['class'], - ); - } - $skip = new Event\Skip($reason, $traceItem, Util\Trace::findTestMethod()); - foreach ($this->skipListeners as $l) { - $l($skip); - } - } -} diff --git a/src/Assertion/BoolAssertion.php b/src/Assertion/BoolAssertion.php deleted file mode 100644 index 6dd9394..0000000 --- a/src/Assertion/BoolAssertion.php +++ /dev/null @@ -1,41 +0,0 @@ - $failureListeners, - Vector $successListeners, - ) { - $this->setFailureListeners($failureListeners); - $this->setSuccessListeners($successListeners); - } - - public function is(bool $expected): void { - if ($this->context === $expected) { - $this->emitSuccess(); - return; - } - $this->emitFailure( - Failure::fromCallStack( - 'Expected '. - ($expected ? 'true' : 'false'). - ', value was '. - ($expected ? 'false' : 'true'). - '.', - ), - ); - } -} diff --git a/src/Assertion/CallableAssertion.php b/src/Assertion/CallableAssertion.php deleted file mode 100644 index aaefca8..0000000 --- a/src/Assertion/CallableAssertion.php +++ /dev/null @@ -1,200 +0,0 @@ - $failureListeners, - Vector $successListeners, - ) { - $this->setFailureListeners($failureListeners); - $this->setSuccessListeners($successListeners); - } - - public function willThrow(): void { - try { - $c = $this->context; - $c(); - } catch (\Exception $e) { - $this->emitSuccess(); - return; - } - $this->missingException(); - } - - public function willThrowClass(string $className): void { - try { - $c = $this->context; - $c(); - } catch (\Exception $e) { - if (is_a($e, $className)) { - $this->emitSuccess(); - return; - } - $this->wrongClass($className, get_class($e)); - return; - } - $this->missingException(); - } - - public function willThrowMessage(string $message): void { - try { - $c = $this->context; - $c(); - } catch (\Exception $e) { - if ($e->getMessage() === $message) { - $this->emitSuccess(); - return; - } - $this->wrongMessage($message, $e->getMessage()); - return; - } - $this->missingException(); - } - - public function willThrowMessageContaining(string $needle): void { - try { - $c = $this->context; - $c(); - } catch (\Exception $e) { - if (strpos($e->getMessage(), $needle) !== false) { - $this->emitSuccess(); - return; - } - $this->messageDoesNotContain($needle, $e->getMessage()); - return; - } - $this->missingException(); - } - - public function willThrowClassWithMessage( - string $className, - string $message, - ): void { - try { - $c = $this->context; - $c(); - } catch (\Exception $e) { - if ($e->getMessage() !== $message) { - $this->wrongMessage($message, $e->getMessage()); - return; - } - if (!is_a($e, $className)) { - $this->wrongClass($className, get_class($e)); - return; - } - $this->emitSuccess(); - return; - } - $this->missingException(); - } - - public function willThrowClassWithMessageContaining( - string $className, - string $needle, - ): void { - try { - $c = $this->context; - $c(); - } catch (\Exception $e) { - if (strpos($e->getMessage(), $needle) === false) { - $this->messageDoesNotContain($needle, $e->getMessage()); - return; - } - if (!is_a($e, $className)) { - $this->wrongClass($className, get_class($e)); - return; - } - $this->emitSuccess(); - return; - } - $this->missingException(); - } - - public function willNotThrow(): void { - try { - $c = $this->context; - $c(); - } catch (\Exception $e) { - $this->emitFailure( - Failure::fromCallStack( - implode( - PHP_EOL, - [ - 'Unexpected exception thrown.', - get_class($e), - $e->getMessage(), - ], - ), - ), - ); - return; - } - $this->emitSuccess(); - } - - private function missingException(): void { - $this->emitFailure( - Failure::fromCallStack('Expected exception to be thrown.'), - ); - } - - private function wrongClass(string $expected, string $actual): void { - $this->emitFailure( - Failure::fromCallStack( - 'Expected exception of type '. - $expected. - ' but '. - $actual. - ' was thrown.', - ), - ); - } - - private function wrongMessage(string $expected, string $actual): void { - $this->emitFailure( - Failure::fromCallStack( - implode( - PHP_EOL, - [ - 'Expected exception message:', - $expected, - 'Actual message:', - $actual, - ], - ), - ), - ); - } - - private function messageDoesNotContain( - string $expected, - string $actual, - ): void { - $this->emitFailure( - Failure::fromCallStack( - implode( - PHP_EOL, - [ - 'Expected exception message to contain:', - $expected, - 'Actual message:', - $actual, - ], - ), - ), - ); - } -} diff --git a/src/Assertion/ContainerAssertion.php b/src/Assertion/ContainerAssertion.php deleted file mode 100644 index 042f979..0000000 --- a/src/Assertion/ContainerAssertion.php +++ /dev/null @@ -1,250 +0,0 @@ - - implements \HackPack\HackUnit\Contract\Assertion\ContainerAssertion { - - use FailureEmitter; - use SuccessEmitter; - - private bool $negate = false; - private \ConstVector $context; - - public function __construct( - Container $context, - Vector $failureListeners, - Vector $successListeners, - ) { - $this->context = new Vector($context); - $this->setFailureListeners($failureListeners); - $this->setSuccessListeners($successListeners); - } - - public function not(): this { - $this->negate = true; - return $this; - } - - public function contains( - Tval $expected, - ?(function(Tval, Tval): bool) $comparitor = null, - ): void { - - if ($this->context->isEmpty()) { - if ($this->negate) { - $this->emitSuccess(); - return; - } - $this->emitFailure(Failure::fromCallStack('The Container is empty.')); - return; - } - - if ($comparitor === null) { - $comparitor = self::identityComparitor(); - } - - foreach ($this->context as $value) { - if ($comparitor($expected, $value)) { - - if ($this->negate) { - $this->emitFailure( - Failure::fromCallStack( - 'Expected Container to not contain '. - var_export($expected, true), - ), - ); - return; - } - - $this->emitSuccess(); - return; - } - } - - if ($this->negate) { - $this->emitSuccess(); - return; - } - - $this->emitFailure( - Failure::fromCallStack( - 'Expected Container to contain '.var_export($expected, true), - ), - ); - } - - public function containsAll( - Container $expected, - ?(function(Tval, Tval): bool) $comparitor = null, - ): void { - if ($this->context->isEmpty()) { - if ($this->negate) { - $this->emitSuccess(); - return; - } - $this->emitFailure(Failure::fromCallStack('The Container is empty.')); - return; - } - - if ($comparitor === null) { - $comparitor = self::identityComparitor(); - } - - foreach ($expected as $other) { - - $otherIsContained = array_reduce( - $this->context->toArray(), - ($result, $contextVal) ==> $result || - $comparitor($contextVal, $other), - false, - ); - - if ($otherIsContained) { - continue; - } - - if ($this->negate) { - $this->emitSuccess(); - return; - } - $this->emitFailure( - Failure::fromCallStack( - 'Container expected to contain '.var_export($other, true), - ), - ); - return; - } - - if ($this->negate) { - $this->emitFailure( - Failure::fromCallStack( - 'Container expected to not contain all of the given list.', - ), - ); - return; - } - $this->emitSuccess(); - - } - - public function containsAny( - Container $expected, - ?(function(Tval, Tval): bool) $comparitor = null, - ): void { - if ($this->context->isEmpty()) { - if ($this->negate) { - $this->emitSuccess(); - return; - } - $this->emitFailure(Failure::fromCallStack('The Container is empty.')); - return; - } - - if ($comparitor === null) { - $comparitor = self::identityComparitor(); - } - - foreach ($expected as $otherValue) { - - $otherIsContained = array_reduce( - $this->context->toArray(), - ($result, $contextVal) ==> $result || - $comparitor($contextVal, $otherValue), - false, - ); - - if ($otherIsContained) { - if ($this->negate) { - $this->emitFailure( - Failure::fromCallStack( - 'Container expected to not contain '. - var_export($otherValue, true), - ), - ); - return; - } - $this->emitSuccess(); - return; - } - } - - if ($this->negate) { - $this->emitSuccess(); - return; - } - - $this->emitFailure( - Failure::fromCallStack( - 'Container expected to contain at least one item from the list.', - ), - ); - } - - public function containsOnly( - Container $expected, - ?(function(Tval, Tval): bool) $comparitor = null, - ): void { - $expected = new Vector($expected); - - if ($this->context->count() !== $expected->count()) { - if ($this->negate) { - $this->emitSuccess(); - return; - } - $message = - $this->context->count() > $expected->count() - ? 'Container contains more elements than expected.' - : 'Container contains fewer elements than expected.'; - $this->emitFailure(Failure::fromCallStack($message)); - return; - } - - if ($this->context->isEmpty()) { - if ($this->negate) { - $this->emitFailure( - Failure::fromCallStack('Traverseable expected to not be empty.'), - ); - return; - } - $this->emitSuccess(); - return; - } - - $this->containsAll($expected, $comparitor); - - } - - public function isEmpty(): void { - if ($this->context->isEmpty()) { - if ($this->negate) { - $this->emitFailure( - Failure::fromCallStack('Container expected not to be empty.'), - ); - return; - } - $this->emitSuccess(); - return; - } - - if ($this->negate) { - $this->emitSuccess(); - return; - } - $this->emitFailure( - Failure::fromCallStack('Container expected to be empty.'), - ); - } - - <<__Memoize>> - private static function identityComparitor(): (function(T, T): bool) { - return ($a, $b) ==> $a === $b; - } -} diff --git a/src/Assertion/KeyedContainerAssertion.php b/src/Assertion/KeyedContainerAssertion.php deleted file mode 100644 index eb2b494..0000000 --- a/src/Assertion/KeyedContainerAssertion.php +++ /dev/null @@ -1,250 +0,0 @@ - implements IAssertion { - - use FailureEmitter; - use SuccessEmitter; - - private bool $negate = false; - private \ConstMap $context; - - public function __construct( - KeyedContainer $context, - Vector $failureListeners, - Vector $successListeners, - ) { - $this->context = new Map($context); - $this->setFailureListeners($failureListeners); - $this->setSuccessListeners($successListeners); - } - - public function not(): this { - $this->negate = true; - return $this; - } - - public function containsKey(Tkey $expected): void { - if ($this->context->containsKey($expected)) { - if ($this->negate) { - $this->emitFailure( - Failure::fromCallStack( - 'Expected Keyed Container to not have key '. - var_export($expected, true), - ), - ); - return; - } - $this->emitSuccess(); - return; - } - - if ($this->negate) { - $this->emitSuccess(); - return; - } - - $this->emitFailure( - Failure::fromCallStack( - 'Expected Keyed Container to have key '.var_export($expected, true), - ), - ); - return; - } - - public function contains( - Tkey $key, - Tval $val, - ?(function(Tkey, Tval, Tval): bool) $comparitor = null, - ): void { - if ($comparitor === null) { - $comparitor = self::identityComparitor(); - } - - if (!$this->context->containsKey($key)) { - if ($this->negate) { - $this->emitSuccess(); - return; - } - $this->emitFailure( - Failure::fromCallStack( - 'Expected Keyed Container to have key '.var_export($key, true), - ), - ); - return; - } - - if ($comparitor($key, $this->context->at($key), $val)) { - if ($this->negate) { - $this->emitFailure( - Failure::fromCallStack( - 'Expected Keyed Container to not contain a matching value at key '. - var_export($key, true), - ), - ); - return; - } - $this->emitSuccess(); - return; - } - - if ($this->negate) { - $this->emitSuccess(); - return; - } - - $this->emitFailure( - Failure::fromCallStack( - 'Expected Keyed Container to contain a matching value at key '. - var_export($key, true), - ), - ); - } - - public function containsAll( - KeyedContainer $expected, - ?(function(Tkey, Tval, Tval): bool) $comparitor = null, - ): void { - if ($comparitor === null) { - $comparitor = self::identityComparitor(); - } - $filtered = - (new Map($expected))->filterWithKey( - ($k, $v) ==> { - if ($this->context->containsKey($k)) { - return !$comparitor($k, $this->context->at($k), $v); - } - return true; - }, - ); - - if ($filtered->count() === 0) { - if ($this->negate) { - $this->emitFailure( - Failure::fromCallStack( - 'Expected Keyed Container to not contain all elements of given list.', - ), - ); - return; - } - $this->emitSuccess(); - return; - } - - if ($this->negate) { - $this->emitSuccess(); - return; - } - $this->emitFailure( - Failure::fromCallStack( - 'Expected Keyed Container to contain all elements of given list.', - ), - ); - } - - public function containsOnly( - KeyedContainer $expected, - ?(function(Tkey, Tval, Tval): bool) $comparitor = null, - ): void { - $comparitor = - $comparitor === null ? self::identityComparitor() : $comparitor; - $filter = ($a, $b) ==> { - - return $a->filterWithKey( - ($k, $v) ==> { - if ($b->containsKey($k)) { - return !$comparitor($k, $b->at($k), $v); - } - return true; - }, - ); - }; - - $expected = new Map($expected); - $filteredContext = $filter($this->context, $expected); - $filteredExpected = $filter($expected, $this->context); - - if ($filteredContext->isEmpty() && $filteredExpected->isEmpty()) { - if ($this->negate) { - $this->emitFailure( - Failure::fromCallStack( - 'Expected Keyed Container to not contain only the elements of the given list', - ), - ); - return; - } - $this->emitSuccess(); - return; - } - - if ($this->negate) { - $this->emitSuccess(); - return; - } - - $this->emitFailure( - Failure::fromCallStack( - 'Expected Keyed Container to contain only the elements of the given list', - ), - ); - } - - public function containsAny( - KeyedContainer $expected, - ?(function(Tkey, Tval, Tval): bool) $comparitor = null, - ): void { - if ($comparitor === null) { - $comparitor = self::identityComparitor(); - } - - foreach ($expected as $expectedKey => $expectedValue) { - if (!$this->context->containsKey($expectedKey)) { - continue; - } - - if ($comparitor( - $expectedKey, - $this->context->at($expectedKey), - $expectedValue, - )) { - if ($this->negate) { - $this->emitFailure( - Failure::fromCallStack( - 'Expected Keyed Container to not contain any elements of the given list.', - ), - ); - return; - } - $this->emitSuccess(); - return; - } - } - - if ($this->negate) { - $this->emitSuccess(); - return; - } - $this->emitFailure( - Failure::fromCallStack( - 'Expected Keyed Container to contain any elements of the given list.', - ), - ); - } - - <<__Memoize>> - private static function identityComparitor( - ): (function(Tkey, Tval, Tval): bool) { - return ($key, $a, $b) ==> $a === $b; - } -} diff --git a/src/Assertion/MixedAssertion.php b/src/Assertion/MixedAssertion.php deleted file mode 100644 index 60d4f5b..0000000 --- a/src/Assertion/MixedAssertion.php +++ /dev/null @@ -1,158 +0,0 @@ - $failureListeners, - Vector $successListeners, - ) { - $this->setFailureListeners($failureListeners); - $this->setSuccessListeners($successListeners); - } - - public function not(): this { - $this->negate = true; - return $this; - } - - public function isNull(): void { - if ($this->context === null) { - $this->negate - ? $this->fail('Expected context to be non-null.') - : $this->emitSuccess(); - return; - } - $this->negate - ? $this->emitSuccess() - : $this->fail('Expected context to be null.'); - } - - public function isBool(): void { - if (is_bool($this->context)) { - $this->negate - ? $this->fail('Expected context to not be a bool.') - : $this->emitSuccess(); - return; - } - $this->negate - ? $this->emitSuccess() - : $this->fail('Expected context to be a bool.'); - } - - public function isInt(): void { - if (is_int($this->context)) { - $this->negate - ? $this->fail('Expected context to not be an integer.') - : $this->emitSuccess(); - return; - } - $this->negate - ? $this->emitSuccess() - : $this->fail('Expected context to be an integer.'); - } - - public function isFloat(): void { - if (is_float($this->context)) { - $this->negate - ? $this->fail('Expected context to not be an float.') - : $this->emitSuccess(); - return; - } - $this->negate - ? $this->emitSuccess() - : $this->fail('Expected context to be an float.'); - } - - public function isString(): void { - if (is_string($this->context)) { - $this->negate - ? $this->fail('Expected context to not be an string.') - : $this->emitSuccess(); - return; - } - $this->negate - ? $this->emitSuccess() - : $this->fail('Expected context to be an string.'); - } - - public function isArray(): void { - if (is_array($this->context)) { - $this->negate - ? $this->fail('Expected context to not be an array.') - : $this->emitSuccess(); - return; - } - $this->negate - ? $this->emitSuccess() - : $this->fail('Expected context to be an array.'); - } - - public function looselyEquals(mixed $expected): void { - if ($this->context == $expected) { - $this->negate - ? $this->fail('Items expected to not be equal.') - : $this->emitSuccess(); - return; - } - $this->negate - ? $this->emitSuccess() - : $this->fail('Items expected to be equal.'); - } - - public function identicalTo(mixed $expected): void { - if ($this->context === $expected) { - $this->negate - ? $this->fail('Items expected to not be identical.') - : $this->emitSuccess(); - return; - } - $this->negate - ? $this->emitSuccess() - : $this->fail('Items expected to be identical.'); - } - - public function isObject(): void { - if (is_object($this->context)) { - $this->negate - ? $this->fail('Expected context to not be an object.') - : $this->emitSuccess(); - return; - } - $this->negate - ? $this->emitSuccess() - : $this->fail('Expected context to be an object.'); - } - - public function isTypeOf(string $className): void { - if (is_a($this->context, $className)) { - $this->negate - ? $this->fail( - 'Expected context to not be an instance of '.$className.'.', - ) - : $this->emitSuccess(); - return; - } - $this->negate - ? $this->emitSuccess() - : $this->fail('Expected context to be an instance of '.$className.'.'); - } - - private function fail(string $message): void { - $this->emitFailure(Failure::fromCallStack($message)); - } -} diff --git a/src/Assertion/NumericAssertion.php b/src/Assertion/NumericAssertion.php deleted file mode 100644 index b4a622a..0000000 --- a/src/Assertion/NumericAssertion.php +++ /dev/null @@ -1,99 +0,0 @@ - - implements - \HackPack\HackUnit\Contract\Assertion\NumericAssertion { - use FailureEmitter; - use SuccessEmitter; - - private bool $negate = false; - - public function __construct( - private Tcontext $context, - Vector $failureListeners, - Vector $successListeners, - ) { - $this->setFailureListeners($failureListeners); - $this->setSuccessListeners($successListeners); - } - - public function not(): this { - $this->negate = true; - return $this; - } - - public function eq(Tcontext $expected): void { - if ($this->context === $expected) { - $this->negate ? $this->fail('!==', $expected) : $this->emitSuccess(); - return; - } - $this->negate ? $this->emitSuccess() : $this->fail('===', $expected); - } - - public function gt(Tcontext $expected): void { - if ($this->context > $expected) { - $this->negate ? $this->fail('!>', $expected) : $this->emitSuccess(); - return; - } - $this->negate ? $this->emitSuccess() : $this->fail('>', $expected); - } - - public function gte(Tcontext $expected): void { - if ($this->context >= $expected) { - $this->negate ? $this->fail('!>=', $expected) : $this->emitSuccess(); - return; - } - $this->negate ? $this->emitSuccess() : $this->fail('>=', $expected); - } - - public function lt(Tcontext $expected): void { - if ($this->context < $expected) { - $this->negate ? $this->fail('!<', $expected) : $this->emitSuccess(); - return; - } - $this->negate ? $this->emitSuccess() : $this->fail('<', $expected); - } - - public function lte(Tcontext $expected): void { - if ($this->context <= $expected) { - $this->negate ? $this->fail('!<=', $expected) : $this->emitSuccess(); - return; - } - $this->negate ? $this->emitSuccess() : $this->fail('<=', $expected); - } - - private function fail(string $comparison, Tcontext $expected): void { - if (is_int($this->context)) { - $this->emitFailure( - Failure::fromCallStack( - sprintf( - 'Integer assertion failed. Expected %d %s %d', - $this->context, - $comparison, - $expected, - ), - ), - ); - return; - } - $this->emitFailure( - Failure::fromCallStack( - sprintf( - 'Float assertion failed. Expected %f %s %f', - $this->context, - $comparison, - $expected, - ), - ), - ); - } -} diff --git a/src/Assertion/StringAssertion.php b/src/Assertion/StringAssertion.php deleted file mode 100644 index ee52d61..0000000 --- a/src/Assertion/StringAssertion.php +++ /dev/null @@ -1,183 +0,0 @@ - $failureListeners, - Vector $successListeners, - ) { - $this->setFailureListeners($failureListeners); - $this->setSuccessListeners($successListeners); - } - - public function not(): this { - $this->negate = true; - return $this; - } - - public function is(string $expected): this { - if ($this->context === $expected) { - $this->negate - ? $this->fail(Vector {'Strings expected to be non-identical.'}) - : $this->emitSuccess(); - return $this; - } - $this->negate - ? $this->emitSuccess() - : $this->fail( - Vector { - 'Strings expected to be identical:', - 'Context ('.strlen($this->context).'):', - substr($this->context, 0, 250), - '', - 'Expected ('.strlen($expected).')', - substr($expected, 0, 250), - }, - ); - return $this; - } - - public function hasLength(int $length): this { - if (strlen($this->context) === $length) { - $this->negate - ? $this->fail( - Vector { - 'Expected length: '.$length, - 'Context ('.strlen($this->context).'):', - substr($this->context, 0, 250), - }, - ) - : $this->emitSuccess(); - return $this; - } - $this->negate - ? $this->emitSuccess() - : $this->fail( - Vector {'Expected string to have length different than '.$length}, - ); - return $this; - } - - public function matches(string $pattern): this { - $result = preg_match($pattern, $this->context); - /* HH_FIXME[4118] */ - if ($result === false) { - $this->fail( - Vector { - 'Error when matching pattern '.$pattern, - $this->lastPregError(), - }, - ); - return $this; - } - - if ($result === 1) { - $this->negate - ? $this->fail( - Vector {'String expected to not match '.$pattern, $this->context}, - ) - : $this->emitSuccess(); - return $this; - } - - $this->negate - ? $this->emitSuccess() - : $this->fail( - Vector {'String expected to match '.$pattern, $this->context}, - ); - return $this; - } - - private function lastPregError(): string { - switch (preg_last_error()) { - case PREG_NO_ERROR: - return 'No error'; - case PREG_INTERNAL_ERROR: - return 'Internal preg error'; - case PREG_BACKTRACK_LIMIT_ERROR: - return 'Backtrack limit'; - case PREG_RECURSION_LIMIT_ERROR: - return 'Recursion limit'; - case PREG_BAD_UTF8_ERROR: - return 'Invalid UTF8'; - case PREG_BAD_UTF8_OFFSET_ERROR: - return 'Matched to middle of UTF8 character.'; - } - return 'Unknown error'; - } - - public function contains(string $needle): this { - if (strpos($this->context, $needle) === false) { - $this->negate - ? $this->emitSuccess() - : $this->fail( - Vector { - 'Expected context to contain substring.', - 'Context:', - $this->context, - 'Substring:', - $needle, - }, - ); - return $this; - } - $this->negate - ? $this->fail( - Vector { - 'Expected context to not contain substring.', - 'Context:', - $this->context, - 'Substring:', - $needle, - }, - ) - : $this->emitSuccess(); - return $this; - } - - public function containedBy(string $haystack): this { - if (strpos($haystack, $this->context) === false) { - $this->negate - ? $this->emitSuccess() - : $this->fail( - Vector { - 'Context:', - $this->context, - 'Expected to be contained by:', - $haystack, - }, - ); - return $this; - } - $this->negate - ? $this->fail( - Vector { - 'Context:', - $this->context, - 'Expected to not be contained by:', - $haystack, - }, - ) - : $this->emitSuccess(); - return $this; - } - - private function fail(Vector $lines): void { - $this->emitFailure(Failure::fromCallStack(implode(PHP_EOL, $lines))); - } -} diff --git a/src/Contract/Assert.php b/src/Contract/Assert.php deleted file mode 100644 index b0853ee..0000000 --- a/src/Contract/Assert.php +++ /dev/null @@ -1,23 +0,0 @@ -; - public function float(float $context): Assertion\NumericAssertion; - public function string(string $context): Assertion\StringAssertion; - public function whenCalled( - (function(): void) $context, - ): Assertion\CallableAssertion; - public function mixed(mixed $context): Assertion\MixedAssertion; - public function container( - Container $context, - ): Assertion\ContainerAssertion; - public function keyedContainer( - KeyedContainer $context, - ): Assertion\KeyedContainerAssertion; - public function skip(string $reason, ?TraceItem $traceItem = null): void; -} diff --git a/src/Contract/Assertion/Assertion.php b/src/Contract/Assertion/Assertion.php deleted file mode 100644 index b81594a..0000000 --- a/src/Contract/Assertion/Assertion.php +++ /dev/null @@ -1,11 +0,0 @@ - extends Assertion { - - public function contains( - Tval $expected, - ?(function(Tval, Tval): bool) $comparitor = null, - ): void; - - public function containsAll( - Container $expected, - ?(function(Tval, Tval): bool) $comparitor = null, - ): void; - - public function containsAny( - Container $expected, - ?(function(Tval, Tval): bool) $comparitor = null, - ): void; - - public function containsOnly( - Container $expected, - ?(function(Tval, Tval): bool) $comparitor = null, - ): void; - - public function isEmpty(): void; -} diff --git a/src/Contract/Assertion/KeyedContainerAssertion.php b/src/Contract/Assertion/KeyedContainerAssertion.php deleted file mode 100644 index ca95bf2..0000000 --- a/src/Contract/Assertion/KeyedContainerAssertion.php +++ /dev/null @@ -1,10 +0,0 @@ - extends Assertion { - public function containsKey(Tkey $expected): void; - public function contains(Tkey $key, Tval $val): void; - public function containsAll(KeyedContainer $expected): void; - public function containsAny(KeyedContainer $expected): void; -} diff --git a/src/Contract/Assertion/MixedAssertion.php b/src/Contract/Assertion/MixedAssertion.php deleted file mode 100644 index 522bd61..0000000 --- a/src/Contract/Assertion/MixedAssertion.php +++ /dev/null @@ -1,17 +0,0 @@ - extends Assertion { - public function not(): this; - public function eq(Tcontext $expected): void; - public function gt(Tcontext $expected): void; - public function gte(Tcontext $expected): void; - public function lt(Tcontext $expected): void; - public function lte(Tcontext $expected): void; -} diff --git a/src/Contract/Assertion/StringAssertion.php b/src/Contract/Assertion/StringAssertion.php deleted file mode 100644 index 8bde2ae..0000000 --- a/src/Contract/Assertion/StringAssertion.php +++ /dev/null @@ -1,12 +0,0 @@ -; -} diff --git a/src/Contract/Test/Parser.php b/src/Contract/Test/Parser.php deleted file mode 100644 index 12e3518..0000000 --- a/src/Contract/Test/Parser.php +++ /dev/null @@ -1,51 +0,0 @@ -; - - /** - * Return a list of public static methods to run before the suite starts - */ - public function suiteUp(): \ConstVector; - - /** - * Return a list of public static methods to run after the suite ends - */ - public function suiteDown(): \ConstVector; - - /** - * Return a list of public methods (static or not) to run just before each test - */ - public function testUp(): \ConstVector; - - /** - * Return a list of public methods (static or not) to run just after each test - */ - public function testDown(): \ConstVector; - - /** - * Return enough data to define a test method - * - * The factory name SHOULD be contained in the list of factories returned above, - * but this is not required. - */ - public function tests( - ): \ConstVector string, - 'method' => string, - 'skip' => bool, - 'data provider' => string, - )>; - - /** - * List of malformed suite events to broadcast - */ - public function errors(): \ConstVector; -} diff --git a/src/Contract/Test/Runner.php b/src/Contract/Test/Runner.php deleted file mode 100644 index e7c0e71..0000000 --- a/src/Contract/Test/Runner.php +++ /dev/null @@ -1,27 +0,0 @@ - $suites): void; -} diff --git a/src/Contract/Test/Suite.php b/src/Contract/Test/Suite.php deleted file mode 100644 index 13ba882..0000000 --- a/src/Contract/Test/Suite.php +++ /dev/null @@ -1,17 +0,0 @@ -; - public function run( - Assert $assert, - (function(): void) $testPassed, - \ConstVector $testStartListeners, - ): Awaitable; - public function down(): Awaitable; - public function name(): string; -} diff --git a/src/Event/BuildFailure.php b/src/Event/BuildFailure.php deleted file mode 100644 index 418142b..0000000 --- a/src/Event/BuildFailure.php +++ /dev/null @@ -1,18 +0,0 @@ -path; - } - - public function exception(): \Exception { - return $this->exception; - } -} diff --git a/src/Event/Failure.php b/src/Event/Failure.php deleted file mode 100644 index c197c1f..0000000 --- a/src/Event/Failure.php +++ /dev/null @@ -1,34 +0,0 @@ -assertionCallSite; - } - - public function testMethodTraceItem(): TraceItem { - return $this->testCallSite; - } - - public function getMessage(): string { - return $this->message; - } -} diff --git a/src/Event/FailureEmitter.php b/src/Event/FailureEmitter.php deleted file mode 100644 index 84b4564..0000000 --- a/src/Event/FailureEmitter.php +++ /dev/null @@ -1,25 +0,0 @@ - $failureListeners = Vector {}; - - public function onFailure(FailureListener $l): this { - $this->failureListeners->add($l); - return $this; - } - - public function setFailureListeners( - Traversable $listeners, - ): this { - $this->failureListeners->clear()->addAll($listeners); - return $this; - } - - private function emitFailure(Failure $event): void { - foreach ($this->failureListeners as $l) { - $l($event); - } - } -} diff --git a/src/Event/Interruption.php b/src/Event/Interruption.php deleted file mode 100644 index afe190c..0000000 --- a/src/Event/Interruption.php +++ /dev/null @@ -1,5 +0,0 @@ -reason; - } - - public function traceItem(): TraceItem { - return $this->item; - } -} diff --git a/src/Event/Pass.php b/src/Event/Pass.php deleted file mode 100644 index 8b1a464..0000000 --- a/src/Event/Pass.php +++ /dev/null @@ -1,17 +0,0 @@ -testCallSite; - } -} diff --git a/src/Event/Skip.php b/src/Event/Skip.php deleted file mode 100644 index 9828899..0000000 --- a/src/Event/Skip.php +++ /dev/null @@ -1,31 +0,0 @@ -reason; - } - - public function skipCallSite(): TraceItem { - return $this->callSite; - } - - public function testMethodTraceItem(): TraceItem { - return $this->testSite; - } -} diff --git a/src/Event/Success.php b/src/Event/Success.php deleted file mode 100644 index 9b106f8..0000000 --- a/src/Event/Success.php +++ /dev/null @@ -1,25 +0,0 @@ -assertionCallSite; - } - - public function testMethodTraceItem(): TraceItem { - return $this->testCallSite; - } - -} diff --git a/src/Event/SuccessEmitter.php b/src/Event/SuccessEmitter.php deleted file mode 100644 index b269bc4..0000000 --- a/src/Event/SuccessEmitter.php +++ /dev/null @@ -1,26 +0,0 @@ - $successListeners = Vector {}; - - public function onSuccess(SuccessListener $l): this { - $this->successListeners->add($l); - return $this; - } - - public function setSuccessListeners( - Traversable $listeners, - ): this { - $this->successListeners->clear()->addAll(new Vector($listeners)); - return $this; - } - - private function emitSuccess(): void { - $e = Success::fromCallStack(); - foreach ($this->successListeners as $l) { - $l($e); - } - } -} diff --git a/src/Event/SuiteStart.php b/src/Event/SuiteStart.php deleted file mode 100644 index afdc5e8..0000000 --- a/src/Event/SuiteStart.php +++ /dev/null @@ -1,11 +0,0 @@ -suiteName; - } -} diff --git a/src/Event/TestStart.php b/src/Event/TestStart.php deleted file mode 100644 index fdc424a..0000000 --- a/src/Event/TestStart.php +++ /dev/null @@ -1,18 +0,0 @@ -suiteName; - } - - public function testName(): string { - return $this->testName; - } -} diff --git a/src/Exception/InterruptTest.php b/src/Exception/InterruptTest.php deleted file mode 100644 index c010feb..0000000 --- a/src/Exception/InterruptTest.php +++ /dev/null @@ -1,5 +0,0 @@ - $reportFormatters, - private Report\Status $status, - private Test\SuiteBuilder $suiteBuilder, - private Test\Loader $loader, - private Test\Runner $runner, - ) { - $this->summaryBuilder = new Report\SummaryBuilder(); - } - - public function run(): void { - $this->loader->onBuildFailure( - ($event) ==> { - $this->failures = true; - $this->status->handleBuildFailure($event); - }, - ); - $this->suiteBuilder->onMalformedSuite( - inst_meth($this->summaryBuilder, 'handleMalformedSuite'), - ); - - $this->runner->onRunStart( - () ==> { - $this->status->handleRunStart(); - $this->summaryBuilder->startTiming(); - }, - ); - $this->runner->onFailure( - ($e) ==> { - // Allow us to set the exit code - $this->failures = true; - $this->status->handleFailure($e); - $this->summaryBuilder->handleFailure($e); - - }, - ); - $this->runner->onSkip( - ($e) ==> { - $this->status->handleSkip($e); - $this->summaryBuilder->handleSkip($e); - }, - ); - - $this->runner->onSuccess( - ($e) ==> { - $this->summaryBuilder->handleSuccess($e); - }, - ); - - $this->runner->onPass( - ($e) ==> { - $this->status->handlePass($e); - $this->summaryBuilder->handlePass($e); - }, - ); - - $this->runner->onUncaughtException( - ($exception) ==> { - $this->summaryBuilder->handleUntestedException($exception); - }, - ); - $this->runner->onRunEnd( - () ==> { - $this->summaryBuilder->stopTiming(); - $summary = $this->summaryBuilder->getSummary(); - foreach ($this->reportFormatters as $formatter) { - $formatter->writeReport($summary); - } - }, - ); - // LET'S DO THIS! - $this->runner->run($this->loader->testSuites()); - - // Exit codes FTW - if ($this->failures) { - exit(1); - } - exit(0); - } -} diff --git a/src/Report/Format.php b/src/Report/Format.php deleted file mode 100644 index 648b91d..0000000 --- a/src/Report/Format.php +++ /dev/null @@ -1,7 +0,0 @@ -line(PHP_EOL); - $this->line($this->timeReport($status)); - $this->line($this->testSummary($status)); - $this->show($this->malformedReport($status)); - $this->show($this->skipReport($status)); - $this->show($this->errorReport($status)); - $this->show($this->untestedExceptionReport($status)); - } - public function untestedExceptionReport(Summary $summary): string { - $entries = Vector {}; - foreach ($summary['untested exceptions'] as $e) { - - $message = - 'Fatal exception thrown in '. - $e->getFile(). - ' on line '. - $e->getLine(). - '.'; - - $entries->add( - implode( - PHP_EOL, - [ - $message, - 'Exception message:', - $e->getMessage(), - 'Trace:', - $e->getTraceAsString(), - ], - ), - ); - } - - return PHP_EOL.implode(PHP_EOL, $entries).PHP_EOL; - } - - public function testSummary(Summary $summary): string { - return sprintf( - 'Assertions: %s/%d Tests: %s/%d Failed: %s Skipped %s', - $summary['success count'], - $summary['assert count'], - $summary['pass count'], - $summary['test count'], - $summary['fail count'], - $summary['skip count'], - ); - } - - public function skipReport(Summary $summary): string { - if ($summary['skip events']->isEmpty()) { - return ''; - } - return - PHP_EOL. - 'Skipped tests:'. - PHP_EOL. - implode( - PHP_EOL.PHP_EOL, - $summary['skip events']->mapWithKey( - ($idx, $e) ==> { - return implode( - PHP_EOL, - [ - '-*-*-*- Test Skip '.($idx + 1).' -*-*-*-', - $this->buildMethodCall($e->testMethodTraceItem()), - ' In file '.$e->testMethodTraceItem()['file'], - $e->message(), - ], - ); - }, - ), - ). - PHP_EOL; - - } - - public function errorReport(Summary $summary): string { - if ($summary['fail events']->isEmpty()) { - return ''; - } - $report = ''; - foreach ($summary['fail events'] as $idx => $e) { - $assertionTraceItem = $e->assertionTraceItem(); - $testTraceItem = $e->testMethodTraceItem(); - $assertionCall = $this->buildMethodCall($assertionTraceItem); - $testMethod = $this->buildMethodCall($testTraceItem); - $report .= - implode( - PHP_EOL, - [ - '', - '-*-*-*- Test Failure '.($idx + 1).' -*-*-*-', - 'Test failure - '.$testMethod, - 'Assertion failed in '.$assertionCall, - 'On line '. - $assertionTraceItem['line']. - ' of '. - $assertionTraceItem['file'], - $e->getMessage(), - ], - ). - PHP_EOL; - } - return $report.PHP_EOL; - } - - private function timeReport(Summary $summary): string { - $elapsedTime = $summary['end time'] - $summary['start time']; - if ($elapsedTime < 0.000000001) { - return 'Finished testing.'; - } - return sprintf('Finished testing in %.2f seconds.', $elapsedTime); - } - - private function malformedReport(Summary $summary): string { - if ($summary['malformed events']->isEmpty()) { - return ''; - } - - $report = 'Some test suites were malformed:'; - - foreach ($summary['malformed events'] as $idx => $event) { - $report .= implode( - PHP_EOL, - [ - PHP_EOL, - '-*-*-*- Malformed Error '.($idx + 1).' -*-*-*-', - $this->buildMethodCall($event->traceItem()), - $this->buildLineReference($event->traceItem()), - $event->message(), - ], - ); - } - - return $report.PHP_EOL; - } - - private function buildLineReference(TraceItem $item): string { - $lineNumber = $item['line']; - $fileName = $item['file']; - $lineNumber = $lineNumber === null ? '??' : (string) $lineNumber; - $fileName = $fileName === null ? 'Unknown file' : (string) $fileName; - return 'On line '.$lineNumber.' in file '.$fileName; - } - - private function buildMethodCall(TraceItem $item): string { - $className = $item['class']; - $methodName = $item['function']; - if ($className === null) { - $className = 'Unknown class'; - } - if ($methodName === null) { - $methodName = 'Unknown method'; - } - $out = $className.'->'.$methodName.'()'; - return $out; - } - - private function line(string $message): void { - fwrite($this->out, $message.PHP_EOL); - } - - private function show(string $message): void { - fwrite($this->out, $message); - } -} diff --git a/src/Report/Status.php b/src/Report/Status.php deleted file mode 100644 index 5b671a8..0000000 --- a/src/Report/Status.php +++ /dev/null @@ -1,49 +0,0 @@ -out, - sprintf( - "\nHackUnit by HackPack version %s\nHHVM version %s\n", - Options::VERSION, - $hhvmVersion, - ), - ); - } - - public function handlePass(Pass $event): void { - fwrite($this->out, '.'); - } - - public function handleFailure(Failure $event): void { - fwrite($this->out, 'F'); - } - - public function handleSkip(Skip $event): void { - fwrite($this->out, 'S'); - } - - public function handleBuildFailure(BuildFailure $event): void { - sprintf( - "\n~*~*~*~ Build Failure ~*~*~*~\nFile: %s\nMessage: %s\n", - $event->filePath(), - $event->exception()->getMessage(), - ) - |> fwrite($this->out, $$); - } -} diff --git a/src/Report/SummaryBuilder.php b/src/Report/SummaryBuilder.php deleted file mode 100644 index f9ba525..0000000 --- a/src/Report/SummaryBuilder.php +++ /dev/null @@ -1,277 +0,0 @@ - float, - 'end time' => float, - 'assert count' => int, - 'success count' => int, - 'pass count' => int, - 'fail count' => int, - 'fail events' => Vector, - 'skip count' => int, - 'skip events' => Vector, - 'test count' => int, - 'malformed events' => Vector, - 'untested exceptions' => Vector<\Exception>, - 'suite summaries' => Map, -); -type Summary = shape( - 'start time' => float, - 'end time' => float, - 'assert count' => int, - 'success count' => int, - 'pass count' => int, - 'fail count' => int, - 'fail events' => \ConstVector, - 'skip count' => int, - 'skip events' => \ConstVector, - 'test count' => int, - 'malformed events' => \ConstVector, - 'untested exceptions' => \ConstVector<\Exception>, - 'suite summaries' => \ConstMap, -); - -type MutableSuiteSummary = shape( - 'assert count' => int, - 'success count' => int, - 'pass count' => int, - 'fail count' => int, - 'skip count' => int, - 'test count' => int, - 'test summaries' => Map, -); - -type SuiteSummary = shape( - 'assert count' => int, - 'success count' => int, - 'pass count' => int, - 'fail count' => int, - 'skip count' => int, - 'test count' => int, - 'test summaries' => \ConstMap, -); - -type TestSummary = shape( - 'assert count' => int, - 'success count' => int, - 'result' => TestResult, - 'skip event' => ?Skip, - 'fail event' => ?Failure, -); - -type TestInfo = shape( - 'test name' => string, - 'suite name' => string, -); - -enum TestResult : string { - Pass = 'pass'; - Fail = 'fail'; - Skip = 'skip'; - Error = 'error'; -} - -class SummaryBuilder { - - // Mirror Summary shape, but with mutable collections - private MutableSummary $summary; - public function __construct() { - $this->summary = self::emptyMutableSummary(); - } - - public function startTiming(): void { - $this->summary['start time'] = microtime(true); - } - - public function stopTiming(): void { - $this->summary['end time'] = microtime(true); - } - - public function handleFailure(Failure $event): void { - $testInfo = $this->determineTestInfo($event->testMethodTraceItem()); - $this->ensureTestExists($testInfo); - - $this->summary['test count']++; - $this->summary['fail count']++; - $this->summary['assert count']++; - $this->summary['fail events']->add($event); - - $suiteSummary = - $this->summary['suite summaries']->at($testInfo['suite name']); - $suiteSummary['test count']++; - $suiteSummary['fail count']++; - $suiteSummary['assert count']++; - - $testSummary = - $suiteSummary['test summaries']->at($testInfo['test name']); - $testSummary['fail event'] = $event; - $testSummary['assert count']++; - $testSummary['result'] = TestResult::Skip; - - $suiteSummary['test summaries'] - ->set($testInfo['test name'], $testSummary); - $this->summary['suite summaries'] - ->set($testInfo['suite name'], $suiteSummary); - - } - - public function handleSkip(Skip $event): void { - $testInfo = $this->determineTestInfo($event->testMethodTraceItem()); - $this->ensureTestExists($testInfo); - - $this->summary['test count']++; - $this->summary['skip count']++; - $this->summary['skip events']->add($event); - - $suiteSummary = - $this->summary['suite summaries']->at($testInfo['suite name']); - $suiteSummary['test count']++; - $suiteSummary['skip count']++; - - $testSummary = - $suiteSummary['test summaries']->at($testInfo['test name']); - $testSummary['skip event'] = $event; - $testSummary['result'] = TestResult::Skip; - - $suiteSummary['test summaries'] - ->set($testInfo['test name'], $testSummary); - $this->summary['suite summaries'] - ->set($testInfo['suite name'], $suiteSummary); - } - - public function handleSuccess(Success $event): void { - $testInfo = $this->determineTestInfo($event->testMethodTraceItem()); - $this->ensureTestExists($testInfo); - - $this->summary['assert count']++; - $this->summary['success count']++; - - $suiteSummary = - $this->summary['suite summaries']->at($testInfo['suite name']); - $suiteSummary['assert count']++; - $suiteSummary['success count']++; - - $testSummary = - $suiteSummary['test summaries']->at($testInfo['test name']); - $testSummary['assert count']++; - $testSummary['success count']++; - - $suiteSummary['test summaries'] - ->set($testInfo['test name'], $testSummary); - $this->summary['suite summaries'] - ->set($testInfo['suite name'], $suiteSummary); - } - - public function handlePass(Pass $event): void { - $testInfo = $this->determineTestInfo($event->testMethodTraceItem()); - $this->ensureTestExists($testInfo); - - $this->summary['test count']++; - $this->summary['pass count']++; - - $this->summary['suite summaries'] - ->at($testInfo['suite name'])['test count']++; - $this->summary['suite summaries'] - ->at($testInfo['suite name'])['pass count']++; - } - - public function handleUntestedException(\Exception $e): void { - $this->summary['untested exceptions']->add($e); - } - - public function handleMalformedSuite(MalformedSuite $event): void { - $this->summary['malformed events']->add($event); - } - - public function getSummary(): Summary { - return $this->summary; - } - - public static function emptySummary(): Summary { - return self::emptyMutableSummary(); - } - - private static function emptyMutableSummary(): MutableSummary { - return shape( - 'start time' => 0.0, - 'end time' => 0.0, - 'assert count' => 0, - 'success count' => 0, - 'pass count' => 0, - 'fail count' => 0, - 'fail events' => Vector {}, - 'skip count' => 0, - 'skip events' => Vector {}, - 'test count' => 0, - 'malformed events' => Vector {}, - 'untested exceptions' => Vector {}, - 'suite summaries' => Map {}, - ); - } - - public static function emptySuiteSummary(): SuiteSummary { - return self::emptyMutableSuiteSummary(); - } - - private static function emptyMutableSuiteSummary(): MutableSuiteSummary { - - return shape( - 'assert count' => 0, - 'success count' => 0, - 'pass count' => 0, - 'fail count' => 0, - 'skip count' => 0, - 'test count' => 0, - 'test summaries' => Map {}, - ); - } - - public static function emptyTestSummary(): TestSummary { - return shape( - 'assert count' => 0, - 'success count' => 0, - 'message' => '', - 'result' => TestResult::Pass, - ); - } - - private function determineTestInfo(TraceItem $trace): TestInfo { - $testName = Shapes::idx($trace, 'function', '??'); - if ($testName === null) { - $testName = '??'; - } - $suiteName = - Shapes::idx($trace, 'class', Shapes::idx($trace, 'file', '??')); - if ($suiteName === null) { - $suiteName = '??'; - } - - return shape('test name' => $testName, 'suite name' => $suiteName); - } - - private function ensureTestExists(TestInfo $testInfo): void { - if (!$this->summary['suite summaries'] - ->containsKey($testInfo['suite name'])) { - $this->summary['suite summaries'] - ->set($testInfo['suite name'], self::emptyMutableSuiteSummary()); - } - if (!$this->summary['suite summaries'] - ->at($testInfo['suite name'])['test summaries'] - ->containsKey($testInfo['test name'])) { - $this->summary['suite summaries'] - ->at($testInfo['suite name'])['test summaries'] - ->set($testInfo['test name'], self::emptyTestSummary()); - } - } - -} diff --git a/src/Test/Loader.php b/src/Test/Loader.php deleted file mode 100644 index 3e9be9b..0000000 --- a/src/Test/Loader.php +++ /dev/null @@ -1,116 +0,0 @@ - $buildFailureListeners = Vector {}; - - public function __construct( - private (function(string): Traversable) $suiteBuilder, - private Set $includes = Set {}, - private Set $excludes = Set {}, - ) {} - - public function onBuildFailure(BuildFailureListener $l): this { - $this->buildFailureListeners->add($l); - return $this; - } - - public function including(string $path): this { - $this->includes->add($path); - return $this; - } - - public function excluding(string $path): this { - $fullPath = realpath($path); - if (is_string($fullPath)) { - $this->excludes->add($fullPath); - } - return $this; - } - - public function testSuites(): Vector { - $suites = Vector {}; - $builder = $this->suiteBuilder; - - foreach ($this->pathsToScan() as $path) { - try { - $suite = $builder($path); - } catch (\Exception $e) { - $this->emitBuildFailure($path, $e); - $suite = null; - } - - if ($suite !== null) { - $suites->addAll($suite); - } - } - - return $suites; - } - - private function pathsToScan(): \Generator { - foreach ($this->includes as $includeBase) { - $info = new SplFileInfo($includeBase); - $rp = $info->getRealPath(); - if (!is_string($rp) || !$info->isReadable()) { - echo 'skipping '.$rp.PHP_EOL; - continue; - } - - if ($info->isFile() && $this->isPathIncluded($rp)) { - yield $rp; - } - - if ($info->isDir()) { - $rdi = new \RecursiveDirectoryIterator( - $rp, - FilesystemIterator::CURRENT_AS_FILEINFO | - FilesystemIterator::UNIX_PATHS | - FilesystemIterator::SKIP_DOTS, - ); - /* HH_FIXME[4105] */ - $rfi = new \RecursiveCallbackFilterIterator( - $rdi, - $pathInfo ==> { - $realPath = $pathInfo->getRealPath(); - return - $pathInfo->isReadable() && - is_string($realPath) && - $this->isPathIncluded($realPath); - }, - ); - $rii = new \RecursiveIteratorIterator($rfi); - foreach ($rii as $fileInfo) { - $realPath = $fileInfo->getRealPath(); - if (is_string($realPath)) { - yield $realPath; - } - } - } - } - } - - private function isPathIncluded(string $path): bool { - foreach ($this->excludes as $exclude) { - if ($path === $exclude || strpos($path, $exclude.'/') === 0) { - return false; - } - } - return true; - } - - private function emitBuildFailure(string $path, \Exception $e): void { - $event = new BuildFailure($path, $e); - foreach ($this->buildFailureListeners as $l) { - $l($event); - } - } -} diff --git a/src/Test/Parser.php b/src/Test/Parser.php deleted file mode 100644 index 01f1d86..0000000 --- a/src/Test/Parser.php +++ /dev/null @@ -1,511 +0,0 @@ - $errors = Vector {}; - private Map $factories = Map {}; - private Map string, - 'data type' => string, - )> $dataProviders = Map {}; - private Vector $suiteUp = Vector {}; - private Vector $suiteDown = Vector {}; - private Vector $testUp = Vector {}; - private Vector $testDown = Vector {}; - private Vector string, - 'method' => string, - 'skip' => bool, - 'data provider' => string, - )> $tests = Vector {}; - - private ReflectionClass $class; - - public function __construct(string $className, string $fileName) { - $this->ensureClassExists($className, $fileName); - - $this->class = new ReflectionClass($className); - - // Check the constructor last to allow declared default factory - $constructor = null; - - // Only look for tests if the class is instantiable - if ($this->class->isAbstract()) { - return; - } - - // Need to identify data providers before validating test methods - $this->extractDataProviders(); - - foreach ($this->class->getMethods() as $method) { - if ($method->isConstructor()) { - $constructor = $method; - continue; - } - $this->categorize($method); - } - - if ($constructor !== null) { - $this->categorize($constructor); - } - } - - public function factories(): \ConstMap { - return $this->factories; - } - - public function suiteUp(): \ConstVector { - return $this->suiteUp; - } - - public function suiteDown(): \ConstVector { - return $this->suiteDown; - } - - public function testUp(): \ConstVector { - return $this->testUp; - } - - public function testDown(): \ConstVector { - return $this->testDown; - } - - public function tests( - ): \ConstVector string, - 'method' => string, - 'skip' => bool, - 'data provider' => string, - )> { - return $this->tests; - } - - public function errors(): \ConstVector { - return $this->errors; - } - - private function categorize(ReflectionMethod $method): void { - if ($method->isConstructor()) { - $this->checkConstructor($method); - } - - $attrs = new Map($method->getAttributes()); - if (!$attrs->containsKey('Test') && - !$attrs->containsKey('Setup') && - !$attrs->containsKey('TearDown') && - !$attrs->containsKey('SuiteProvider')) { - // This method can't be categorized - return; - } - - if ($method->isConstructor() || $method->isDestructor()) { - // Must be normal instance method - $this->errors - ->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - 'Setup, TearDown, and Test methods must be instance methods and must not be the constructor, the destructor, nor be abstract.', - ), - ); - return; - } - - $this->checkUpDown('Setup', $method); - $this->checkUpDown('TearDown', $method); - $this->checkTest($method); - $this->checkFactory($method); - } - - private function checkUpDown(string $type, ReflectionMethod $method): void { - $attr = (new Map($method->getAttributes()))->get($type); - if ($attr === null) { - return; - } - - // No parameters - if ($method->getNumberOfRequiredParameters() > 0) { - $this->errors->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - $type.' methods must not require parameters.', - ), - ); - return; - } - - $attr = (new Set($attr))->map($v ==> strtolower($v)); - - // Look for <<$type('suite')>> - if ($attr->contains('suite')) { - // Suite setup/teardown must be static - if (!$method->isStatic()) { - $this->errors->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - 'Suite '.$type.' methods must be declared static.', - ), - ); - return; - } - - if ($type === 'Setup') { - $this->suiteUp->add($method->getName()); - } - if ($type === 'TearDown') { - $this->suiteDown->add($method->getName()); - } - } - - // Look for <<$type('test')>> and <<$type>> - if ($attr->isEmpty() || $attr->contains('test')) { - if ($type === 'Setup') { - $this->testUp->add($method->getName()); - } - if ($type === 'TearDown') { - $this->testDown->add($method->getName()); - } - } - } - - private function checkTest(ReflectionMethod $method): void { - // Look for <> attribute - $testAttr = (new Map($method->getAttributes()))->get('Test'); - if ($testAttr === null) { - return; - } - - // If no value, this will be null cast to a string - // and the empty string is the alias for the default factory - $factory = (string) (new Vector($testAttr))->get(0); - - $dataAttr = $method->getAttribute('Data'); - if ($dataAttr === null) { - $dataProvider = null; - } else { - $dataProvider = $this->determineDataProviderForTest($method, $dataAttr); - if ($dataProvider === null) { - return; - } - } - - if ($this->testParamsAreInvalid($method, $dataProvider)) { - return; - } - - $this->tests->add( - shape( - 'factory name' => $factory, - 'method' => $method->getName(), - 'skip' => (new Map($method->getAttributes()))->containsKey('Skip'), - 'data provider' => - $dataProvider === null ? '' : $dataProvider['method'], - ), - ); - } - - private function determineDataProviderForTest( - ReflectionMethod $method, - array $dataAttr, - ): ?shape( - 'method' => string, - 'data type' => string, - ) { - if (count($dataAttr) < 1) { - $this->errors - ->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - 'You must specify the data provider to use, e.g. <>', - ), - ); - return null; - } - - $provider = $this->dataProviders->get((string) $dataAttr[0]); - if ($provider === null) { - $this->errors->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - 'Unknown data provider "'.(string) $dataAttr[0].'"', - ), - ); - return null; - } - - return $provider; - } - - private function testParamsAreInvalid( - ReflectionMethod $method, - ?shape( - 'method' => string, - 'data type' => string, - ) $dataProvider, - ): bool { - - $expectedParams = Vector {Assert::class}; - if ($dataProvider !== null) { - $expectedParams->add($dataProvider['data type']); - } - - $params = new Vector($method->getParameters()); - $invalidParams = $params->filterWithKey( - ($index, $parameter) ==> { - if (!$expectedParams->containsKey($index)) { - return true; - } - - return $parameter->getTypeText() !== $expectedParams->at($index); - }, - ); - - if ($invalidParams->count() > 0 || $params->isEmpty()) { - sprintf( - 'Test method %s must accept exactly %d %s %s', - $method->getName(), - $expectedParams->count(), - $expectedParams->count() === 1 ? 'type' : 'types', - implode(' and ', $expectedParams), - ) - |> $this->errors->add( - new MalformedSuite(Trace::fromReflectionMethod($method), $$), - ); - return true; - } - return false; - } - - private function checkFactory(ReflectionMethod $method): void { - $attr = (new Map($method->getAttributes()))->get('SuiteProvider'); - if ($attr === null) { - return; - } - - $attr = new Vector($attr); - - $alias = $attr->count() > 0 ? $attr->at(0) : ''; - if (!is_string($alias)) { - $this->errors - ->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - 'The <> annotation must have exactly one string parameter', - ), - ); - return; - } - - if ($this->factories->containsKey($alias)) { - $this->errors - ->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - 'The <> annotation must have a unique name', - ), - ); - return; - } - - if (!$method->isStatic()) { - $this->errors - ->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - 'Suite factories annotated with <> must be declared static', - ), - ); - return; - } - - if ($method->getNumberOfRequiredParameters() > 0) { - $this->errors - ->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - 'Suite factories annotated with <> not require any input parameters', - ), - ); - return; - } - - $returnType = (string) $method->getReturnType(); - if (!$this->producesSuiteInstance($method)) { - $this->errors - ->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - 'Suite factories annotated with <> must return an instance of the suite class', - ), - ); - return; - } - - $this->factories->set($alias, $method->getName()); - } - - private function producesSuiteInstance(ReflectionMethod $method): bool { - $returnType = $method->getReturnType(); - - if ($returnType === null || - $returnType->isBuiltin() || - $returnType->allowsNull()) { - return false; - } - - $returnString = (string) $returnType; - - return - $returnString === 'HH\this' || - $this->class->getName() === $returnString; - - } - - private function extractDataProviders(): void { - foreach ($this->class->getMethods() as $method) { - - $dataAttribute = $method->getAttribute('DataProvider'); - if ($dataAttribute === null) { - continue; - } - if (count($dataAttribute) < 1) { - $this->errors - ->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - 'Data providers must have a name, e.g. <>', - ), - ); - continue; - } - - $providerName = $dataAttribute[0]; - if (!is_string($providerName)) { - $this->errors->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - 'Data provider names must be strings.', - ), - ); - continue; - } - - if (!$method->isStatic()) { - $this->errors->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - 'Data providers must be static methods.', - ), - ); - continue; - } - - if ($method->getNumberOfRequiredParameters() !== 0) { - $this->errors->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - 'Data providers must not require input parameters.', - ), - ); - continue; - } - - $dataType = $this->determineDataProviderType($method); - if ($dataType === null) { - continue; - } - - $this->dataProviders->set( - $providerName, - shape('method' => $method->getName(), 'data type' => $dataType), - ); - } - } - - private function determineDataProviderType( - ReflectionMethod $method, - ): ?string { - - // Ensure we have a return type - $return = $method->getReturnType(); - if ($return === null) { - $this->errors->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - 'You must specify a return type for data provider methods.', - ), - ); - return null; - } - - // No nullable types - if ($return->allowsNull()) { - $this->errors->add( - new MalformedSuite( - Trace::fromReflectionMethod($method), - 'Data provider methods may not return nullable types.', - ), - ); - return null; - } - - // Ensure return is foreachable - $typeString = (string) $return; - $expectedStart = - $method->isAsync() ? 'HH\AsyncIterator<' : 'HH\Traversable<'; - if (substr($typeString, 0, strlen($expectedStart)) !== $expectedStart) { - $message = - $method->isAsync() - ? 'Async data providers must return AsyncIterator' - : 'Data providers must return a Traversable'; - $this->errors->add( - new MalformedSuite(Trace::fromReflectionMethod($method), $message), - ); - return null; - } - - // The rest of the return string is the type being passed to the test - return substr($typeString, strlen($expectedStart), -1); - } - - private function checkConstructor(ReflectionMethod $method): void { - if ($method === null) { - // No constructor, oh well. :) - return; - } - - // Don't overwrite the default factory - if ($this->factories->containsKey('')) { - return; - } - - if ($method->getNumberOfRequiredParameters() === 0) { - $this->factories->set('', $method->getName()); - } - } - - private function ensureClassExists( - string $className, - string $fileName, - ): void { - if (!class_exists($className)) { - - if (is_file($fileName)) { - /* HH_FIXME[1002] */ - require_once ($fileName); - } - - if (!class_exists($className)) { - throw new \RuntimeException('Unable to locate class '.$className); - } - - } - } -} diff --git a/src/Test/Runner.php b/src/Test/Runner.php deleted file mode 100644 index f3d4eef..0000000 --- a/src/Test/Runner.php +++ /dev/null @@ -1,190 +0,0 @@ - $exceptionListeners = Vector {}; - private Vector $failureListeners = Vector {}; - private Vector $passListeners = Vector {}; - private Vector $runEndListeners = Vector {}; - private Vector $runStartListeners = Vector {}; - private Vector $skipListeners = Vector {}; - private Vector $successListeners = Vector {}; - private Vector $suiteEndListeners = Vector {}; - private Vector $suiteStartListeners = Vector {}; - private Vector $testStartListeners = Vector {}; - - public function __construct( - private (function(Vector, - Vector, - Vector, - ): Assert) $assertBuilder, - ) {} - - public function onFailure(FailureListener $l): this { - $this->failureListeners->add($l); - return $this; - } - - public function onUncaughtException(ExceptionListener $l): this { - $this->exceptionListeners->add($l); - return $this; - } - - public function onRunEnd(RunEndListener $l): this { - $this->runEndListeners->add($l); - return $this; - } - - public function onRunStart(RunStartListener $l): this { - $this->runStartListeners->add($l); - return $this; - } - - public function onSkip(SkipListener $l): this { - $this->skipListeners->add($l); - return $this; - } - - public function onSuccess(SuccessListener $l): this { - $this->successListeners->add($l); - return $this; - } - - public function onSuiteEnd(SuiteEndListener $l): this { - $this->suiteEndListeners->add($l); - return $this; - } - - public function onSuiteStart(SuiteStartListener $l): this { - $this->suiteStartListeners->add($l); - return $this; - } - - public function onTestStart(TestStartListener $l): this { - $this->testStartListeners->add($l); - return $this; - } - - public function onPass(PassListener $l): this { - $this->passListeners->add($l); - return $this; - } - - public function run(Vector $suites): void { - - // Throw an interruption after all other handlers - $this->failureListeners->add( - $failure ==> { - throw new Interruption(); - }, - ); - - $this->skipListeners->add( - $skip ==> { - throw new Interruption(); - }, - ); - $this->emitRunStart(); - - $builder = $this->assertBuilder; - - $awaitable = Asio\vw( - $suites->map( - async ($s) ==> { - $this->emitSuiteStart(new SuiteStart($s->name())); - await $s->up(); - - $testResult = await $s->run( - $builder( - $this->failureListeners, - $this->skipListeners, - $this->successListeners, - ), - () ==> { - $this->emitPass(); - }, - $this->testStartListeners, - ) |> Asio\wrap($$); - - await $s->down(); - $this->emitSuiteEnd(); - - if ($testResult->isFailed()) { - throw $testResult->getException(); - } - }, - ), - ); - - foreach (Asio\join($awaitable) as $result) { - if ($result->isFailed()) { - $this->emitException($result->getException()); - } - } - - $this->emitRunEnd(); - } - - private function emitSuiteEnd(): void { - foreach ($this->suiteEndListeners as $l) { - $l(); - } - } - - private function emitSuiteStart(SuiteStart $e): void { - foreach ($this->suiteStartListeners as $l) { - $l($e); - } - } - - private function emitTestStart(TestStart $e): void { - foreach ($this->testStartListeners as $l) { - $l($e); - } - } - - private function emitRunEnd(): void { - foreach ($this->runEndListeners as $l) { - $l(); - } - } - - private function emitRunStart(): void { - foreach ($this->runStartListeners as $l) { - $l(); - } - } - - private function emitPass(): void { - $event = Pass::fromCallStack(); - foreach ($this->passListeners as $l) { - $l($event); - } - } - - private function emitException(\Exception $e): void { - foreach ($this->exceptionListeners as $l) { - $l($e); - } - } -} diff --git a/src/Test/SkippedSuite.php b/src/Test/SkippedSuite.php deleted file mode 100644 index 5c0dc0f..0000000 --- a/src/Test/SkippedSuite.php +++ /dev/null @@ -1,27 +0,0 @@ - {} - - public async function down(): Awaitable {} - - public async function run( - Assert $assert, - (function(): void) $testPassed, - \ConstVector $testStartListeners, - ): Awaitable { - $assert->skip('Class '.$this->name.' marked "Skipped"', $this->trace); - } - - public function name(): string { - return $this->name; - } -} diff --git a/src/Test/Suite.php b/src/Test/Suite.php deleted file mode 100644 index e12dcce..0000000 --- a/src/Test/Suite.php +++ /dev/null @@ -1,101 +0,0 @@ - string, - 'suite name' => string, - 'factory' => (function(): Awaitable), - 'method' => InvokerWithParams, - 'trace item' => TraceItem, - 'skip' => bool, - 'data provider' => (function(): AsyncIterator>), -); - -class Suite implements \HackPack\HackUnit\Contract\Test\Suite { - - public function __construct( - private string $name, - private \ConstVector $tests = Vector {}, - private \ConstVector $suiteup = Vector {}, - private \ConstVector $suitedown = Vector {}, - private \ConstVector $testup = Vector {}, - private \ConstVector $testdown = Vector {}, - ) {} - - public function name(): string { - return $this->name; - } - - public async function run( - Assert $assert, - (function(): void) $testPassed, - \ConstVector $testStartListeners, - ): Awaitable { - await (async (Test $test) ==> { - - $testStartEvent = - new TestStart($test['suite name'], $test['name']); - foreach ($testStartListeners as $testStartListener) { - $testStartListener($testStartEvent); - } - - if ($test['skip']) { - try { - $assert->skip('Test marked <>', $test['trace item']); - } catch (Interruption $e) { - // any listeners should have been notified by now - } - return; - } - - $instance = await $test['factory'](); - - await ($this->testup->map($pretest ==> $pretest($instance, [])) - |> Asio\v($$)); - - $results = Vector {}; - foreach ($test['data provider']() await as $data) { - array_unshift($data, $assert); - $results->add($test['method']($instance, $data)); - } - $results = await Asio\vw($results); - foreach ($results as $result) { - if ($result->isSucceeded()) { - $testPassed(); - } - - if ($result->isFailed()) { - $exception = $result->getException(); - if (!($exception instanceof Interruption)) { - throw $exception; - } - } - } - - await $this->testdown->map( - $posttest ==> $posttest($instance, []), - ) - |> Asio\v($$); - }) - |> $this->tests->map($$) - |> Asio\v($$); - } - - public async function up(): Awaitable { - await \HH\Asio\v($this->suiteup->map($f ==> $f(null, []))); - } - - public async function down(): Awaitable { - await \HH\Asio\v($this->suitedown->map($f ==> $f(null, []))); - } -} diff --git a/src/Test/SuiteBuilder.php b/src/Test/SuiteBuilder.php deleted file mode 100644 index f581f52..0000000 --- a/src/Test/SuiteBuilder.php +++ /dev/null @@ -1,255 +0,0 @@ -): Awaitable); - -final class SuiteBuilder { - public function __construct( - private (function(string, string): Parser) $parserBuilder, - private Vector $malformedListeners = Vector {}, - ) {} - - public function onMalformedSuite(MalformedSuiteListener $listener): this { - $this->malformedListeners->add($listener); - return $this; - } - - public function buildSuites(string $filename): Traversable { - $suites = Vector {}; - $parserBuilder = $this->parserBuilder; - - foreach (FileParser::FromFile($filename)->getClasses() as $scannedClass) { - - if ($this->markedAsSkipped($scannedClass)) { - $pos = $scannedClass->getPosition(); - [ - 'line' => $pos['line'], - 'class' => $scannedClass->getName(), - 'file' => $pos['filename'], - ] |> Trace::buildItem($$) - |> new SkippedSuite($scannedClass->getName(), $$) - |> $suites->add($$); - continue; - } - - $mirror = $this->reflectClass($scannedClass); - if ($mirror === null) { - continue; - } - - $parser = $parserBuilder( - $scannedClass->getName(), - $scannedClass->getFileName(), - ); - if ($parser->tests()->isEmpty()) { - continue; - } - - $suite = $this->buildSuite($mirror, $parser); - if ($suite !== null) { - $suites->add($suite); - } - } - - return $suites; - } - - private function markedAsSkipped(ScannedBasicClass $class): bool { - return $class->getAttributes()->containsKey('Skip'); - } - - private function buildInvoker(ReflectionMethod $method): InvokerWithParams { - return async ($instance, $params) ==> { - - $result = - $method->isStatic() - ? $method->invokeArgs(null, $params) - : $method->invokeArgs($instance, $params); - - if ($method->isAsync()) { - await $result; - } - - }; - } - - private function buildDataProvider( - ?ReflectionMethod $method, - ): (function(): AsyncIterator>) { - if ($method === null) { - return async () ==> { - yield []; - }; - } - - $result = $method->invoke(null); - - if ($method->isAsync()) { - return async () ==> { - foreach ($result await as $data) { - yield [$data]; - } - }; - } - - return async () ==> { - foreach ($result as $data) { - yield [$data]; - } - }; - } - - private function buildSuite( - ReflectionClass $classMirror, - Parser $parser, - ): ?SuiteInterface { - $tests = Vector {}; - $errors = $parser->errors()->toVector(); - - // Convert method names to ReflectionMethods - $getMethod = inst_meth($classMirror, 'getMethod'); - $nameToInvoker = $name ==> $this->buildInvoker($getMethod($name)); - - $factories = - $methodName ==> { - return async () ==> { - - if ($methodName === '__construct') { - return $classMirror->newInstance(); - } - - $method = $classMirror->getMethod($methodName); - $result = $method->invoke(null); - if ($method->isAsync()) { - $result = await $result; - } - return $result; - }; - } |> $parser->factories()->map($$); - - // Set the default constructor if possible - if (!$factories->containsKey('')) { - $default = $this->getDefaultFactory($classMirror); - if ($default !== null) { - $factories = $factories->toMap()->set('', $default); - } - } - - $suiteUp = $parser->suiteUp()->map($nameToInvoker); - $suiteDown = $parser->suiteDown()->map($nameToInvoker); - $testUp = $parser->testUp()->map($nameToInvoker); - $testDown = $parser->testDown()->map($nameToInvoker); - - $nullTests = - $test ==> { - - if (!$factories->containsKey($test['factory name'])) { - - ($test['factory name'] === '' - ? 'You must provide a factory method to construct your test suite and annotate it with <>.' - : 'Suite provider "'.$test['factory name'].'" not found.') - |> $errors->add( - new MalformedSuite( - Trace::fromReflectionMethod($getMethod($test['method'])), - $$, - ), - ); - - return null; - } - - return - $getMethod($test['method']) - |> shape( - 'name' => $$->getName(), - 'suite name' => $classMirror->getName(), - 'factory' => $factories->at($test['factory name']), - 'method' => $this->buildInvoker($$), - 'trace item' => Trace::fromReflectionMethod($$), - 'skip' => $test['skip'], - 'data provider' => - ($test['data provider'] === '' - ? null - : $getMethod($test['data provider'])) - |> $this->buildDataProvider($$), - ); - - } - |> $parser->tests()->map($$); - - if (!$errors->isEmpty()) { - foreach ($errors as $error) { - $this->emitMalformedSuite($error); - } - return null; - } - - $tests = Vector {}; - foreach ($nullTests as $t) { - if ($t !== null) { - $tests->add($t); - } - } - return new Suite( - $classMirror->getName(), - $tests, - $suiteUp, - $suiteDown, - $testUp, - $testDown, - ); - } - - private function getDefaultFactory( - ReflectionClass $classMirror, - ): ?(function(): Awaitable) { - $constructor = $classMirror->getConstructor(); - - if ($constructor === null || - $constructor->getNumberOfRequiredParameters() === 0) { - return async () ==> $classMirror->newInstance(); - } - - return null; - } - - private function emitMalformedSuite(MalformedSuite $event): void { - foreach ($this->malformedListeners as $l) { - $l($event); - } - } - - private function load(string $fileName): void { - // Is there a better way of dynamically including files? - /* HH_FIXME[1002] */ - require_once ($fileName); - } - - private function reflectClass( - ScannedBasicClass $scannedClass, - ): ?ReflectionClass { - if (!class_exists($scannedClass->getName())) { - $this->load($scannedClass->getFileName()); - } - - try { - return new \ReflectionClass($scannedClass->getName()); - } catch (\ReflectionException $e) { - // Unable to load the file, or the map was wrong? - // Should we warn the user? - //echo PHP_EOL . 'Unable to reflect class ' . $scannedClass->getName() . PHP_EOL; - return null; - } - } -} diff --git a/src/Util/Builder.php b/src/Util/Builder.php deleted file mode 100644 index cfa084c..0000000 --- a/src/Util/Builder.php +++ /dev/null @@ -1,51 +0,0 @@ - $args): this { - return new self(Options::fromCli($args)); - } - - public function __construct(private Options $options) {} - - public function build(): HackUnit { - $suiteBuilder = new SuiteBuilder( - ($className, $fileName) ==> new Parser($className, $fileName), - ); - - $loader = new Loader( - $class ==> $suiteBuilder->buildSuites($class), - $this->options->includes->toSet(), - $this->options->excludes->toSet(), - ); - - $runner = new Runner(class_meth(Assert::class, 'build')); - - return new HackUnit( - $this->buildReportFormatters(), - $this->buildStatus(), - $suiteBuilder, - $loader, - $runner, - ); - } - - private function buildReportFormatters(): Vector { - return Vector {new Cli(STDOUT)}; - } - - private function buildStatus(): Status { - return new Status(STDOUT); - } -} diff --git a/src/Util/Options.php b/src/Util/Options.php deleted file mode 100644 index b45bac3..0000000 --- a/src/Util/Options.php +++ /dev/null @@ -1,87 +0,0 @@ - $includes, - public \ConstSet $excludes, - ) {} - - public static function fromCli(Traversable $args): Options { - $includes = []; - $excludes = []; - - $arglist = new Vector($args); - $arglist->reverse(); - - // first arg is always path to executable - $arglist->pop(); - - $addPathToArray = ($path, $array) ==> { - $realpath = realpath($path); - if (is_string($realpath)) { - $array[] = $realpath; - } - return $array; - }; - - while ($arglist) { - $arg = $arglist->pop(); - if (substr($arg, 0, 2) === '--') { - $path = self::handleLongOption(substr($arg, 2), $arglist); - if ($path !== '') { - $excludes = $addPathToArray($path, $excludes); - } - continue; - } - if (substr($arg, 0, 1) === '-') { - $path = self::handleShortOption(substr($arg, 1), $arglist); - if ($path !== '') { - $excludes = $addPathToArray($path, $excludes); - } - continue; - } - $includes = $addPathToArray($arg, $includes); - } - - return new Options(new ImmSet($includes), new ImmSet($excludes)); - } - - private static function handleLongOption( - string $arg, - Vector $args, - ): string { - $parts = new Vector(explode('=', $arg, 2)); - if ($parts->at(0) !== 'exclude') { - return ''; - } - $value = $parts->get(1); - if ($value === null) { - $value = self::tryNext($args); - } - return $value; - } - - private static function handleShortOption( - string $arg, - Vector $args, - ): string { - if (substr($arg, 0, 1) !== 'e') { - return ''; - } - $value = substr($arg, 1); - if ($value === false) { - $value = self::tryNext($args); - } - return $value; - } - private static function tryNext(Vector $args): string { - if ($args->isEmpty() || substr($args->at(0), 0, 1) === '-') { - return ''; - } - return $args->pop(); - } -} diff --git a/src/Util/Trace.php b/src/Util/Trace.php deleted file mode 100644 index 644828a..0000000 --- a/src/Util/Trace.php +++ /dev/null @@ -1,168 +0,0 @@ - ?string, - 'line' => ?int, - 'function' => ?string, - 'class' => ?string, -); - -class Trace { - public static function fromScannedMethod( - ScannedBasicClass $class, - ScannedMethod $method, - ): TraceItem { - return self::buildItem( - [ - 'line' => Shapes::idx($method->getPosition(), 'line'), - 'class' => $class->getName(), - 'file' => $method->getFileName(), - 'function' => $method->getName(), - ], - ); - } - - public static function fromReflectionClass( - \ReflectionClass $classMirror, - ): TraceItem { - return self::buildItem( - [ - 'line' => $classMirror->getStartLine(), - 'class' => $classMirror->getName(), - 'file' => $classMirror->getFileName(), - ], - ); - } - - public static function fromReflectionMethod( - \ReflectionMethod $methodMirror, - ): TraceItem { - return self::buildItem( - [ - 'line' => $methodMirror->getStartLine(), - 'function' => $methodMirror->name, - 'class' => $methodMirror->class, - 'file' => $methodMirror->getFileName(), - ], - ); - } - - public static function generate(): Vector { - return - self::convert((new Vector(debug_backtrace()))->removeKey(0)->toArray()); - } - - public static function convert( - array> $trace, - ): Vector { - return (new Vector($trace))->map($t ==> self::buildItem($t)); - } - - public static function buildItem(array $item): TraceItem { - return shape( - 'line' => - array_key_exists('line', $item) && is_int($item['line']) - ? (int) $item['line'] - : null, - 'function' => - array_key_exists('function', $item) && is_string($item['function']) - ? (string) $item['function'] - : null, - 'class' => - array_key_exists('class', $item) && is_string($item['class']) - ? (string) $item['class'] - : null, - 'file' => - array_key_exists('file', $item) && is_string($item['file']) - ? (string) $item['file'] - : null, - ); - } - - public static function findAssertionCallFromStack( - Vector $trace, - ): TraceItem { - foreach ($trace as $idx => $item) { - // Always switching classes when making an assertion - if (($trace->containsKey($idx + 1) && - $item['class'] === $trace->at($idx + 1)['class']) || - $item['class'] === null) { - continue; - } - - // See if current item implements the assertion interface - $implements = class_implements($item['class']); - if (is_array($implements) && - array_key_exists(Assertion::class, $implements)) { - // Next item in the stack was the actual caller - if ($trace->containsKey($idx + 1)) { - return shape( - 'line' => $trace->at($idx)['line'], - 'function' => $trace->at($idx + 1)['function'], - 'class' => $trace->at($idx + 1)['class'], - 'file' => $trace->at($idx)['file'], - ); - } - return self::emptyTraceItem(); - } - } - return self::emptyTraceItem(); - } - - public static function findTestMethodFromStack( - Vector $trace, - ): TraceItem { - foreach ($trace as $idx => $item) { - // Make sure we know the class and method names - if ($item['class'] === null || $item['function'] === null) { - continue; - } - try { - $class = new \ReflectionClass($item['class']); - $method = $class->getMethod((string) $item['function']); - } catch (\ReflectionException $e) { - // Either class or function were not defined - continue; - } - - // See if the class is a suite and the method is a test - $classAttributes = new Map($class->getAttributes()); - $methodAttributes = new Map($method->getAttributes()); - - if ($methodAttributes->get('Test') !== null) { - // Found the marked test method - return shape( - 'line' => $trace->at($idx - 1)['line'], - 'function' => $trace->at($idx)['function'], - 'class' => $trace->at($idx)['class'], - 'file' => $trace->at($idx - 1)['file'], - ); - } - } - - return self::emptyTraceItem(); - } - - public static function findAssertionCall(): TraceItem { - return self::findAssertionCallFromStack(self::generate()); - } - - public static function findTestMethod(): TraceItem { - return self::findTestMethodFromStack(self::generate()); - } - - private static function emptyTraceItem(): TraceItem { - return shape( - 'line' => null, - 'function' => null, - 'class' => null, - 'file' => null, - ); - } -} diff --git a/stylesheets/github-light.css b/stylesheets/github-light.css new file mode 100644 index 0000000..d64ba5d --- /dev/null +++ b/stylesheets/github-light.css @@ -0,0 +1,124 @@ +/* +The MIT License (MIT) + +Copyright (c) 2015 GitHub, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +*/ + +.pl-c /* comment */ { + color: #969896; +} + +.pl-c1 /* constant, markup.raw, meta.diff.header, meta.module-reference, meta.property-name, support, support.constant, support.variable, variable.other.constant */, +.pl-s .pl-v /* string variable */ { + color: #0086b3; +} + +.pl-e /* entity */, +.pl-en /* entity.name */ { + color: #795da3; +} + +.pl-s .pl-s1 /* string source */, +.pl-smi /* storage.modifier.import, storage.modifier.package, storage.type.java, variable.other, variable.parameter.function */ { + color: #333; +} + +.pl-ent /* entity.name.tag */ { + color: #63a35c; +} + +.pl-k /* keyword, storage, storage.type */ { + color: #a71d5d; +} + +.pl-pds /* punctuation.definition.string, string.regexp.character-class */, +.pl-s /* string */, +.pl-s .pl-pse .pl-s1 /* string punctuation.section.embedded source */, +.pl-sr /* string.regexp */, +.pl-sr .pl-cce /* string.regexp constant.character.escape */, +.pl-sr .pl-sra /* string.regexp string.regexp.arbitrary-repitition */, +.pl-sr .pl-sre /* string.regexp source.ruby.embedded */ { + color: #183691; +} + +.pl-v /* variable */ { + color: #ed6a43; +} + +.pl-id /* invalid.deprecated */ { + color: #b52a1d; +} + +.pl-ii /* invalid.illegal */ { + background-color: #b52a1d; + color: #f8f8f8; +} + +.pl-sr .pl-cce /* string.regexp constant.character.escape */ { + color: #63a35c; + font-weight: bold; +} + +.pl-ml /* markup.list */ { + color: #693a17; +} + +.pl-mh /* markup.heading */, +.pl-mh .pl-en /* markup.heading entity.name */, +.pl-ms /* meta.separator */ { + color: #1d3e81; + font-weight: bold; +} + +.pl-mq /* markup.quote */ { + color: #008080; +} + +.pl-mi /* markup.italic */ { + color: #333; + font-style: italic; +} + +.pl-mb /* markup.bold */ { + color: #333; + font-weight: bold; +} + +.pl-md /* markup.deleted, meta.diff.header.from-file */ { + background-color: #ffecec; + color: #bd2c00; +} + +.pl-mi1 /* markup.inserted, meta.diff.header.to-file */ { + background-color: #eaffea; + color: #55a532; +} + +.pl-mdr /* meta.diff.range */ { + color: #795da3; + font-weight: bold; +} + +.pl-mo /* meta.output */ { + color: #1d3e81; +} + diff --git a/stylesheets/styles.css b/stylesheets/styles.css new file mode 100644 index 0000000..647f08d --- /dev/null +++ b/stylesheets/styles.css @@ -0,0 +1,423 @@ +@import url(https://fonts.googleapis.com/css?family=Arvo:400,700,400italic); + +/* MeyerWeb Reset */ + +html, body, div, span, applet, object, iframe, +h1, h2, h3, h4, h5, h6, p, blockquote, pre, +a, abbr, acronym, address, big, cite, code, +del, dfn, em, img, ins, kbd, q, s, samp, +small, strike, strong, sub, sup, tt, var, +b, u, i, center, +dl, dt, dd, ol, ul, li, +fieldset, form, label, legend, +table, caption, tbody, tfoot, thead, tr, th, td, +article, aside, canvas, details, embed, +figure, figcaption, footer, header, hgroup, +menu, nav, output, ruby, section, summary, +time, mark, audio, video { + margin: 0; + padding: 0; + border: 0; + font: inherit; + vertical-align: baseline; +} + + +/* Base text styles */ + +body { + padding:10px 50px 0 0; + font-family:"Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 14px; + color: #232323; + background-color: #FBFAF7; + margin: 0; + line-height: 1.8em; + -webkit-font-smoothing: antialiased; + +} + +h1, h2, h3, h4, h5, h6 { + color:#232323; + margin:36px 0 10px; +} + +p, ul, ol, table, dl { + margin:0 0 22px; +} + +h1, h2, h3 { + font-family: Arvo, Monaco, serif; + line-height:1.3; + font-weight: normal; +} + +h1,h2, h3 { + display: block; + border-bottom: 1px solid #ccc; + padding-bottom: 5px; +} + +h1 { + font-size: 30px; +} + +h2 { + font-size: 24px; +} + +h3 { + font-size: 18px; +} + +h4, h5, h6 { + font-family: Arvo, Monaco, serif; + font-weight: 700; +} + +a { + color:#C30000; + font-weight:200; + text-decoration:none; +} + +a:hover { + text-decoration: underline; +} + +a small { + font-size: 12px; +} + +em { + font-style: italic; +} + +strong { + font-weight:700; +} + +ul { + list-style-position: inside; + list-style: disc; + padding-left: 25px; +} + +ol { + list-style-position: inside; + list-style: decimal; + padding-left: 25px; +} + +blockquote { + margin: 0; + padding: 0 0 0 20px; + font-style: italic; +} + +dl, dt, dd, dl p { + font-color: #444; +} + +dl dt { + font-weight: bold; +} + +dl dd { + padding-left: 20px; + font-style: italic; +} + +dl p { + padding-left: 20px; + font-style: italic; +} + +hr { + border:0; + background:#ccc; + height:1px; + margin:0 0 24px; +} + +/* Images */ + +img { + position: relative; + margin: 0 auto; + max-width: 650px; + padding: 5px; + margin: 10px 0 32px 0; + border: 1px solid #ccc; +} + +p img { + display: inline; + margin: 0; + padding: 0; + vertical-align: middle; + text-align: center; + border: none; +} + +/* Code blocks */ + +code, pre { + font-family: Monaco, "Bitstream Vera Sans Mono", "Lucida Console", Terminal, monospace; + color:#000; + font-size:14px; +} + +pre { + padding: 4px 12px; + background: #FDFEFB; + border-radius:4px; + border:1px solid #D7D8C8; + overflow: auto; + overflow-y: hidden; + margin-bottom: 32px; +} + + +/* Tables */ + +table { + width:100%; +} + +table { + border: 1px solid #ccc; + margin-bottom: 32px; + text-align: left; + } + +th { + font-family: 'Arvo', Helvetica, Arial, sans-serif; + font-size: 18px; + font-weight: normal; + padding: 10px; + background: #232323; + color: #FDFEFB; + } + +td { + padding: 10px; + background: #ccc; + } + + +/* Wrapper */ +.wrapper { + width:960px; +} + + +/* Header */ + +header { + background-color: #171717; + color: #FDFDFB; + width:170px; + float:left; + position:fixed; + border: 1px solid #000; + -webkit-border-top-right-radius: 4px; + -webkit-border-bottom-right-radius: 4px; + -moz-border-radius-topright: 4px; + -moz-border-radius-bottomright: 4px; + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; + padding: 34px 25px 22px 50px; + margin: 30px 25px 0 0; + -webkit-font-smoothing: antialiased; +} + +p.header { + font-size: 16px; +} + +h1.header { + font-family: Arvo, sans-serif; + font-size: 30px; + font-weight: 300; + line-height: 1.3em; + border-bottom: none; + margin-top: 0; +} + + +h1.header, a.header, a.name, header a{ + color: #fff; +} + +a.header { + text-decoration: underline; +} + +a.name { + white-space: nowrap; +} + +header ul { + list-style:none; + padding:0; +} + +header li { + list-style-type: none; + width:132px; + height:15px; + margin-bottom: 12px; + line-height: 1em; + padding: 6px 6px 6px 7px; + + background: #AF0011; + background: -moz-linear-gradient(top, #AF0011 0%, #820011 100%); + background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f8f8f8), color-stop(100%,#dddddd)); + background: -webkit-linear-gradient(top, #AF0011 0%,#820011 100%); + background: -o-linear-gradient(top, #AF0011 0%,#820011 100%); + background: -ms-linear-gradient(top, #AF0011 0%,#820011 100%); + background: linear-gradient(top, #AF0011 0%,#820011 100%); + + border-radius:4px; + border:1px solid #0D0D0D; + + -webkit-box-shadow: inset 0px 1px 1px 0 rgba(233,2,38, 1); + box-shadow: inset 0px 1px 1px 0 rgba(233,2,38, 1); + +} + +header li:hover { + background: #C3001D; + background: -moz-linear-gradient(top, #C3001D 0%, #950119 100%); + background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f8f8f8), color-stop(100%,#dddddd)); + background: -webkit-linear-gradient(top, #C3001D 0%,#950119 100%); + background: -o-linear-gradient(top, #C3001D 0%,#950119 100%); + background: -ms-linear-gradient(top, #C3001D 0%,#950119 100%); + background: linear-gradient(top, #C3001D 0%,#950119 100%); +} + +a.buttons { + -webkit-font-smoothing: antialiased; + background: url(../images/arrow-down.png) no-repeat; + font-weight: normal; + text-shadow: rgba(0, 0, 0, 0.4) 0 -1px 0; + padding: 2px 2px 2px 22px; + height: 30px; +} + +a.github { + background: url(../images/octocat-small.png) no-repeat 1px; +} + +a.buttons:hover { + color: #fff; + text-decoration: none; +} + + +/* Section - for main page content */ + +section { + width:650px; + float:right; + padding-bottom:50px; +} + + +/* Footer */ + +footer { + width:170px; + float:left; + position:fixed; + bottom:10px; + padding-left: 50px; +} + +@media print, screen and (max-width: 960px) { + + div.wrapper { + width:auto; + margin:0; + } + + header, section, footer { + float:none; + position:static; + width:auto; + } + + footer { + border-top: 1px solid #ccc; + margin:0 84px 0 50px; + padding:0; + } + + header { + padding-right:320px; + } + + section { + padding:20px 84px 20px 50px; + margin:0 0 20px; + } + + header a small { + display:inline; + } + + header ul { + position:absolute; + right:130px; + top:84px; + } +} + +@media print, screen and (max-width: 720px) { + body { + word-wrap:break-word; + } + + header { + padding:10px 20px 0; + margin-right: 0; + } + + section { + padding:10px 0 10px 20px; + margin:0 0 30px; + } + + footer { + margin: 0 0 0 30px; + } + + header ul, header p.view { + position:static; + } +} + +@media print, screen and (max-width: 480px) { + + header ul li.download { + display:none; + } + + footer { + margin: 0 0 0 20px; + } + + footer a{ + display:block; + } + +} + +@media print { + body { + padding:0.4in; + font-size:12pt; + color:#444; + } +} \ No newline at end of file diff --git a/test/Assert.php b/test/Assert.php deleted file mode 100644 index 60789cc..0000000 --- a/test/Assert.php +++ /dev/null @@ -1,49 +0,0 @@ - $skips = Vector {}; - - <> - public function clearEvents(): void { - $this->skips->clear(); - } - - <> - public function skipIdentifiesCaller(iAssert $assert): void { - $sut = new Assert( - Vector {}, - Vector { - $skip ==> { - $this->skips->add($skip); - }, - }, - Vector {}, - ); - $line = __LINE__ + 1; - $sut->skip('testing'); - - $assert->int($this->skips->count())->eq(1); - $skip = $this->skips->at(0); - - $this->checkTrace( - $skip->skipCallSite(), - shape( - 'line' => $line, - 'function' => __FUNCTION__, - 'class' => __CLASS__, - 'file' => __FILE__, - ), - $assert, - ); - - $assert->string($skip->message())->is('testing'); - } -} diff --git a/test/Assertion/AssertionTest.php b/test/Assertion/AssertionTest.php deleted file mode 100644 index 01eea4c..0000000 --- a/test/Assertion/AssertionTest.php +++ /dev/null @@ -1,29 +0,0 @@ - $failEvents = Vector {}; - - private function successListeners(): Vector { - return Vector { - ($e) ==> { - $this->successCount++; - }, - }; - } - - private function failListeners(): Vector { - return Vector { - ($e) ==> { - $this->failEvents->add($e); - }, - }; - } -} diff --git a/test/Assertion/BoolAssertion.php b/test/Assertion/BoolAssertion.php deleted file mode 100644 index 837a93a..0000000 --- a/test/Assertion/BoolAssertion.php +++ /dev/null @@ -1,54 +0,0 @@ -failListeners(), - $this->successListeners(), - ); - } - - <> - public function triggersSuccessWhenBoolsMatch(Assert $assert): void { - $a = $this->makeAssertion(true); - $a->is(true); - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - - $a = $this->makeAssertion(false); - $a->is(false); - $assert->int($this->successCount)->eq(2); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function triggersFailureWhenBoolDoesNotMatch(Assert $assert): void { - $a = $this->makeAssertion(false); - $line = __LINE__ + 1; - $a->is(true); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - $e = $this->failEvents->at(0); - $this->checkTrace( - $e->assertionTraceItem(), - shape( - 'line' => $line, - 'function' => __FUNCTION__, - 'class' => __CLASS__, - 'file' => __FILE__, - ), - $assert, - ); - } -} diff --git a/test/Assertion/CallableAssertion.php b/test/Assertion/CallableAssertion.php deleted file mode 100644 index a0fb1f9..0000000 --- a/test/Assertion/CallableAssertion.php +++ /dev/null @@ -1,223 +0,0 @@ - { - }, - $this->failListeners(), - $this->successListeners(), - ); - } - - private function buildThrowingAssertion(): CallableAssertion { - return new CallableAssertion( - () ==> { - throw new TestException(self::message); - }, - $this->failListeners(), - $this->successListeners(), - ); - } - - <> - public function expectedMissingException(Assert $assert): void { - $this->buildNonThrowingAssertion()->willNotThrow(); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function unexpectedException(Assert $assert): void { - $this->buildThrowingAssertion()->willNotThrow(); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function expectedException(Assert $assert): void { - $this->buildThrowingAssertion()->willThrow(); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectedExceptionWithMessage(Assert $assert): void { - $this->buildThrowingAssertion()->willThrowMessage(self::message); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectedExceptionWithMessageContaining( - Assert $assert, - ): void { - $this->buildThrowingAssertion() - ->willThrowMessageContaining(self::message); - $this->buildThrowingAssertion() - ->willThrowMessageContaining(self::subMessage); - - $assert->int($this->successCount)->eq(2); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectedExceptionClass(Assert $assert): void { - $this->buildThrowingAssertion()->willThrowClass(self::exceptionClass); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectedExceptionClassWithMessage(Assert $assert): void { - $this->buildThrowingAssertion() - ->willThrowClassWithMessage(self::exceptionClass, self::message); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectedExceptionClassWithMessageContaining( - Assert $assert, - ): void { - $this->buildThrowingAssertion()->willThrowClassWithMessageContaining( - self::exceptionClass, - self::message, - ); - $this->buildThrowingAssertion()->willThrowClassWithMessageContaining( - self::exceptionClass, - self::subMessage, - ); - - $assert->int($this->successCount)->eq(2); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function missingException(Assert $assert): void { - $this->buildNonThrowingAssertion()->willThrow(); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function missingExceptionWithMessage(Assert $assert): void { - $this->buildNonThrowingAssertion()->willThrowMessage(self::message); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function missingExceptionClass(Assert $assert): void { - $this->buildNonThrowingAssertion()->willThrowClass(self::class); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function missingExceptionClassWithMessage(Assert $assert): void { - $this->buildNonThrowingAssertion() - ->willThrowClassWithMessage(self::class, self::message); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function missingExceptionClassWithMessageContaining( - Assert $assert, - ): void { - $this->buildNonThrowingAssertion() - ->willThrowClassWithMessageContaining(self::class, self::message); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function wrongMessage(Assert $assert): void { - $this->buildThrowingAssertion()->willThrowMessage(self::notSubMessage); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function messageDoesNotContain(Assert $assert): void { - $this->buildThrowingAssertion() - ->willThrowMessageContaining(self::notSubMessage); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function wrongClass(Assert $assert): void { - $this->buildThrowingAssertion()->willThrowClass(self::class); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function wrongClassRightMessage(Assert $assert): void { - $this->buildThrowingAssertion() - ->willThrowClassWithMessage(self::class, self::message); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function wrongClassMessageDoesContain(Assert $assert): void { - $this->buildThrowingAssertion() - ->willThrowClassWithMessageContaining(self::class, self::message); - $this->buildThrowingAssertion() - ->willThrowClassWithMessageContaining(self::class, self::subMessage); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(2); - } - - <> - public function rightClassWrongMessage(Assert $assert): void { - $this->buildThrowingAssertion() - ->willThrowClassWithMessage(self::exceptionClass, self::subMessage); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function rightClassMessageDoesNotContain(Assert $assert): void { - $this->buildThrowingAssertion()->willThrowClassWithMessageContaining( - self::exceptionClass, - self::notSubMessage, - ); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } -} diff --git a/test/Assertion/ContainerAssertion.php b/test/Assertion/ContainerAssertion.php deleted file mode 100644 index 173d4c5..0000000 --- a/test/Assertion/ContainerAssertion.php +++ /dev/null @@ -1,427 +0,0 @@ -( - Container $actual, - ): ContainerAssertion { - return new ContainerAssertion( - $actual, - $this->failListeners(), - $this->successListeners(), - ); - } - - <> - public function doesContain(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b'}); - - $assertion->contains('b'); - $assertion->contains('a'); - - $assert->int($this->successCount)->eq(2); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesContainCustom(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {1, 3}); - - $assertion->contains(2, ($a, $b) ==> true); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function emptyDoesNotContain(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {}); - - $assertion->not()->contains('c'); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContain(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b'}); - - $assertion->not()->contains('c'); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContainCustom(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b'}); - - $assertion->not()->contains('a', ($a, $b) ==> false); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function failsToContain(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b'}); - - $assertion->contains(1); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function emptyFailsToContain(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {}); - - $assertion->contains(1); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - $assert->string($this->failEvents->at(0)->getMessage()) - ->is('The Container is empty.'); - } - - <> - public function failsToContainCustom(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b'}); - - $assertion->contains('a', ($a, $b) ==> false); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function failsToNotContain(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b'}); - - $assertion->not()->contains('b'); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function failsToNotContainCustom(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b'}); - - $assertion->not()->contains('c', ($a, $b) ==> true); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function doesContainAll(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->containsAll(Vector {'a', 'c'}); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesContainAllCustom(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->containsAll(Vector {'a', 'c', 'e'}, ($a, $b) ==> true); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContainAll(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b'}); - - $assertion->not()->containsAll(Vector {'c', 'a'}); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContainAllCustom(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->not()->containsAll(Vector {'a', 'c'}, ($a, $b) ==> false); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function failsToContainAll(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b'}); - - $assertion->containsAll(Vector {'c', 'a'}); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function failsToContainAllCustom(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b'}); - - $assertion->containsAll(Vector {'b', 'a'}, ($a, $b) ==> false); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function failsToNotContainAll(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->not()->containsAll(Vector {'a', 'b'}); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function failsToNotContainAllCustom(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->not()->containsAll(Vector {'a', 'd'}, ($a, $b) ==> true); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function doesContainAny(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->containsAny(Vector {'a', 'd'}); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesContainAnyCustom(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->containsAny(Vector {'d'}, ($a, $b) ==> true); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContainAny(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->not()->containsAny(Vector {'f', 'd'}); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function emptyDoesNotContainAny(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {}); - - $assertion->not()->containsAny(Vector {'f', 'd'}); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContainAnyCustom(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->not()->containsAny(Vector {'a', 'd'}, ($a, $b) ==> false); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function failsToContainAny(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->containsAny(Vector {'f', 'd'}); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function emptyFailsToContainAny(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {}); - - $assertion->containsAny(Vector {'f', 'd'}); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - $assert->string($this->failEvents->at(0)->getMessage()) - ->is('The Container is empty.'); - } - - <> - public function failsToNotContainAny(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->not()->containsAny(Vector {'f', 'b'}); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function failsToNotContainAnyCustom(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->not()->containsAny(Vector {'d', 'f'}, ($a, $b) ==> true); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function doesContainOnly(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->containsOnly(Vector {'b', 'c', 'a'}); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesContainOnlyCustom(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->containsOnly(Vector {'d', 'c', 'a'}, ($a, $b) ==> true); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContainOnly(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->not(); - $assertion->containsOnly(Vector {}); - $assertion->containsOnly(Vector {'g', 'a'}); - $assertion->containsOnly(Vector {'g', 'c', 'a'}); - $assertion->containsOnly(Vector {'b', 'g', 'c', 'a'}); - - $assert->int($this->successCount)->eq(4); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContainOnlyCustom(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - $assertion->not() - ->containsOnly(Vector {'a', 'b', 'c'}, ($a, $b) ==> false); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function containsTooMany(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b', 'c'}); - - $assertion->containsOnly(Vector {'g', 'a'}); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - $assert->string($this->failEvents->at(0)->getMessage()) - ->is('Container contains more elements than expected.'); - } - - <> - public function containsTooFew(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a'}); - - $assertion->containsOnly(Vector {'g', 'a'}); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - $assert->string($this->failEvents->at(0)->getMessage()) - ->is('Container contains fewer elements than expected.'); - } - - <> - public function containsWrongElement(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b'}); - - $assertion->containsOnly(Vector {'c', 'a'}); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - $assert->string($this->failEvents->at(0)->getMessage()) - ->is('Container expected to contain '.var_export('c', true)); - } - - <> - public function failsToNotContainOnly(Assert $assert): void { - $assertion = $this->makeAssertion(Vector {'a', 'b'}); - - $assertion->not()->containsOnly(Vector {'b', 'a'}); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function isEmpty(Assert $assert): void { - $assertion = $this->makeAssertion([]); - - $assertion->isEmpty(); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function isNotEmpty(Assert $assert): void { - $assertion = $this->makeAssertion([1]); - - $assertion->not()->isEmpty(); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function failsToBeEmpty(Assert $assert): void { - $assertion = $this->makeAssertion([1]); - - $assertion->isEmpty(); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function failsToNotBeEmpty(Assert $assert): void { - $assertion = $this->makeAssertion([]); - - $assertion->not()->isEmpty(); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } -} diff --git a/test/Assertion/KeyedContainerAssertion.php b/test/Assertion/KeyedContainerAssertion.php deleted file mode 100644 index 90bd2ac..0000000 --- a/test/Assertion/KeyedContainerAssertion.php +++ /dev/null @@ -1,351 +0,0 @@ -( - KeyedContainer $actual, - ): KeyedContainerAssertion { - return new KeyedContainerAssertion( - $actual, - $this->failListeners(), - $this->successListeners(), - ); - } - - <> - public function doesContainKey(Assert $assert): void { - $this->makeAssertion(['a' => null])->containsKey('a'); - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContainKey(Assert $assert): void { - $this->makeAssertion(['a' => null])->not()->containsKey('c'); - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function failsToContainKey(Assert $assert): void { - $this->makeAssertion(['a' => null])->containsKey('c'); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function failsToNotContainKey(Assert $assert): void { - $this->makeAssertion(['a' => null])->not()->containsKey('a'); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function doesContain(Assert $assert): void { - $this->makeAssertion(['a' => 1, 1 => 'a'])->contains('a', 1); - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContain(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->not()->contains('a', 2); - $assertion->not()->contains('b', 1); - $assert->int($this->successCount)->eq(2); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function failsToContain(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->contains('a', 2); - $assertion->contains(2, 'a'); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(2); - } - - <> - public function failsToNotContain(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->not()->contains('a', 1); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function doesContainCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->contains(1, 'b', ($key, $a, $b) ==> true); - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContainCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->not()->contains('a', 1, ($key, $a, $b) ==> false); - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function failsToContainCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->contains('a', 1, ($key, $a, $b) ==> false); - // This one is not a match because the key does not exist - $assertion->contains(0, 'a', ($key, $a, $b) ==> true); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(2); - } - - <> - public function failsToNotContainCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->not()->contains(1, 'b', ($key, $a, $b) ==> true); - $assertion->not()->contains(0, 'a', ($key, $a, $b) ==> true); - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function doesContainAll(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a', 'b' => 1]); - $assertion->containsAll(['a' => 1, 1 => 'a']); - $assertion->containsAll(['a' => 1, 1 => 'a', 'b' => 1]); - $assert->int($this->successCount)->eq(2); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContainAll(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a', 'b' => 1]); - $assertion->not()->containsAll([0 => 'a']); - $assertion->not()->containsAll(['a' => 1, 0 => 'a']); - $assert->int($this->successCount)->eq(2); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function failsToContainAll(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a', 'b' => 1]); - $assertion->containsAll([0 => 'a']); - $assertion->containsAll(['a' => 1, 0 => 'a']); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(2); - } - - <> - public function failsToNotContainAll(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a', 'b' => 1]); - $assertion->not()->containsAll([1 => 'a']); - $assertion->not()->containsAll(['a' => 1, 1 => 'a']); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(2); - } - - <> - public function doesContainAllCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a', 'b' => 1]); - $assertion->containsAll(['a' => 1, 1 => 'b'], ($k, $a, $b) ==> true); - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContainAllCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a', 'b' => 1]); - $assertion->not()->containsAll([0 => 'a'], ($k, $a, $b) ==> true); - $assertion->not() - ->containsAll(['a' => 1, 'b' => 1], ($k, $a, $b) ==> false); - $assert->int($this->successCount)->eq(2); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function failsToContainAllCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a', 'b' => 1]); - $assertion->containsAll([0 => 'a'], ($k, $a, $b) ==> true); - $assertion->containsAll(['a' => 1, 0 => 'a'], ($k, $a, $b) ==> false); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(2); - } - - <> - public function failsToNotContainAllCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a', 'b' => 1]); - $assertion->not() - ->containsAll(['a' => 1, 'b' => 0], ($k, $a, $b) ==> true); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function doesContainOnly(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->containsOnly(['a' => 1, 1 => 'a']); - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContainOnly(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->not()->containsOnly(['a' => 1, 1 => 'a', 'b' => 1]); - $assertion->not()->containsOnly(['a' => 1, 2 => 'a']); - $assertion->not()->containsOnly([2 => 'a']); - $assert->int($this->successCount)->eq(3); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function failsToContainOnly(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->containsOnly(['a' => 1, 1 => 'a', 'b' => 1]); - $assertion->containsOnly(['a' => 1, 2 => 'a']); - $assertion->containsOnly([2 => 'a']); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(3); - } - - <> - public function failsToNotContainOnly(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->not()->containsOnly(['a' => 1, 1 => 'a']); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function doesContainOnlyCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->containsOnly(['a' => 0, 1 => 0], ($k, $a, $b) ==> true); - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContainOnlyCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->not() - ->containsOnly(['a' => 1, 1 => 'a'], ($k, $a, $b) ==> false); - $assertion->not()->containsOnly([1 => 'a'], ($k, $a, $b) ==> true); - $assertion->not() - ->containsOnly(['b' => 1, 1 => 'a'], ($k, $a, $b) ==> true); - $assertion->not() - ->containsOnly(['a' => 1, 1 => 'a', 'b' => 0], ($k, $a, $b) ==> true); - $assert->int($this->successCount)->eq(4); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function failsToContainOnlyCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->containsOnly(['a' => 1, 1 => 'a'], ($k, $a, $b) ==> false); - $assertion->containsOnly([1 => 'a'], ($k, $a, $b) ==> true); - $assertion->containsOnly(['b' => 1, 1 => 'a'], ($k, $a, $b) ==> true); - $assertion->containsOnly( - ['a' => 1, 1 => 'a', 'b' => 0], - ($k, $a, $b) ==> true, - ); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(4); - } - - <> - public function failsToNotContainOnlyCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->not() - ->containsOnly(['a' => 1, 1 => 'b'], ($k, $a, $b) ==> true); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function doesContainAny(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->containsAny(['a' => 2, 1 => 'a']); - $assertion->containsAny([1 => 'a']); - $assertion->containsAny([1 => 'a', 'a' => 1]); - $assert->int($this->successCount)->eq(3); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesContainAnyCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->containsAny(['a' => 2, 4 => 'a'], ($k, $a, $b) ==> true); - $assertion->containsAny([1 => 'b'], ($k, $a, $b) ==> true); - $assert->int($this->successCount)->eq(2); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContainAny(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->not()->containsAny([]); - $assertion->not()->containsAny(['a' => 2, 2 => 'a']); - $assert->int($this->successCount)->eq(2); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function doesNotContainAnyCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->not() - ->containsAny(['a' => 2, 4 => 'a'], ($k, $a, $b) ==> false); - $assertion->not()->containsAny([1 => 'b'], ($k, $a, $b) ==> false); - $assertion->not()->containsAny([4 => 'b'], ($k, $a, $b) ==> true); - $assertion->not()->containsAny([], ($k, $a, $b) ==> true); - $assert->int($this->successCount)->eq(4); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function failsToNotContainAny(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->not()->containsAny(['a' => 2, 1 => 'a']); - $assertion->not()->containsAny([1 => 'a']); - $assertion->not()->containsAny([1 => 'a', 'a' => 1]); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(3); - } - - <> - public function failsToNotContainAnyCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->not() - ->containsAny(['a' => 2, 4 => 'a'], ($k, $a, $b) ==> true); - $assertion->not()->containsAny([1 => 'b'], ($k, $a, $b) ==> true); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(2); - } - - <> - public function failsToContainAny(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->containsAny([]); - $assertion->containsAny(['a' => 2, 2 => 'a']); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(2); - } - - <> - public function failsToContainAnyCustom(Assert $assert): void { - $assertion = $this->makeAssertion(['a' => 1, 1 => 'a']); - $assertion->containsAny(['a' => 2, 4 => 'a'], ($k, $a, $b) ==> false); - $assertion->containsAny([1 => 'b'], ($k, $a, $b) ==> false); - $assertion->containsAny([4 => 'b'], ($k, $a, $b) ==> true); - $assertion->containsAny([], ($k, $a, $b) ==> true); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(4); - } -} diff --git a/test/Assertion/MixedAssertion.php b/test/Assertion/MixedAssertion.php deleted file mode 100644 index 6838c7c..0000000 --- a/test/Assertion/MixedAssertion.php +++ /dev/null @@ -1,168 +0,0 @@ - - $truish = Vector { - '1', - '-1', - '-1.1', - '0.0', - Vector {''}, - [''], - 'a', - 1, - -1, - 1.1, - -0.1, - }; - - private static Vector - $falsish = Vector {'0', Vector {}, [], '', 0, 0.0}; - - private static Vector - $allTypes = Vector {true, 0, 1.0, 'a', [], Vector {}}; - - private function buildAssertion(mixed $context): MixedAssertion { - return new MixedAssertion( - $context, - $this->failListeners(), - $this->successListeners(), - ); - } - - <> - public function looseComparisonToTrue(Assert $assert): void { - $assertion = $this->buildAssertion(true); - $expectedSuccess = 0; - foreach (self::$truish as $truish) { - $expectedSuccess++; - $assertion->looselyEquals($truish); - $assert->int($this->successCount)->eq($expectedSuccess); - $assert->int($this->failEvents->count())->eq(0); - } - } - - <> - public function strictComparisonToTrue(Assert $assert): void { - $assertion = $this->buildAssertion(true); - $expectedFailures = 0; - foreach (self::$truish as $truish) { - $expectedFailures++; - $assertion->identicalTo($truish); - $assert->int($this->failEvents->count())->eq($expectedFailures); - $assert->int($this->successCount)->eq(0); - } - } - - <> - public function looseComparisonToFalse(Assert $assert): void { - $assertion = $this->buildAssertion(false); - $expectedSuccess = 0; - foreach (self::$falsish as $falsish) { - $expectedSuccess++; - $assertion->looselyEquals($falsish); - $assert->int($this->successCount)->eq($expectedSuccess); - $assert->int($this->failEvents->count())->eq(0); - } - } - - <> - public function strictComparisonToFalse(Assert $assert): void { - $assertion = $this->buildAssertion(false); - $expectedFailures = 0; - foreach (self::$falsish as $falsish) { - $expectedFailures++; - $assertion->identicalTo($falsish); - $assert->int($this->failEvents->count())->eq($expectedFailures); - $assert->int($this->successCount)->eq(0); - } - } - - <> - public function isBool(Assert $assert): void { - foreach (self::$allTypes as $item) { - $this->buildAssertion($item)->isBool(); - } - $assert->int($this->failEvents->count()) - ->eq(self::$allTypes->count() - 1); - $assert->int($this->successCount)->eq(1); - } - - <> - public function isInt(Assert $assert): void { - foreach (self::$allTypes as $item) { - $this->buildAssertion($item)->isInt(); - } - $assert->int($this->failEvents->count()) - ->eq(self::$allTypes->count() - 1); - $assert->int($this->successCount)->eq(1); - } - - <> - public function isFloat(Assert $assert): void { - foreach (self::$allTypes as $item) { - $this->buildAssertion($item)->isFloat(); - } - $assert->int($this->failEvents->count()) - ->eq(self::$allTypes->count() - 1); - $assert->int($this->successCount)->eq(1); - } - - <> - public function isString(Assert $assert): void { - foreach (self::$allTypes as $item) { - $this->buildAssertion($item)->isString(); - } - $assert->int($this->failEvents->count()) - ->eq(self::$allTypes->count() - 1); - $assert->int($this->successCount)->eq(1); - } - - <> - public function isArray(Assert $assert): void { - foreach (self::$allTypes as $item) { - $this->buildAssertion($item)->isArray(); - } - $assert->int($this->failEvents->count()) - ->eq(self::$allTypes->count() - 1); - $assert->int($this->successCount)->eq(1); - } - - <> - public function isObject(Assert $assert): void { - foreach (self::$allTypes as $item) { - $this->buildAssertion($item)->isObject(); - } - $assert->int($this->failEvents->count()) - ->eq(self::$allTypes->count() - 1); - $assert->int($this->successCount)->eq(1); - } - - <> - public function isTypeOf(Assert $assert): void { - $this->buildAssertion(Vector {})->isTypeOf(Vector::class); - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function isNotTypeOf(Assert $assert): void { - $this->buildAssertion(Vector {})->isTypeOf(Map::class); - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function isSubTypeOf(Assert $assert): void { - $this->buildAssertion(Vector {})->isTypeOf(\ConstVector::class); - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } -} diff --git a/test/Assertion/NumericAssertion.php b/test/Assertion/NumericAssertion.php deleted file mode 100644 index 64358fa..0000000 --- a/test/Assertion/NumericAssertion.php +++ /dev/null @@ -1,251 +0,0 @@ - { - return new NumericAssertion( - $context, - $this->failListeners(), - $this->successListeners(), - ); - } - - <> - public function expectEqualIsEqual(Assert $assert): void { - $a = $this->makeAssertion(1); - $a->eq(1); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectEqualIsGreater(Assert $assert): void { - $line = __LINE__ + 2; - $a = $this->makeAssertion(1); - $a->eq(0); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - - $this->checkTrace( - $this->failEvents->at(0)->assertionTraceItem(), - shape( - 'line' => $line, - 'function' => __FUNCTION__, - 'class' => __CLASS__, - 'file' => __FILE__, - ), - $assert, - ); - } - - <> - public function expectEqualIsLess(Assert $assert): void { - $line = __LINE__ + 2; - $a = $this->makeAssertion(1); - $a->eq(2); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - - $this->checkTrace( - $this->failEvents->at(0)->assertionTraceItem(), - shape( - 'line' => $line, - 'function' => __FUNCTION__, - 'class' => __CLASS__, - 'file' => __FILE__, - ), - $assert, - ); - } - - <> - public function expectGreaterIsEqual(Assert $assert): void { - $line = __LINE__ + 2; - $a = $this->makeAssertion(1); - $a->gt(1); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - - $this->checkTrace( - $this->failEvents->at(0)->assertionTraceItem(), - shape( - 'line' => $line, - 'function' => __FUNCTION__, - 'class' => __CLASS__, - 'file' => __FILE__, - ), - $assert, - ); - } - - <> - public function expectGreaterIsGreater(Assert $assert): void { - $a = $this->makeAssertion(1); - $a->gt(0); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectGreaterIsLess(Assert $assert): void { - $line = __LINE__ + 2; - $a = $this->makeAssertion(1); - $a->gt(2); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - - $this->checkTrace( - $this->failEvents->at(0)->assertionTraceItem(), - shape( - 'line' => $line, - 'function' => __FUNCTION__, - 'class' => __CLASS__, - 'file' => __FILE__, - ), - $assert, - ); - } - - <> - public function expectGreaterOrEqualIsEqual(Assert $assert): void { - $a = $this->makeAssertion(1); - $a->gte(1); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectGreaterOrEqualIsGreater(Assert $assert): void { - $a = $this->makeAssertion(1); - $a->gte(0); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectGreaterOrEqualIsLess(Assert $assert): void { - $line = __LINE__ + 2; - $a = $this->makeAssertion(1); - $a->gte(2); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - - $this->checkTrace( - $this->failEvents->at(0)->assertionTraceItem(), - shape( - 'line' => $line, - 'function' => __FUNCTION__, - 'class' => __CLASS__, - 'file' => __FILE__, - ), - $assert, - ); - } - - <> - public function expectLessIsEqual(Assert $assert): void { - $line = __LINE__ + 2; - $a = $this->makeAssertion(1); - $a->lt(1); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - - $this->checkTrace( - $this->failEvents->at(0)->assertionTraceItem(), - shape( - 'line' => $line, - 'function' => __FUNCTION__, - 'class' => __CLASS__, - 'file' => __FILE__, - ), - $assert, - ); - } - - <> - public function expectLessIsGreater(Assert $assert): void { - $line = __LINE__ + 2; - $a = $this->makeAssertion(1); - $a->lt(0); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - - $this->checkTrace( - $this->failEvents->at(0)->assertionTraceItem(), - shape( - 'line' => $line, - 'function' => __FUNCTION__, - 'class' => __CLASS__, - 'file' => __FILE__, - ), - $assert, - ); - } - - <> - public function expectLessIsLess(Assert $assert): void { - $a = $this->makeAssertion(1); - $a->lt(2); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectLessOrEqualIsEqual(Assert $assert): void { - $a = $this->makeAssertion(1); - $a->lte(1); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectLessOrEqualIsGreater(Assert $assert): void { - $line = __LINE__ + 2; - $a = $this->makeAssertion(1); - $a->lte(0); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - - $this->checkTrace( - $this->failEvents->at(0)->assertionTraceItem(), - shape( - 'line' => $line, - 'function' => __FUNCTION__, - 'class' => __CLASS__, - 'file' => __FILE__, - ), - $assert, - ); - } - - <> - public function expectLessOrEqualIsLess(Assert $assert): void { - $a = $this->makeAssertion(1); - $a->lte(2); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } -} diff --git a/test/Assertion/StringAssertion.php b/test/Assertion/StringAssertion.php deleted file mode 100644 index 7b32e39..0000000 --- a/test/Assertion/StringAssertion.php +++ /dev/null @@ -1,138 +0,0 @@ -failListeners(), - $this->successListeners(), - ); - } - - <> - public function expectSameToPass(Assert $assert): void { - $a = $this->makeAssertion(); - $a->is(self::test); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectSameToFail(Assert $assert): void { - $a = $this->makeAssertion(); - $a->is(self::superString); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function expectDifferentToPass(Assert $assert): void { - $a = $this->makeAssertion(); - $a->not()->is(self::superString); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectDifferentToFail(Assert $assert): void { - $a = $this->makeAssertion(); - $a->not()->is(self::test); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function expectContainsToPass(Assert $assert): void { - $a = $this->makeAssertion(); - $a->contains(self::subString); - $a->contains(self::test); - - $assert->int($this->successCount)->eq(2); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectContainsToFail(Assert $assert): void { - $a = $this->makeAssertion(); - $a->contains(self::superString); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function expectContainedByToPass(Assert $assert): void { - $a = $this->makeAssertion(); - $a->containedBy(self::superString); - $a->containedBy(self::test); - - $assert->int($this->successCount)->eq(2); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectContainedByToFail(Assert $assert): void { - $a = $this->makeAssertion(); - $a->containedBy(self::subString); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function expectMatchesToPass(Assert $assert): void { - $a = $this->makeAssertion(); - $a->matches(self::matchingPattern); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectMatchesToFail(Assert $assert): void { - $a = $this->makeAssertion(); - $a->matches(self::nonMatchingPattern); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(1); - } - - <> - public function expectHasLengthToPass(Assert $assert): void { - $a = $this->makeAssertion(); - $a->hasLength(self::realLen); - - $assert->int($this->successCount)->eq(1); - $assert->int($this->failEvents->count())->eq(0); - } - - <> - public function expectHasLengthToFail(Assert $assert): void { - $a = $this->makeAssertion(); - $a->hasLength(self::lessLen); - $a->hasLength(self::moreLen); - - $assert->int($this->successCount)->eq(0); - $assert->int($this->failEvents->count())->eq(2); - } -} diff --git a/test/Doubles/AsyncSuite.php b/test/Doubles/AsyncSuite.php deleted file mode 100644 index 8c6f6e9..0000000 --- a/test/Doubles/AsyncSuite.php +++ /dev/null @@ -1,26 +0,0 @@ - {} - public async function down(): Awaitable {} - - public async function run( - Assert $assert, - (function(): void) $testPassed, - \ConstVector $testStartListeners, - ): Awaitable { - await \HH\Asio\usleep($this->sleepTime); - } - - public function name(): string { - return 'Async test suite'; - } -} diff --git a/test/Doubles/SpySuite.php b/test/Doubles/SpySuite.php deleted file mode 100644 index a7499e6..0000000 --- a/test/Doubles/SpySuite.php +++ /dev/null @@ -1,55 +0,0 @@ - int, - 'down' => int, - 'run' => int, -); - -class SpySuite implements Suite { - - public RunCounts $counts = shape('up' => 0, 'down' => 0, 'run' => 0); - public Vector $asserts = Vector {}; - public Vector<(function(): void)> $passCallbacks = Vector {}; - - private (function(): void) $runAction; - - public function __construct(?(function(): void) $runAction = null) { - $this->runAction = - $runAction === null - ? () ==> { - } - : $runAction; - } - - public function name(): string { - return 'Spy Suite'; - } - - public async function up(): Awaitable { - $this->counts['up']++; - } - - public async function down(): Awaitable { - $this->counts['down']++; - } - - public async function run( - Assert $assert, - (function(): void) $testPassed, - \ConstVector $testStartListeners, - ): Awaitable { - $this->asserts->add($assert); - $this->passCallbacks->add($testPassed); - $this->counts['run']++; - $action = $this->runAction; - $action(); - } - -} diff --git a/test/Doubles/Util/Assertion.php b/test/Doubles/Util/Assertion.php deleted file mode 100644 index e702b70..0000000 --- a/test/Doubles/Util/Assertion.php +++ /dev/null @@ -1,9 +0,0 @@ -> - public static function provider(): Traversable { - return []; - } -} - -class DataProviderWithParams { - <> - public static function provider(int $i): Traversable { - return []; - } -} - -class InstanceDataProvider { - <> - public function provider(int $i): Traversable { - return []; - } -} - -class NonTraversableDataProvider { - <> - public static function provider(): void {} - - <> - public static function intProvider(): int { - return 1; - } - - <> - public static function vectorProvider(): Vector { - return Vector {}; - } -} - -class DataConsumerMismatchParams { - <> - public static function provider(): Traversable { - return []; - } - - <> - public function consumer(Assert $assert, string $value): void {} -} - -class DataConsumerMismatchGeneric { - <> - public static function mapProvider(): Traversable> { - return Map {}; - } - - <> - public static function consumesMap( - Assert $assert, - Map $data, - ): void {} - - <> - public static function consumesMapAgain( - Assert $assert, - Map $data, - ): void {} -} - -class DataConsumerMissingName { - <> - public function consumer(Assert $assert): void {} -} diff --git a/test/Fixtures/InvalidSuites/Factory.php b/test/Fixtures/InvalidSuites/Factory.php deleted file mode 100644 index fb4c7fe..0000000 --- a/test/Fixtures/InvalidSuites/Factory.php +++ /dev/null @@ -1,45 +0,0 @@ -> - public static function one(): this { - return new static(); - } - - <> - public static function two(): this { - return new static(); - } -} - -final class FactoryParams { - <> - public static function factory(int $required): this { - return new static(); - } -} - -final class NonStaticFactory { - <> - public function factory(): this { - return new static(); - } -} - -final class FactoryReturnType { - <> - public static function factory(): int { - return 0; - } -} - -abstract class AbstractFactory { - <> - public static function factory(): AbstractFactory { - return new InvalidDerivedFactory(); - } -} - -class InvalidDerivedFactory extends AbstractFactory {} diff --git a/test/Fixtures/InvalidSuites/SuiteUpDown.php b/test/Fixtures/InvalidSuites/SuiteUpDown.php deleted file mode 100644 index 6de893e..0000000 --- a/test/Fixtures/InvalidSuites/SuiteUpDown.php +++ /dev/null @@ -1,23 +0,0 @@ -> - public static function invalid(int $requiredParam): void {} -} - -class SuiteUpNonStatic { - <> - public function invalid(): void {} -} - -class SuiteDownParams { - <> - public static function invalid(int $requiredParam): void {} -} - -class SuiteDownNonStatic { - <> - public function invalid(): void {} -} diff --git a/test/Fixtures/InvalidSuites/Test.php b/test/Fixtures/InvalidSuites/Test.php deleted file mode 100644 index 7380b92..0000000 --- a/test/Fixtures/InvalidSuites/Test.php +++ /dev/null @@ -1,24 +0,0 @@ -> - public function __construct(Assert $assert) {} - - <> - public function __destruct() {} -} - -class TestParams { - <> - public function noParams(): void {} - - <> - public function wrongParam(int $wrong): void {} - - <> - public function tooManyParams(Assert $assert, int $wrong): void {} -} diff --git a/test/Fixtures/InvalidSuites/TestUpDown.php b/test/Fixtures/InvalidSuites/TestUpDown.php deleted file mode 100644 index cc3867f..0000000 --- a/test/Fixtures/InvalidSuites/TestUpDown.php +++ /dev/null @@ -1,29 +0,0 @@ -> - public function invalid(int $requiredParam): void {} -} - -class TestUpConstructDestruct { - <> - public function __construct() {} - - <> - public function __destruct() {} -} - -class TestDownParams { - <> - public function invalid(int $requiredParam): void {} -} - -class TestDownConstructDestruct { - <> - public function __construct() {} - - <> - public function __destruct() {} -} diff --git a/test/Fixtures/LoadingFiles/IgnoreMe/file1 b/test/Fixtures/LoadingFiles/IgnoreMe/file1 deleted file mode 100644 index e69de29..0000000 diff --git a/test/Fixtures/LoadingFiles/IgnoreMe/file2 b/test/Fixtures/LoadingFiles/IgnoreMe/file2 deleted file mode 100644 index e69de29..0000000 diff --git a/test/Fixtures/LoadingFiles/IgnoreMe/file3 b/test/Fixtures/LoadingFiles/IgnoreMe/file3 deleted file mode 100644 index e69de29..0000000 diff --git a/test/Fixtures/LoadingFiles/file1 b/test/Fixtures/LoadingFiles/file1 deleted file mode 100644 index e69de29..0000000 diff --git a/test/Fixtures/LoadingFiles/file2 b/test/Fixtures/LoadingFiles/file2 deleted file mode 100644 index e69de29..0000000 diff --git a/test/Fixtures/LoadingFiles/file3 b/test/Fixtures/LoadingFiles/file3 deleted file mode 100644 index e69de29..0000000 diff --git a/test/Fixtures/TestException.php b/test/Fixtures/TestException.php deleted file mode 100644 index d377009..0000000 --- a/test/Fixtures/TestException.php +++ /dev/null @@ -1,5 +0,0 @@ -> - public static async function asyncDataProvider(): AsyncIterator { - yield 1; - } - - <> - public function asyncConsumer(Assert $assert, int $value): void {} -} diff --git a/test/Fixtures/ValidSuites/Data.php b/test/Fixtures/ValidSuites/Data.php deleted file mode 100644 index 6bd1f69..0000000 --- a/test/Fixtures/ValidSuites/Data.php +++ /dev/null @@ -1,45 +0,0 @@ -> - public static function consumesVector( - Assert $assert, - Vector $data, - ): void {} - - <> - public static function consumesMap( - Assert $assert, - Map $data, - ): void {} - - <> - public static function consumesString(Assert $assert, string $data): void {} - - <> - public static function notRecognized(Assert $assert): void {} - - <> - public static function vectorProvider(): Traversable> { - return Vector {}; - } - - <> - public static function mapProvider(): Traversable> { - return Map {}; - } - - <> - public static function stringProvider(): Traversable { - return Map {}; - } - - <> - public static function dataProviderWithParam(int $i = 1): Traversable { - return []; - } -} diff --git a/test/Fixtures/ValidSuites/ExternalTest.php b/test/Fixtures/ValidSuites/ExternalTest.php deleted file mode 100644 index aae934f..0000000 --- a/test/Fixtures/ValidSuites/ExternalTest.php +++ /dev/null @@ -1,24 +0,0 @@ -> - public function testInsideTrait(Assert $assert): void {} -} - -abstract class AbstractSuite { - <> - public function testInsideAbstractSuite(Assert $assert): void {} -} - -class BaseSuite extends AbstractSuite { - <> - public function testInsideBaseSuite(Assert $assert): void {} -} diff --git a/test/Fixtures/ValidSuites/Factories.php b/test/Fixtures/ValidSuites/Factories.php deleted file mode 100644 index 943da2b..0000000 --- a/test/Fixtures/ValidSuites/Factories.php +++ /dev/null @@ -1,40 +0,0 @@ -> - public static function factory(): this { - return new static(); - } -} - -final class ConstructorIsDefaultWithParams { - public function __construct(string $notRequired = '') {} - - <> - public static function factory(): this { - return new static(); - } -} - -final class ConstructorIsNotDefault { - public function __construct() {} - - <> - public static function factory(): this { - return new static(); - } -} - -<<__ConsistentConstruct>> -abstract class AbstractFactory { - <> - public static function factory(): DerivedFactory { - return new DerivedFactory(); - } -} - -class DerivedFactory extends AbstractFactory {} diff --git a/test/Fixtures/ValidSuites/Setup.php b/test/Fixtures/ValidSuites/Setup.php deleted file mode 100644 index 8bc0821..0000000 --- a/test/Fixtures/ValidSuites/Setup.php +++ /dev/null @@ -1,20 +0,0 @@ -> - public static function suiteOnly(): void {} - - <> - public static function nonRequiredParam(int $param = 0): void {} - - <> - public static function both(): void {} - - <> - public function testOnlyExplicit(): void {} - - <> - public function testOnlyImplicit(): void {} -} diff --git a/test/Fixtures/ValidSuites/TearDown.php b/test/Fixtures/ValidSuites/TearDown.php deleted file mode 100644 index 61a2ad7..0000000 --- a/test/Fixtures/ValidSuites/TearDown.php +++ /dev/null @@ -1,20 +0,0 @@ -> - public static function suiteOnly(): void {} - - <> - public static function nonRequiredParam(int $param = 0): void {} - - <> - public static function both(): void {} - - <> - public function testOnlyExplicit(): void {} - - <> - public function testOnlyImplicit(): void {} -} diff --git a/test/Fixtures/ValidSuites/Test.php b/test/Fixtures/ValidSuites/Test.php deleted file mode 100644 index f52d5a7..0000000 --- a/test/Fixtures/ValidSuites/Test.php +++ /dev/null @@ -1,24 +0,0 @@ -> - public static function namedBuilder(): this { - return new static(); - } - - <> - public function defaultSuiteProvider(Assert $assert): void {} - - <> - public function namedSuiteProvider(Assert $assert): void {} - - <> - public static function staticTest(Assert $assert): void {} - - <> - public static function skippedTest(Assert $assert): void {} -} diff --git a/test/Report/Status.php b/test/Report/Status.php deleted file mode 100644 index 7cbcc0e..0000000 --- a/test/Report/Status.php +++ /dev/null @@ -1,47 +0,0 @@ -> - public static function provider(): this { - $out = fopen('php://memory', 'w+'); - return new static($out, new Status($out)); - } - - public function __destruct() { - fclose($this->out); - } - - <> - public function passShowsDot(Assert $assert): void { - $this->status->handlePass(Pass::fromCallStack()); - $this->assertOutput($assert, '.'); - } - - <> - public function failureShowsF(Assert $assert): void { - $this->status->handleFailure(Failure::fromCallStack('testing')); - $this->assertOutput($assert, 'F'); - } - - <> - public function skipShowsS(Assert $assert): void { - $this->status->handleSkip(Skip::fromCallStack('testing')); - $this->assertOutput($assert, 'S'); - } - - private function assertOutput(Assert $assert, string $expected): void { - rewind($this->out); - $actual = stream_get_contents($this->out); - $assert->string($actual)->is($expected); - } -} diff --git a/test/Report/SummaryBuilder.php b/test/Report/SummaryBuilder.php deleted file mode 100644 index ed4db82..0000000 --- a/test/Report/SummaryBuilder.php +++ /dev/null @@ -1,201 +0,0 @@ -builder = new SummaryBuilder(); - - } - - private function buildStackTraces(): (TraceItem, TraceItem) { - return tuple( - shape( - 'file' => 'test', - 'line' => 10, - 'function' => 'assertionFunction', - 'class' => 'TestClass', - ), - shape( - 'file' => 'test', - 'line' => 10, - 'function' => 'testFunction', - 'class' => 'TestClass', - ), - ); - } - - private function buildSuccessEvent(): Success { - return new Success(...$this->buildStackTraces()); - } - - private function buildFailEvent(): Failure { - return new Failure('failure message', ...$this->buildStackTraces()); - } - - private function buildSkipEvent(): Skip { - return new Skip('skip message', ...$this->buildStackTraces()); - } - - <> - public function successIncrementsAppropriateCounts(Assert $assert): void { - $this->builder->handleSuccess($this->buildSuccessEvent()); - $actualSummary = $this->builder->getSummary(); - - $expectedTestSummary = SummaryBuilder::emptyTestSummary(); - $expectedTestSummary['assert count'] = 1; - $expectedTestSummary['success count'] = 1; - - $expectedSuiteSummary = SummaryBuilder::emptySuiteSummary(); - $expectedSuiteSummary['assert count'] = 1; - $expectedSuiteSummary['success count'] = 1; - $expectedSuiteSummary['test summaries'] = Map { - 'testFunction' => $expectedTestSummary, - }; - - $expectedSummary = SummaryBuilder::emptySummary(); - $expectedSummary['assert count'] = 1; - $expectedSummary['success count'] = 1; - $expectedSummary['suite summaries'] = Map { - 'TestClass' => $expectedSuiteSummary, - }; - - $this->compareSummaries($assert, $actualSummary, $expectedSummary); - } - - <> - public function failIncrementsAppropriateCounts(Assert $assert): void { - $event = $this->buildFailEvent(); - $this->builder->handleFailure($event); - $actualSummary = $this->builder->getSummary(); - - $expectedTestSummary = SummaryBuilder::emptyTestSummary(); - $expectedTestSummary['assert count'] = 1; - $expectedTestSummary['result'] = TestResult::Fail; - $expectedTestSummary['fail event'] = $event; - - $expectedSuiteSummary = SummaryBuilder::emptySuiteSummary(); - $expectedSuiteSummary['assert count'] = 1; - $expectedSuiteSummary['test count'] = 1; - $expectedSuiteSummary['fail count'] = 1; - $expectedSuiteSummary['test summaries'] = Map { - 'testFunction' => $expectedTestSummary, - }; - - $expectedSummary = SummaryBuilder::emptySummary(); - $expectedSummary['assert count'] = 1; - $expectedSummary['test count'] = 1; - $expectedSummary['fail count'] = 1; - $expectedSummary['fail events'] = Vector {$event}; - $expectedSummary['suite summaries'] = Map { - 'TestClass' => $expectedSuiteSummary, - }; - - $this->compareSummaries($assert, $actualSummary, $expectedSummary); - } - - <> - public function skipIncrementsAppropriateCounts(Assert $assert): void { - $event = $this->buildSkipEvent(); - $this->builder->handleSkip($event); - $actualSummary = $this->builder->getSummary(); - - $expectedTestSummary = SummaryBuilder::emptyTestSummary(); - $expectedTestSummary['test count'] = 1; - $expectedTestSummary['result'] = TestResult::Skip; - $expectedTestSummary['skip event'] = $event; - - $expectedSuiteSummary = SummaryBuilder::emptySuiteSummary(); - $expectedSuiteSummary['skip count'] = 1; - $expectedSuiteSummary['test count'] = 1; - $expectedSuiteSummary['test summaries'] = Map { - 'testFunction' => $expectedTestSummary, - }; - - $expectedSummary = SummaryBuilder::emptySummary(); - $expectedSummary['test count'] = 1; - $expectedSummary['skip count'] = 1; - $expectedSummary['skip events'] = Vector {$event}; - $expectedSummary['suite summaries'] = Map { - 'TestClass' => $expectedSuiteSummary, - }; - - $this->compareSummaries($assert, $actualSummary, $expectedSummary); - } - - private function compareSummaries( - Assert $assert, - Summary $actualSummary, - Summary $expectedSummary, - ): void { - $assert->float($actualSummary['start time']) - ->eq($expectedSummary['start time']); - $assert->float($actualSummary['end time']) - ->eq($expectedSummary['end time']); - $assert->int($actualSummary['assert count']) - ->eq($expectedSummary['assert count']); - $assert->int($actualSummary['success count']) - ->eq($expectedSummary['success count']); - $assert->int($actualSummary['pass count']) - ->eq($expectedSummary['pass count']); - $assert->int($actualSummary['fail count']) - ->eq($expectedSummary['fail count']); - $assert->int($actualSummary['skip count']) - ->eq($expectedSummary['skip count']); - $assert->int($actualSummary['test count']) - ->eq($expectedSummary['test count']); - $assert->container($actualSummary['fail events']) - ->containsOnly($expectedSummary['fail events']); - $assert->container($actualSummary['skip events']) - ->containsOnly($expectedSummary['skip events']); - $assert->container($actualSummary['malformed events']) - ->containsOnly($expectedSummary['malformed events']); - $assert->container($actualSummary['untested exceptions']) - ->containsOnly($expectedSummary['untested exceptions']); - - $assert->container($actualSummary['suite summaries']->keys()) - ->containsOnly($expectedSummary['suite summaries']->keys()); - foreach ($expectedSummary['suite summaries'] as - $suiteName => $expectedSuiteSummary) { - $this->compareSuiteSummaries( - $assert, - $actualSummary['suite summaries']->at($suiteName), - $expectedSuiteSummary, - ); - } - } - - private function compareSuiteSummaries( - Assert $assert, - SuiteSummary $actualSummary, - SuiteSummary $expectedSummary, - ): void { - $assert->int($actualSummary['assert count']) - ->eq($expectedSummary['assert count']); - $assert->int($actualSummary['success count']) - ->eq($expectedSummary['success count']); - $assert->int($actualSummary['pass count']) - ->eq($expectedSummary['pass count']); - $assert->int($actualSummary['fail count']) - ->eq($expectedSummary['fail count']); - $assert->int($actualSummary['skip count']) - ->eq($expectedSummary['skip count']); - $assert->int($actualSummary['test count']) - ->eq($expectedSummary['test count']); - - $assert->container($actualSummary['test summaries']->keys()) - ->containsOnly($expectedSummary['test summaries']->keys()); - } -} diff --git a/test/Test/Async.php b/test/Test/Async.php deleted file mode 100644 index f3d8572..0000000 --- a/test/Test/Async.php +++ /dev/null @@ -1,41 +0,0 @@ - $finished = Set {}; - - <> - public async function testOne(Assert $assert): Awaitable { - $assert->container(self::$finished)->isEmpty(); - await \HH\Asio\later(); - self::$finished->add('testOne'); - } - - <> - public async function testTwo(Assert $assert): Awaitable { - $assert->container(self::$finished)->isEmpty(); - await \HH\Asio\later(); - self::$finished->add('testTwo'); - } - - <> - public static async function threeValues(): AsyncIterator { - yield '1'; - yield '2'; - yield '3'; - } - - <> - public async function dataConsumer( - Assert $assert, - string $value, - ): Awaitable { - $assert->container(self::$finished)->isEmpty(); - await \HH\Asio\later(); - self::$finished->add($value); - } - -} diff --git a/test/Test/InvalidParsing.php b/test/Test/InvalidParsing.php deleted file mode 100644 index cce7124..0000000 --- a/test/Test/InvalidParsing.php +++ /dev/null @@ -1,146 +0,0 @@ - string, - 'errors' => int, -); - -class InvalidParsing extends ParserTest { - - protected static function basePath(): string { - return dirname(__DIR__).'/Fixtures/InvalidSuites'; - } - - protected static function fullName(string $name): string { - return 'HackPack\\HackUnit\\Tests\\Fixtures\\InvalidSuites\\'.$name; - } - - <> - public function factoryParsing(Assert $assert): void { - $factoryList = $this->parserFromSuiteName('AbstractFactory')->factories(); - $assert->int($factoryList->count())->eq(0); - } - - <> - public static function invalidSuiteUpDown(): Traversable { - return [ - 'SuiteUpParams', - 'SuiteUpNonStatic', - 'SuiteDownParams', - 'SuiteDownNonStatic', - ]; - } - - <> - public function SuiteUpDownParseErrors( - Assert $assert, - string $suiteName, - ): void { - $parser = $this->parserFromSuiteName($suiteName); - $assert->int($parser->errors()->count())->eq(1); - $assert->int($parser->suiteUp()->count())->eq(0); - } - - <> - public static function invalidUpDownSuites(): Traversable { - return [ - shape('errors' => 1, 'name' => 'TestUpParams'), - shape('errors' => 2, 'name' => 'TestUpConstructDestruct'), - shape('errors' => 2, 'name' => 'TestDownConstructDestruct'), - shape('errors' => 1, 'name' => 'TestUpParams'), - shape('errors' => 1, 'name' => 'TestDownParams'), - ]; - } - <> - public function TestUpDownParseErrors( - Assert $assert, - ErrorSuite $suiteData, - ): void { - $parser = $this->parserFromSuiteName($suiteData['name']); - $assert->int($parser->errors()->count())->eq($suiteData['errors']); - $assert->int($parser->testUp()->count())->eq(0); - } - - <> - public function TestParseErrors(Assert $assert): void { - $parser = $this->parserFromSuiteName('TestConstructDestruct'); - $assert->int($parser->errors()->count())->eq(2); - $assert->int($parser->tests()->count())->eq(0); - - $parser = $this->parserFromSuiteName('TestParams'); - $assert->int($parser->errors()->count())->eq(3); - $assert->int($parser->tests()->count())->eq(0); - } - - <> - public static function invalidFactories(): Traversable { - return [ - 'FactoryParams', - 'NonStaticFactory', - 'FactoryReturnType', - 'InvalidDerivedFactory', - ]; - } - - <> - public function FactoryParseErrors(Assert $assert, string $suiteName): void { - $parser = $this->parserFromSuiteName($suiteName); - $assert->int($parser->errors()->count())->eq(1); - $assert->int($parser->factories()->count())->eq(0); - } - - <> - public function duplicateFactories(Assert $assert): void { - $parser = $this->parserFromSuiteName('DuplicateFactories'); - $assert->int($parser->errors()->count())->eq(1); - $assert->int($parser->factories()->count())->eq(1); - } - - <> - public static function invalidDataProviders(): Traversable { - return [ - shape('errors' => 1, 'name' => 'DataProviderMissingName'), - shape('errors' => 1, 'name' => 'DataProviderWithParams'), - shape('errors' => 1, 'name' => 'InstanceDataProvider'), - shape('errors' => 3, 'name' => 'NonTraversableDataProvider'), - ]; - } - - <> - public function invalidDataProvider( - Assert $assert, - ErrorSuite $suiteData, - ): void { - $parser = $this->parserFromSuiteName($suiteData['name']); - $assert->int($parser->errors()->count())->eq($suiteData['errors']); - $assert->int($parser->tests()->count())->eq(0); - } - - <> - public static function invalidDataConsumers(): Traversable { - return [ - shape('errors' => 1, 'name' => 'DataConsumerMismatchParams'), - shape('errors' => 1, 'name' => 'DataConsumerMissingName'), - shape('errors' => 2, 'name' => 'DataConsumerMismatchGeneric'), - ]; - } - - <> - public function invalidDataConsumer( - Assert $assert, - ErrorSuite $suiteData, - ): void { - $parser = $this->parserFromSuiteName($suiteData['name']); - if ($parser->errors()->count() !== $suiteData['errors']) { - var_dump($suiteData, $parser->errors()); - } - $assert->int($parser->errors()->count())->eq($suiteData['errors']); - $assert->int($parser->tests()->count())->eq(0); - } -} diff --git a/test/Test/Loader.php b/test/Test/Loader.php deleted file mode 100644 index 2bb3b0e..0000000 --- a/test/Test/Loader.php +++ /dev/null @@ -1,120 +0,0 @@ - $fileNames = Vector {}; - - private Loader $loader; - - public function __construct() { - $this->fileDir = dirname(__DIR__).'/Fixtures/LoadingFiles'; - $this->loader = new Loader( - $filename ==> { - $this->fileNames->add($filename); - return Vector {}; - }, - ); - } - - <> - public function ignoresMultipleFiles(Assert $assert): void { - $this->loader - ->including($this->fileDir) - ->excluding($this->fileDir.'/IgnoreMe/file1') - ->excluding($this->fileDir.'/IgnoreMe/file2'); - $this->assertExpectedFiles( - $assert, - Vector { - $this->fileDir.'/file1', - $this->fileDir.'/file2', - $this->fileDir.'/file3', - $this->fileDir.'/IgnoreMe/file3', - }, - ); - } - - <> - public function ignoresFile(Assert $assert): void { - $this->loader - ->including($this->fileDir) - ->excluding($this->fileDir.'/IgnoreMe/file1'); - $this->assertExpectedFiles( - $assert, - Vector { - $this->fileDir.'/file1', - $this->fileDir.'/file2', - $this->fileDir.'/file3', - $this->fileDir.'/IgnoreMe/file2', - $this->fileDir.'/IgnoreMe/file3', - }, - ); - } - - <> - public function ignoresFolder(Assert $assert): void { - $this->loader - ->including($this->fileDir) - ->excluding($this->fileDir.'/IgnoreMe'); - $this->assertExpectedFiles( - $assert, - Vector { - $this->fileDir.'/file1', - $this->fileDir.'/file2', - $this->fileDir.'/file3', - }, - ); - } - - <> - public function loadsAllFiles(Assert $assert): void { - $this->loader->including($this->fileDir); - $this->assertExpectedFiles( - $assert, - Vector { - $this->fileDir.'/file1', - $this->fileDir.'/file2', - $this->fileDir.'/file3', - $this->fileDir.'/IgnoreMe/file1', - $this->fileDir.'/IgnoreMe/file2', - $this->fileDir.'/IgnoreMe/file3', - }, - ); - } - - <> - public function loadsSingleFile(Assert $assert): void { - $this->loader->including($this->fileDir.'/file1'); - $this->assertExpectedFiles($assert, Vector {$this->fileDir.'/file1'}); - } - - <> - public function loadsMultipleFiles(Assert $assert): void { - $this->loader - ->including($this->fileDir.'/file1') - ->including($this->fileDir.'/file2'); - $this->assertExpectedFiles( - $assert, - Vector {$this->fileDir.'/file1', $this->fileDir.'/file2'}, - ); - } - - private function assertExpectedFiles( - Assert $assert, - Vector $expectedFiles, - ): void { - // This actually hits the filesystem - $this->loader->testSuites(); - - $missing = array_diff($expectedFiles, $this->fileNames); - $extra = array_diff($this->fileNames, $expectedFiles); - - $assert->int(count($missing))->eq(0); - $assert->int(count($extra))->eq(0); - } -} diff --git a/test/Test/ParserTest.php b/test/Test/ParserTest.php deleted file mode 100644 index 358132f..0000000 --- a/test/Test/ParserTest.php +++ /dev/null @@ -1,38 +0,0 @@ - $parsersBySuiteName = Map {}; - - <> - public static function buildParsers(): void { - self::$parsersBySuiteName->clear()->addAll( - TreeParser::FromPath(static::basePath()) - ->getClasses() - ->map( - $class ==> Pair { - $class->getName(), - new Parser($class->getName(), $class->getFileName()), - }, - ), - ); - } - - protected function parserFromSuiteName(string $name): Parser { - $parser = self::$parsersBySuiteName->get(static::fullName($name)); - - if ($parser === null) { - throw new \RuntimeException('Unable to locate suite '.$name); - } - return $parser; - } -} diff --git a/test/Test/Runner.php b/test/Test/Runner.php deleted file mode 100644 index d4d1d69..0000000 --- a/test/Test/Runner.php +++ /dev/null @@ -1,186 +0,0 @@ - $failureListeners = Vector {}; - private Vector $skipListeners = Vector {}; - private Vector $successListeners = Vector {}; - private Vector $asserts = Vector {}; - private Vector<\Exception> $uncaughtExceptions = Vector {}; - private Runner $runner; - private int $testsPassed = 0; - - public function __construct() { - $this->runner = new Runner(inst_meth($this, 'assertionBuilder')); - } - - public function assertionBuilder( - Vector $failures, - Vector $skips, - Vector $successes, - ): Assert { - $this->failureListeners->addAll($failures); - $this->skipListeners->addAll($skips); - $this->successListeners->addAll($successes); - - $assert = new \HackPack\HackUnit\Assert($failures, $skips, $successes); - - $this->asserts->add($assert); - return $assert; - } - - <> - public function allSuitesAreRun(Assert $assert): void { - $suites = Vector {}; - for ($i = 0; $i < 3; $i++) { - $suites->add(new SpySuite()); - } - - $this->runner->run($suites); - - foreach ($suites as $index => $suite) { - - // Tell the typechecker we know what's going on - invariant($suite instanceof SpySuite, ''); - - // Ensure each suite is run once - $assert->int($suite->counts['up'])->eq(1); - $assert->int($suite->counts['run'])->eq(1); - $assert->int($suite->counts['down'])->eq(1); - - // Ensure the suites are passed the generated assert objects - $assert->mixed($suite->asserts->at(0)) - ->identicalTo($this->asserts->at($index)); - } - } - - <> - public function suitesAreRunAsync(Assert $assert): void { - // 0.01 second per suite - $sleepTime = 10000; - $suites = Vector {}; - for ($i = 0; $i < 3; $i++) { - $suites->add(new AsyncSuite($sleepTime)); - } - - $start = microtime(true); - $this->runner->run($suites); - $end = microtime(true); - - // Convert delta time to microseconds - $deltaTime = ($end - $start) * 1000000; - - // Total run time should be less than twice the sleep time - // since all are running in async - $assert->float($deltaTime)->lt(2.0 * $sleepTime); - } - - <> - public function interruptionEventHandlersAreAdded(Assert $assert): void { - $this->runner->run(Vector {new SpySuite()}); - - $assert->int($this->failureListeners->count())->eq(1); - $assert->int($this->skipListeners->count())->eq(1); - $assert->int($this->successListeners->count())->eq(0); - - // Ensure the handlers called throw an Interruption exception - $assert->whenCalled( - () ==> { - $listener = $this->failureListeners->at(0); - $listener(Failure::fromCallStack('fake failure')); - }, - )->willThrowClass(Interruption::class); - - $assert->whenCalled( - () ==> { - $listener = $this->skipListeners->at(0); - $listener(Skip::fromCallStack('fake failure')); - }, - )->willThrowClass(Interruption::class); - } - - <> - public function listenersArePassedToAssertBuilder(Assert $assert): void { - $failure = ($event) ==> { - }; - $skip = ($event) ==> { - }; - $success = ($event) ==> { - }; - - $this->runner->onFailure($failure); - $this->runner->onSkip($skip); - $this->runner->onSuccess($success); - - $this->runner->run(Vector {new SpySuite()}); - - $assert->int($this->failureListeners->count())->eq(2); - $assert->int($this->skipListeners->count())->eq(2); - $assert->int($this->successListeners->count())->eq(1); - - // This also implicitly tests that the interruption handlers are added at the end - $assert->mixed($this->failureListeners->at(0))->identicalTo($failure); - $assert->mixed($this->skipListeners->at(0))->identicalTo($skip); - $assert->mixed($this->successListeners->at(0))->identicalTo($success); - } - - <> - public function testPassListenersAreRun(Assert $assert): void { - $this->runner->onPass( - ($e) ==> { - $this->testsPassed++; - }, - ); - - $suite = new SpySuite(); - $this->runner->run(Vector {$suite}); - - $assert->int($suite->passCallbacks->count())->eq(1); - $passCallback = $suite->passCallbacks->at(0); - - $assert->int($this->testsPassed)->eq(0); - $passCallback(); - $assert->int($this->testsPassed)->eq(1); - } - - <> - public function unexpectedExceptionIsHandled(Assert $assert): void { - $this->runner->onUncaughtException( - $e ==> { - $this->uncaughtExceptions->add($e); - }, - ); - - $exception = new \Exception('With a message'); - $suite = new SpySuite( - () ==> { - throw $exception; - }, - ); - - $assert->whenCalled( - () ==> { - $this->runner->run(Vector {$suite}); - }, - )->willNotThrow(); - - $assert->container($this->uncaughtExceptions) - ->containsOnly(Vector {$exception}); - $assert->int($suite->counts['up'])->eq(1); - $assert->int($suite->counts['run'])->eq(1); - $assert->int($suite->counts['down'])->eq(1); - } -} diff --git a/test/Test/Suite.php b/test/Test/Suite.php deleted file mode 100644 index c57949c..0000000 --- a/test/Test/Suite.php +++ /dev/null @@ -1,320 +0,0 @@ - $skipEvents = Vector {}; - private Vector $testStartEvents = Vector {}; - - private (function(): Awaitable) $factory; - private TraceItem $traceItem; - - public function __construct() { - $this->factory = async () ==> { - $this->factoryRuns++; - return $this; - }; - $this->traceItem = Trace::buildItem([]); - } - - <> - public function dataConsumerTest(Assert $assert): void { - $testMethod = async ($instance, $args) ==> { - $this->testRuns++; - $assert->mixed($instance)->identicalTo($this); - $assert->int(count($args))->eq(2); - $assert->mixed($args[0])->isTypeOf(Assert::class); - $assert->mixed($args[1])->identicalTo($this->testRuns); - }; - $test = shape( - 'name' => '', - 'suite name' => '', - 'factory' => $this->factory, - 'method' => $testMethod, - 'trace item' => $this->traceItem, - 'skip' => false, - 'data provider' => async () ==> { - yield [1]; - yield [2]; - }, - ); - $suite = new Suite( - '', - Vector {$test}, - Vector {}, - Vector {}, - Vector {}, - Vector {}, - ); - - $assert->whenCalled(() ==> $this->runSuite($suite))->willNotThrow(); - $assert->int($this->passedEvents)->eq(2); - $assert->int($this->testRuns)->eq(2); - } - - <> - public function unexpectedExceptionTest(Assert $assert): void { - $tests = Vector { - $this->makePassingTest($assert), - $this->makeUnexpectedExceptionTest(), - $this->makePassingTest($assert), - }; - $suite = new Suite( - '', - $tests, - Vector {}, - Vector {}, - Vector {$this->makeTestUp($assert)}, - Vector {$this->makeTestDown($assert)}, - ); - - $assert->whenCalled(() ==> $this->runSuite($suite)) - ->willThrowMessage('This is the message'); - $assert->int($this->passedEvents)->eq(2); - $assert->int($this->testUpRuns)->eq(3); - $assert->int($this->testDownRuns)->eq(2); - } - - <> - public function suiteTests(Assert $assert): void { - foreach (range(0, 3) as $thirdTestCount) { - - $tests = Vector {}; - for ($i = 0; $i < $thirdTestCount; $i++) { - $tests->add($this->makeInterruptedTest()); - $tests->add($this->makeSkippedTest($assert)); - $tests->add($this->makePassingTest($assert)); - } - $this->runTests($assert, $tests); - } - } - - private function runTests(Assert $assert, Vector $tests): void { - $thirdTestCount = (int) floor($tests->count() / 3); - - foreach (range(0, 2) as $upDownCount) { - $suite = new Suite( - '', - $tests, - $this->repeat($upDownCount, $this->makeSuiteUp($assert)), - $this->repeat($upDownCount, $this->makeSuiteDown($assert)), - $this->repeat($upDownCount, $this->makeTestUp($assert)), - $this->repeat($upDownCount, $this->makeTestDown($assert)), - ); - - $assert->whenCalled(() ==> $this->runSuite($suite))->willNotThrow(); - - // Test start events triggered - $assert->int($this->testStartEvents->count())->eq($tests->count()); - - // Skipped tests shouldn't run the factory - $assert->int($this->factoryRuns)->eq(2 * $thirdTestCount); - - // Skipped tests shouldn't be run - $assert->int($this->testRuns)->eq(2 * $thirdTestCount); - - // Interrupted and skipped tests shouldn't be passed - $assert->int($this->passedEvents)->eq($thirdTestCount); - - // Make sure the skip event is triggered for skipped tests - $assert->int($this->skipEvents->count())->eq($thirdTestCount); - - // Make sure the test trace item is passed to the skip event - if ($thirdTestCount > 0) { - $event = $this->skipEvents->at(0); - $assert->mixed($event->skipCallSite())->identicalTo($this->traceItem); - } - - // Test up/down should not run skipped tests, should run for interrupted tests - $assert->int($this->testUpRuns)->eq(2 * $thirdTestCount * $upDownCount); - $assert->int($this->testDownRuns) - ->eq(2 * $thirdTestCount * $upDownCount); - - // Running shouldn't trigger suite up/down - $assert->int($this->suiteUpRuns)->eq(0); - $assert->int($this->suiteDownRuns)->eq(0); - - // Should be independent of test count, and only ups are run - Asio\join($suite->up()); - $assert->int($this->suiteUpRuns)->eq($upDownCount); - $assert->int($this->suiteDownRuns)->eq(0); - - // Should be independent of test count, and only downs are run - Asio\join($suite->down()); - $assert->int($this->suiteUpRuns)->eq($upDownCount); - $assert->int($this->suiteDownRuns)->eq($upDownCount); - - $this->resetCounts(); - } - } - - private function resetCounts(): void { - $this->factoryRuns = 0; - $this->suiteUpRuns = 0; - $this->suiteDownRuns = 0; - $this->testUpRuns = 0; - $this->testDownRuns = 0; - $this->testRuns = 0; - $this->passedEvents = 0; - $this->skipEvents->clear(); - $this->testStartEvents->clear(); - } - - private function repeat(int $count, T $item): Vector { - $list = Vector {}; - $list->resize($count, $item); - return $list; - } - - private function makeTestMethod(Assert $assert): InvokerWithParams { - return async ($instance, $args) ==> { - $assert->mixed($instance)->identicalTo($this); - $assert->int(count($args))->eq(1); - $assert->mixed($args[0])->isTypeOf(Assert::class); - $this->testRuns++; - }; - } - - private function makePassingTest(Assert $assert): TestShape { - return shape( - 'name' => 'passing', - 'suite name' => '', - 'factory' => $this->factory, - 'method' => $this->makeTestMethod($assert), - 'trace item' => $this->traceItem, - 'skip' => false, - 'data provider' => async () ==> { - yield []; - }, - ); - } - - private function makeSkippedTest(Assert $assert): TestShape { - return shape( - 'name' => 'skipped', - 'suite name' => '', - 'factory' => $this->factory, - 'method' => $this->makeTestMethod($assert), - 'trace item' => $this->traceItem, - 'skip' => true, - 'data provider' => async () ==> { - yield []; - }, - ); - } - - private function makeUnexpectedExceptionTest(): TestShape { - return shape( - 'name' => 'unexpected exception', - 'suite name' => '', - 'factory' => $this->factory, - 'method' => async ($instance, $args) ==> { - $this->testRuns++; - throw new \Exception('This is the message'); - }, - 'trace item' => $this->traceItem, - 'skip' => false, - 'data provider' => async () ==> { - yield []; - }, - ); - } - - private function makeInterruptedTest(): TestShape { - return shape( - 'name' => 'interrupted', - 'suite name' => '', - 'factory' => $this->factory, - 'method' => async ($instance, $args) ==> { - $this->testRuns++; - throw new Interruption(); - }, - 'trace item' => $this->traceItem, - 'skip' => false, - 'data provider' => async () ==> { - yield []; - }, - ); - } - - private function makeSuiteUp(Assert $assert): InvokerWithParams { - return async ($instance, $params) ==> { - $this->suiteUpRuns++; - // All suite up methods are static, so no instance should be passed - $assert->mixed($instance)->isNull(); - }; - } - - private function makeSuiteDown(Assert $assert): InvokerWithParams { - return async ($instance, $params) ==> { - $this->suiteDownRuns++; - // All suite down methods are static, so no instance should be passed - $assert->mixed($instance)->isNull(); - }; - } - - private function makeTestUp(Assert $assert): InvokerWithParams { - return - async ($instance, $params) ==> { - $this->testUpRuns++; - // The test factories all return $this. Ensure it is passed to the test up methods. - $assert->mixed($instance)->identicalTo($this); - }; - } - - private function makeTestDown(Assert $assert): InvokerWithParams { - return - async ($instance, $params) ==> { - $this->testDownRuns++; - // The test factories all return $this. Ensure it is passed to the test up methods. - $assert->mixed($instance)->identicalTo($this); - }; - } - - private function runSuite(Suite $suite): void { - Asio\join( - $suite->run( - $this->makeAssert(), - () ==> { - $this->passedEvents++; - }, - Vector { - (TestStart $e) ==> { - $this->testStartEvents->add($e); - }, - }, - ), - ); - } - - private function makeAssert(): Assert { - $skipListener = ($skipEvent) ==> { - $this->skipEvents->add($skipEvent); - }; - - return new \HackPack\HackUnit\Assert( - Vector {}, - Vector {$skipListener}, - Vector {}, - ); - } -} diff --git a/test/Test/ValidParsing.php b/test/Test/ValidParsing.php deleted file mode 100644 index 3c283a9..0000000 --- a/test/Test/ValidParsing.php +++ /dev/null @@ -1,164 +0,0 @@ -> - public function validSuitesParseWithoutError(Assert $assert): void { - foreach (self::$parsersBySuiteName as $parser) { - $assert->bool($parser->errors()->isEmpty())->is(true); - } - } - - <> - public function factoryParsing(Assert $assert): void { - $factoryList = - $this->parserFromSuiteName('ConstructorIsDefaultWithNoParams') - ->factories(); - - $assert->int($factoryList->count())->eq(2); - $assert->bool($factoryList->containsKey(''))->is(true); - $assert->bool($factoryList->containsKey('named'))->is(true); - $assert->string($factoryList->at(''))->is('__construct'); - $assert->string($factoryList->at('named'))->is('factory'); - - $factoryList = - $this->parserFromSuiteName('ConstructorIsDefaultWithParams') - ->factories(); - - $assert->int($factoryList->count())->eq(2); - $assert->bool($factoryList->containsKey(''))->is(true); - $assert->bool($factoryList->containsKey('named'))->is(true); - $assert->string($factoryList->at(''))->is('__construct'); - $assert->string($factoryList->at('named'))->is('factory'); - - $factoryList = - $this->parserFromSuiteName('ConstructorIsNotDefault')->factories(); - $assert->bool($factoryList->containsKey(''))->is(true); - $assert->string($factoryList->at(''))->is('factory'); - - $factoryList = $this->parserFromSuiteName('DerivedFactory')->factories(); - $assert->bool($factoryList->containsKey(''))->is(true); - $assert->string($factoryList->at(''))->is('factory'); - - $factoryList = $this->parserFromSuiteName('AbstractFactory')->factories(); - $assert->int($factoryList->count())->eq(0); - } - - <> - public function setupParsing(Assert $assert): void { - $this->updownParsing('Setup', $assert); - } - - <> - public function teardownParsing(Assert $assert): void { - $this->updownParsing('TearDown', $assert); - } - - private function updownParsing(string $type, Assert $assert): void { - $parser = $this->parserFromSuiteName($type); - $suiteUp = $type === 'Setup' ? $parser->suiteUp() : $parser->suiteDown(); - $assert->container($suiteUp) - ->containsOnly(['suiteOnly', 'both', 'nonRequiredParam']); - - $expectedTestUp = Vector {}; - $testUp = $type === 'Setup' ? $parser->testUp() : $parser->testDown(); - $assert->container($testUp) - ->containsOnly(['both', 'testOnlyExplicit', 'testOnlyImplicit']); - } - - <> - public function testParsing(Assert $assert): void { - $parser = $this->parserFromSuiteName('Test'); - - $tests = Map::fromItems( - $parser->tests()->map($test ==> Pair {$test['method'], $test}), - ); - - $expectedTestNames = Vector { - 'defaultSuiteProvider', - 'namedSuiteProvider', - 'staticTest', - 'skippedTest', - }; - - $assert->container($tests->keys())->containsOnly($expectedTestNames); - - $defaultProvider = $tests->at('defaultSuiteProvider'); - $assert->string($defaultProvider['factory name'])->is(''); - $assert->bool($defaultProvider['skip'])->is(false); - - $defaultProvider = $tests->at('namedSuiteProvider'); - $assert->string($defaultProvider['factory name'])->is('named'); - $assert->bool($defaultProvider['skip'])->is(false); - - $defaultProvider = $tests->at('skippedTest'); - $assert->string($defaultProvider['factory name'])->is(''); - $assert->bool($defaultProvider['skip'])->is(true); - } - - <> - public function inheritedTests(Assert $assert): void { - $parser = $this->parserFromSuiteName('BaseSuite'); - $testNames = $parser->tests()->map($test ==> $test['method']); - $assert->container($testNames) - ->containsOnly(['testInsideBaseSuite', 'testInsideAbstractSuite']); - - $parser = $this->parserFromSuiteName('HasExternalSuite'); - $testNames = $parser->tests()->map($test ==> $test['method']); - $assert->container($testNames)->containsOnly( - ['testInsideBaseSuite', 'testInsideAbstractSuite', 'testInsideTrait'], - ); - } - - <> - public function abstractClassesDoNotHaveTests(Assert $assert): void { - $parser = $this->parserFromSuiteName('AbstractSuite'); - - $assert->int($parser->tests()->count())->eq(0); - } - - <> - public function validDataProvider(Assert $assert): void { - $tests = Map::fromItems( - $this->parserFromSuiteName('Data') - ->tests() - ->map($test ==> Pair {$test['method'], $test}), - ); - $assert->container($tests->keys()) - ->containsOnly(['consumesVector', 'consumesMap', 'consumesString']); - - $assert->string($tests->at('consumesVector')['data provider']) - ->is('vectorProvider'); - $assert->string($tests->at('consumesMap')['data provider']) - ->is('mapProvider'); - $assert->string($tests->at('consumesString')['data provider']) - ->is('stringProvider'); - } - - <> - public function asyncDataProvider(Assert $assert): void { - $tests = Map::fromItems( - $this->parserFromSuiteName('AsyncData') - ->tests() - ->map($test ==> Pair {$test['method'], $test}), - ); - $assert->container($tests->keys())->containsOnly(['asyncConsumer']); - - $assert->string($tests->at('asyncConsumer')['data provider']) - ->is('asyncDataProvider'); - } -} diff --git a/test/TraceItemTest.php b/test/TraceItemTest.php deleted file mode 100644 index 9aa0869..0000000 --- a/test/TraceItemTest.php +++ /dev/null @@ -1,47 +0,0 @@ -mixed($actual['line'])->isInt(); - $assert->int((int) $actual['line'])->eq($line); - } else { - $assert->mixed($actual['line'])->isNull(); - } - - if (is_string($method)) { - $assert->mixed($actual['function'])->isString(); - $assert->string((string) $actual['function'])->is($method); - } else { - $assert->mixed($actual['function'])->isNull(); - } - - if (is_string($class)) { - $assert->mixed($actual['class'])->isString(); - $assert->string((string) $actual['class'])->is($class); - } else { - $assert->mixed($actual['class'])->isNull(); - } - - if (is_string($file)) { - $assert->mixed($actual['file'])->isString(); - $assert->string((string) $actual['file'])->is($file); - } else { - $assert->mixed($actual['file'])->isNull(); - } - } -} diff --git a/test/Util/TraceTest.php b/test/Util/TraceTest.php deleted file mode 100644 index 69773bc..0000000 --- a/test/Util/TraceTest.php +++ /dev/null @@ -1,164 +0,0 @@ - { - return Vector { - 1, - 0, - -1, - true, - false, - 0.1, - 0.0, - -1.1, - [], - ['a'], - new TraceTest(), - }; - } - - private function nonInts(): Vector { - return Vector { - 'a', - 'longer string?', - true, - false, - 0.1, - 0.0, - -1.1, - [], - ['a'], - new TraceTest(), - }; - } - - <> - public function missingParamsResultsInNull(Assert $assert): void { - $raw = []; - $items = Trace::convert([$raw]); - $assert->int($items->count())->eq(1); - - $item = $items->at(0); - - $assert->mixed($item['line'])->isNull(); - $assert->mixed($item['function'])->isNull(); - $assert->mixed($item['class'])->isNull(); - $assert->mixed($item['file'])->isNull(); - } - - <> - public function lineMustBeInteger(Assert $assert): void { - foreach ($this->nonInts() as $mixed) { - $item = Trace::convert([['line' => $mixed]])->at(0); - $assert->mixed($item['line'])->isNull(); - } - foreach ([-1, 0, 1, 3] as $int) { - $item = Trace::convert([['line' => $int]])->at(0); - $assert->mixed($item['line'])->identicalTo($int); - } - } - - <> - public function functionMustBeString(Assert $assert): void { - foreach ($this->nonStrings() as $mixed) { - $item = Trace::convert([['function' => $mixed]])->at(0); - $assert->mixed($item['function'])->isNull(); - } - foreach (['', '0', '1e10', 'normal string'] as $string) { - $item = Trace::convert([['function' => $string]])->at(0); - $assert->mixed($item['function'])->identicalTo($string); - } - } - - <> - public function classMustBeString(Assert $assert): void { - foreach ($this->nonStrings() as $mixed) { - $item = Trace::convert([['class' => $mixed]])->at(0); - $assert->mixed($item['class'])->isNull(); - } - foreach (['', '0', '1e10', 'normal string'] as $string) { - $item = Trace::convert([['class' => $string]])->at(0); - $assert->mixed($item['class'])->identicalTo($string); - } - } - - <> - public function fileMustBeString(Assert $assert): void { - foreach ($this->nonStrings() as $mixed) { - $item = Trace::convert([['file' => $mixed]])->at(0); - $assert->mixed($item['file'])->isNull(); - } - foreach (['', '0', '1e10', 'normal string'] as $string) { - $item = Trace::convert([['file' => $string]])->at(0); - $assert->mixed($item['file'])->identicalTo($string); - } - } - - <> - public function assertionCallSearchFailsWhenSearchingWithoutAssertion( - Assert $assert, - ): void { - $item = Trace::findAssertionCall(); - $assert->mixed($item['line'])->isNull(); - $assert->mixed($item['function'])->isNull(); - $assert->mixed($item['class'])->isNull(); - $assert->mixed($item['file'])->isNull(); - } - - <> - public function assertionCallSearchSucceedsWhenSearchingWithAssertion( - Assert $assert, - ): void { - $mockAssert = new \HackPack\HackUnit\Tests\Doubles\Util\Assertion(); - $items = Vector {}; - $line = __LINE__ + 5; - $mockAssert->run( - () ==> { - $items->add(Trace::findAssertionCall()); - }, - ); - - $assert->int($items->count())->eq(1); - $item = $items->at(0); - - $assert->mixed($item['line'])->isInt(); - $assert->mixed($item['function'])->isString(); - $assert->mixed($item['class'])->isString(); - $assert->mixed($item['file'])->isString(); - - $assert->int((int) $item['line'])->eq($line); - $assert->string((string) $item['function'])->is(__FUNCTION__); - $assert->string((string) $item['class'])->is(__CLASS__); - $assert->string((string) $item['file'])->is(__FILE__); - } - - private function levelOne(): TraceItem { - return $this->levelTwo(); - } - - private function levelTwo(): TraceItem { - return Trace::findTestMethod(); - } - - <> - public function findTestMethod(Assert $assert): void { - $line = __LINE__ + 1; - $item = $this->levelOne(); - - $assert->mixed($item['line'])->isInt(); - $assert->mixed($item['function'])->isString(); - $assert->mixed($item['class'])->isString(); - $assert->mixed($item['file'])->isString(); - - $assert->int((int) $item['line'])->eq($line); - $assert->string((string) $item['function'])->is(__FUNCTION__); - $assert->string((string) $item['class'])->is(__CLASS__); - $assert->string((string) $item['file'])->is(__FILE__); - } -} diff --git a/test/self-test.ini b/test/self-test.ini deleted file mode 100644 index 3d3eca9..0000000 --- a/test/self-test.ini +++ /dev/null @@ -1,2 +0,0 @@ -hhvm.hack.lang.look_for_typechecker = false -hhvm.jit = false diff --git a/test/self-test.php b/test/self-test.php deleted file mode 100644 index b69635d..0000000 --- a/test/self-test.php +++ /dev/null @@ -1,48 +0,0 @@ -add(JUnitFormat::build($circleReportDir.'/report.xml')); -// } -$status = new Status(STDOUT); - -$suiteBuilder = new SuiteBuilder( - ($className, $fileName) ==> new Parser($className, $fileName), -); - -$include = Set {$root.'/test'}; -$exclude = Set { - $root.'/test/self-test.php', - $root.'/test/self-test.ini', - $root.'/test/Fixtures', - $root.'/test/Doubles', -}; -$loader = new Loader( - $class ==> $suiteBuilder->buildSuites($class), - $include, - $exclude, -); - -$runner = new Runner(class_meth(Assert::class, 'build')); - -$hackunit = - new HackUnit($reportFormatters, $status, $suiteBuilder, $loader, $runner); -$hackunit->run();