Skip to content

Commit

Permalink
Feature/dependencies test trait (#405)
Browse files Browse the repository at this point in the history
* Add new Dependency_Assertions trait

* Fix linting
  • Loading branch information
anubisthejackle committed Jul 5, 2023
1 parent c91d6bb commit e833403
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions src/mantle/testing/concerns/trait-dependency-assertions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php //phpcs:disable WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
/**
* Dependency_Assertions trait file
*
* @package Mantle
*/

namespace Mantle\Testing\Concerns;

use PHPUnit\Framework\Assert as PHPUnit;
use Mantle\Support\Collection;

trait Dependency_Assertions {

/**
* Asserts that the contents of an array are loaded prior to testing.
*
* Array can be an array of strings or an array of arrays where the first value is a string -- for instance,
* a data provider.
*
* @param array $dependencies Dependencies array.
*/
public static function assertDependenciesLoaded( array $dependencies ) {
if ( count( $dependencies ) === 0 ) {
PHPUnit::markTestIncomplete( 'Asserting an empty dependency array has been loaded does not assert that no dependencies have been loaded.' );
}

foreach ( $dependencies as $dependency ) {
if ( is_array( $dependency ) ) {
$dependency = array_shift( $dependency );
}

if ( ! is_string( $dependency ) ) {
PHPUnit::fail( 'Dependency type not string.' );
continue;
}

self::assertDependencyLoaded( $dependency );
}
}

/**
* Asserts that a file is loaded.
*
* @param string $dependency The dependency file name.
*/
public static function assertDependencyLoaded( string $dependency ) {
static $includes;

if (
! is_array( $includes ) ||
empty( $includes )
) {
$includes = new Collection( get_included_files() );
}

PHPUnit::assertTrue(
$includes
->filter( fn( $file ) => strpos( $file, $dependency ) !== false )
->count() > 0,
sprintf(
'%s dependency not found in included files.',
(string) $dependency
)
);
}

}

0 comments on commit e833403

Please sign in to comment.