Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
jarektkaczyk committed Jul 17, 2018
0 parents commit 7fd07db
Show file tree
Hide file tree
Showing 5 changed files with 277 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/coverage
/vendor
composer.lock
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2018 Jarek Tkaczyk <[email protected]>

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.
66 changes: 66 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Sofa/EloquentTestsuite

#### help yourself UNIT test Eloquent models

[![Downloads](https://poser.pugx.org/sofa/eloquent-testsuite/downloads)](https://packagist.org/packages/sofa/eloquent-testsuite) [![stable](https://poser.pugx.org/sofa/eloquent-testsuite/v/stable.svg)](https://packagist.org/packages/sofa/eloquent-testsuite)


## Usage
After you [installed](#installation) the package you can customize the thresholds publish configuration by calling:

```
$ php artisan vendor:publish --provider="Sofa\DbQueriesAlert\ServiceProvider"
```

and edit it in `config/db_queries_alert.php`:
```php
return [
'error' => 100,
'warning' => 50,
'info' => 20,
];
```


Now you're good to go. The package will call `Log::error` (or `warning|info`) whenever your app hits given threshold. Catch this error in the monitoring service you're using for the application (or simply check your local `storage/logs/laravel[-YYYY-MM-DD].log` file).


## Installation

1. Add package to your project:
```
path/to/your/app$ composer require sofa/eloquent-testsuite
```

2. Add `EloquentTestsuite` trait to your PHPUnit Test:
```php
// app/Http/Kernel.php
class SomeModelTest extends \PHPUnit\Framework\TestCase
{
use EloquentSuite;

/** @test */
public function user_belongs_to_organization()
{
$user = $this->createRelationMock(User::class, 'belongsTo', Organization::class);
$this->assertRelation('belongsTo', $user->organization());
}

/** @test */
public function user_has_many_customers()
{
// $relation is a Mockery mock
[$user, $relation] = $this->createRelationChainMock(User::class, 'hasMany', Customer::class);

$relation->shouldReceive('active')->once()->andReturnSelf();
$relation->shouldReceive('latest')->once()->andReturnSelf();

$this->assertRelation('hasMany', $user->customers());
}
}
```


#### Contribution

All contributions are welcome, PRs must be **PSR-2 compliant**.
40 changes: 40 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"name": "sofa/eloquent-testsuite",
"description": "Helpers for fast and reliable UNIT tests for your Eloquent Models with PHPUnit",
"license": "MIT",
"support": {
"issues": "https://github.com/jarektkaczyk/eloquent-testsuite/issues",
"source": "https://github.com/jarektkaczyk/eloquent-testsuite"
},
"keywords": [
"laravel",
"database",
"eloquent",
"unittest",
"unit",
"test",
"testing",
"unittesting"
],
"authors": [
{
"name": "Jarek Tkaczyk",
"email": "[email protected]",
"homepage": "https://softonsofa.com/",
"role": "Developer"
}
],
"require": {
"php": ">=7.1.0"
},
"require-dev": {
"illuminate/database": "^5.4",
"mockery/mockery" : "0.9.*|^1.0"
},
"autoload": {
"psr-4": {
"Sofa\\EloquentTestsuite\\": "src"
}
},
"minimum-stability": "stable"
}
147 changes: 147 additions & 0 deletions src/EloquentSuite.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
<?php

namespace Sofa\EloquentTestsuite;

use Mockery;
use Illuminate\Database\Eloquent\Relations;
use PHPUnit\Framework\MockObject\MockObject;

trait EloquentSuite
{
protected static $eloquent_relations = [
'hasOne' => Relations\HasOne::class,
'hasMany' => Relations\HasMany::class,
'morphTo' => Relations\MorphTo::class,
'morphOne' => Relations\MorphOne::class,
'belongsTo' => Relations\BelongsTo::class,
'morphMany' => Relations\MorphMany::class,
'morphToMany' => Relations\MorphToMany::class,
'morphedByMany' => Relations\MorphToMany::class,
'belongsToMany' => Relations\BelongsToMany::class,
'hasManyThrough' => Relations\HasManyThrough::class,
];

/**
* Prepare partial mock of Eloquent model with specified relation.
* It sets expectation and returns the mock. Assertion should be made next:
*
* ```php
* // MyModel - very simple relation, no customization, no query methods chained:
* public function someRelation()
* {
* return $this->belongsTo(RelatedModel::class);
* }
* // test
* $model = $this->createRelationMock(MyModel::class, 'belongsTo', RelatedModel::class);
* $this->assertRelation('belongsTo', $model->someRelation());
*
*
* // MyModel - customization on the relation:
* public function someRelation()
* {
* return $this->belongsTo(RelatedModel::class, 'custom_fk', 'custom_pk');
* }
* // test
* $model = $this->createRelationMock(MyModel::class, 'belongsTo', RelatedModel::class, 'custom_fk', 'custom_pk');
* $this->assertRelation('belongsTo', $model->someRelation());
* ```
*
* @param string $model Classname of the model under test
* @param string $relation Relation method (belongsTo, hasMany etc)
* @param string $related Classname of the related model
* @param ...string $params Optional params for the relation
* @return \PHPUnit\Framework\MockObject\MockObject[]
*/
public function createRelationMock(string $model, string $relation, string $related, ...$params) : MockObject
{
return $this->createRelationChainMock($model, $relation, $related, ...$params)[0];
}

/**
* Prepare partial mock of Eloquent model with specified relation.
* It sets expectation and returns the mock. Actual relation method should be called next.
* Returns array [$model, $relation_query] to assert against chained method on the relation.
*
* ```php
* // MyModel - chained query methods:
* public function someRelation()
* {
* return $this->belongsTo(RelatedModel::class)->where('active', true)->latest();
* }
* // test
*
* // $model will be PHPUnit's own \PHPUnit\Framework\MockObject\MockObject which suits our requirement for this test.
* // $relation will be \Mockery\MockInterface as this is what works best to make assertions on eloquent magic.
* [$model, $relation] = $this->createRelationChainMock(MyModel::class, 'belongsTo', RelatedModel::class);
*
* $relation->shouldReceive('where')->once()->with('active', true)->andReturnSelf();
* $relation->shouldReceive('latest')->once()->andReturnSelf();
*
* $this->assertRelation('belongsTo', $model->someRelation());
* ```
*
* @param string $model Classname of the model under test
* @param string $relation Relation method (belongsTo, hasMany etc)
* @param string $related Classname of the related model
* @param ...string $params Optional params for the relation
* @return [\PHPUnit\Framework\MockObject\MockObject, \Mockery\MockInterface]
*/
public function createRelationChainMock(string $model, string $relation, string $related, ...$params) : array
{
if (!array_key_exists($relation, self::$eloquent_relations)) {
$this->fail('Unknown relation provided: ' . $relation);
}

// Here we create partial mock of the model in order to fake only the built-in relation
// method. This will let us test our own code in the model, but won't touch internal
// implementation of the framework. The latter slows down and makes tests brittle.
$model_mock = $this->createPartialMock($model, [$relation]);
$relation_mock = Mockery::mock(self::$eloquent_relations[$relation]);

// We don't expect any custom params for the relation. Eloquent will use defaults.
if (empty($params)) {
$model_mock->expects($this->once())
->method($relation)
->with($related, $this->isEmpty()) // don't expect any parameters
->willReturn($relation_mock);
}

// Custom relation params were passed, so we set expectation against them:
else {
$model_mock->expects($this->once())
->method($relation)
->with($related, ...$params)
->willReturn($relation_mock);
}

return [$model_mock, $relation_mock];
}

/**
* Assert that Eloquent relation is defined as expected on the model.
*
* @param string $relation
* @param \Illuminate\Database\Eloquent\Relations\Relation $actual
* @param string $message
* @return void
*/
public static function assertRelation(string $relation, Relations\Relation $actual, $message = '')
{
if (array_key_exists($relation, self::$eloquent_relations)) {
$relation = self::$eloquent_relations[$relation];
}

if (!in_array($relation, self::$eloquent_relations)) {
self::fail('Unknown relation provided: ' . $relation);
}

self::assertInstanceOf(
$relation,
$actual,
$message ?: 'Possible reasons:' .
' relation not defined on the model,' .
' unexpected query methods chained on relation object,' .
' missing return statement.'
);
}
}

0 comments on commit 7fd07db

Please sign in to comment.