4

我正在 laravel 中为我的模型编写一些测试,当我使用spatie/laravel-activitylog启用活动日志时遇到了一些麻烦。

所以,我创建一个用户,使用Factory,我在系统中进行身份验证,当我尝试注销时,我得到这个错误:

1) Tests\Feature\Usuario\CriarUsuarioTest::testAcessaPaginaDeRegistro Illuminate\Database\Eloquent\JsonEncodingException:无法将模型 [Spatie\Activitylog\Models\Activity] 的属性 [properties] 编码为 JSON:不支持类型。

我的测试TestCase.php

protected function setUp()
{
    parent::setUp();
    $this->user = create('App\Models\Usuario');
    $this->singIn($this->user)
         ->disableExceptionHandling();

}

...
...
...

protected function singIn($user)
{
    $this->actingAs($user);
    return $this;
}

protected function singOut()
{
    // routeLogout() goes to '/logout' route.
    $this->post(routeLogout()); // <- Here, where the error occurs
    return $this;
}

我的App/Models/Usuario.php模型:

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Webpatser\Uuid\Uuid;
use Spatie\Activitylog\Traits\LogsActivity;

class Usuario extends Authenticatable
{
    use LogsActivity, Notifiable, SoftDeletes;
    protected $table = 'usuario';
    protected $fillable = [/*...*/] ; // I remove this to post here on SO
    protected static $logFillable = true;
    public $timestamps = true;
    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at'
    ];
    protected static function boot() 
    {
        // Handle the \LogsActivity boot method
        parent::boot();
        static::saving(function ($usuario){
            $usuario->uuid = Uuid::generate()->string;
        });
    }
    public function getRouteKeyName()
    {
        return 'uuid';
    }
}

我的config/activitylog.php文件:

return [
    'enabled' => env('ACTIVITY_LOGGER_ENABLED', true),
    'delete_records_older_than_days' => 365,
    'default_log_name' => 'default',
    'default_auth_driver' => null,
    'subject_returns_soft_deleted_models' => false,
    'activity_model' => \Spatie\Activitylog\Models\Activity::class,
];

我的phpunit.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
    <phpunit backupGlobals="false" 
             backupStaticAttributes="false" 
             bootstrap="vendor/autoload.php" 
             colors="true" 
             convertErrorsToExceptions="true" 
             convertNoticesToExceptions="true" 
             convertWarningsToExceptions="true" 
             processIsolation="false" 
             stopOnFailure="false">
                 <testsuites>
                      <testsuite name="Feature">
                           <directory suffix="Test.php">./tests/Feature</directory>
                      </testsuite>
                      <testsuite name="Unit">
                           <directory suffix="Test.php">./tests/Unit</directory>
                      </testsuite>
                 </testsuites>
                 <filter>
                    <whitelist processUncoveredFilesFromWhitelist="true">
                        <directory suffix=".php">./app</directory>
                    </whitelist>
                 </filter>
                 <php>
                    <env name="APP_ENV" value="testing"/>
                    <env name="CACHE_DRIVER" value="array"/>
                    <env name="SESSION_DRIVER" value="array"/>
                    <env name="QUEUE_DRIVER" value="sync"/>
                    <env name="API_DEBUG" value="true"/>
                    <env name="memory_limit" value="512M"/>
                    <env name="APP_DATABASE" value="test"/>
                 </php>
    </phpunit>

我的create_activity_log_migration文件:

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateActivityLogTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::create('activity_log', function (Blueprint $table) {
            $table->increments('id');
            $table->string('log_name')->nullable();
            $table->string('description');
            $table->integer('subject_id')->nullable();
            $table->string('subject_type')->nullable();
            $table->integer('causer_id')->nullable();
            $table->string('causer_type')->nullable();
            $table->text('properties')->nullable();
            $table->timestamps();

            $table->index('log_name');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::drop('activity_log');
    }
}

然后我注意到当我禁用模型的活动日志时,它工作正常。而且,当我通过修补程序或浏览器使用系统时,日志也可以正常工作。

4

2 回答 2

1

我无法重现该错误,但我确实有一些注意事项:

  • 您说当您发布到注销路线时会触发错误,但这不应该触发活动记录器,对吗?我的意思是,没有createdupdated或者deleted那里触发了事件。
  • 相反,created当您使用工厂创建用户时,确实会触发一个事件。这反过来会触发活动日志。
  • 当记录器尝试创建新的Activity时,您会得到异常Illuminate\Database\Eloquent\JsonEncodingException: Unable to encode attribute [properties] for model [Spatie\Activitylog\Models\Activity] to JSON: Type is not supported.。这几乎肯定是在方法中抛出的,该方法对属性值进行Illuminate\Database\Eloquent\Concerns\HasAttributes@castAttributeAsJson了简单的处理。json_encode
  • JSON_ERROR_UNSUPPORTED_TYPE - 向 json_encode() 提供了不受支持类型的值,例如资源。

  • 被编码的值。可以是除资源之外的任何类型。

  • 那么,资源是否有可能成为properties要记录的一部分?dd($user->attributeValuesToBeLogged('created'))在创建用户后尝试。
于 2018-01-03T13:55:42.690 回答
0

我找到了答案(但我不知道这是否是解决这个问题的最佳方法);

只需在文件中放入一个$this->createApplication();inSetUp方法,TestCase.php错误就会消失。

谢谢大家,伙计们。

于 2018-01-03T14:21:14.067 回答