ensi/laravel-test-factories 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

ensi/laravel-test-factories

Composer 安装命令:

composer require ensi/laravel-test-factories

包简介

laravel test factories

README 文档

README

Latest Version on Packagist Tests Total Downloads

This package provides factories for typical data structures

Installation

You can install the package via composer:

composer require ensi/laravel-test-factories --dev

Version Compatibility

Laravel Test factories Laravel PHP
^0.0.1 ^8.0 ^8.0
^0.1.0 ^8.0 ^8.0
^0.2.0 ^8.0 ^8.0
^0.2.4 ^8.0 || ^9.0 || ^10.0 ^8.0
^0.2.7 ^8.0 || ^9.0 || ^10.0 || ^11.0 ^8.0
^1.0.0 ^9.0 || ^10.0 || ^11.0 ^8.1

Basic usage

Let's create a factory and extend abstract Factory. All you need is to define definition and make methods.

use Ensi\LaravelTestFactories\Factory;

class CustomerFactory extends Factory
{
    public ?int $id = null;
    public ?FileFactory $avatarFactory = null;
    public ?array $addressFactories = null;

    protected function definition(): array
    {
        return [
            'id' => $this->whenNotNull($this->id, $this->id),
            'user_id' => $this->faker->randomNumber(),
            'is_active' => $this->faker->boolean(),
            'date_start' => $this->faker->dateTime(),
            'avatar' => $this->avatarFactory?->make(),
            'addresses' => $this->executeNested($this->addressFactories, new FactoryMissingValue()),
        ];
    }

    public function make(array $extra = []): CustomerDTO
    {
        static::$index += 1;

        return new CustomerDTO($this->mergeDefinitionWithExtra($extra));
    }

    public function withId(?int $id = null): self
    {
        return $this->immutableSet('id', $id ?? $this->faker->randomNumber());
    }

    public function withAvatar(FileFactory $factory = null): self
    {
        return $this->immutableSet('avatarFactory', $factory ?? FileFactory::new());
    }

    public function includesAddresses(?array $factories = null): self
    {
        return $this->immutableSet('addressFactories', $factories ?? [CustomerAddressFactory::new()]);
    }

    public function active(): self
    {
        return $this->state([
            'is_active' => true,
            'date_start' => $this->faker->dateTimeBetween('-30 years', 'now'),
        ]);
    }
}

// Now we can use Factory like that
$customerData1 = CustomerFactory::new()->make();
$customerData2 = CustomerFactory::new()->active()->make();
$customerData3 = CustomerFactory::new()->withId()->withAvatar(FileFactory::new()->someCustomMethod())->make();

As you can see the package uses fakerphp/faker to generate test data.

You can override any fields in make method:

$customerData1 = CustomerFactory::new()->make(['user_id' => 2]);

If you target is an array, then you can use a helper method makeArray:

    public function make(array $extra = []): array
    {
        return $this->makeArray($extra);
    }

It's recommended to use $this->immutableSet in state change methods to make sure previously created factories are not affected.

Making several objects

$customerDataObjects = CustomerFactory::new()->makeSeveral(3); // returns Illuminate\Support\Collection with 3 elements

Additional Faker methods

$this->faker->randomList(fn() => $this->faker->numerify(), 0, 10) // => ['123', ..., '456']
$this->faker->nullable() // equivalent for $this->faker->optional(), but work with boolean parameter or global static setting
$this->faker->exactly($value) // return $value. Example: $this->faker->nullable()->exactly(AnotherFactory::new()->make())
$this->faker->carbon() // return CarbonInterface
$this->faker->dateMore()
$this->faker->modelId() // return unsigned bit integer value

Additional traits

WithSetPkTrait

If your model has unique index consisting of multiple fields, WithSetPkTrait trait should be used to ensure generated values for these fields are unique.

In order for trait to work, you have to define methods getPkFields, setPk and generatePk and include getPk call in definition. Following is the example of a factory ('client_id' and 'location_id' are fields forming unique index):

    class ClientAmountFactory extends BaseModelFactory
{
    use WithSetPkTrait;

    protected $model = ClientAmount::class;

    public function definition(): array
    {
        return array_merge($this->getPk(), [
            'amount' => $this->faker->numberBetween(1, 1_000_000),
        ]);
    }

    public function getPkFields(): array
    {
        return ['client_id', 'location_id'];
    }

    public function setPk(?int $clientId = null, ?string $locationId = null): self // Use in tests to define values
    {
        return $this->state(function () use ($clientId, $locationId) {
            return $this->generatePk($clientId, $locationId);
        });
    }

    protected function generatePk(?int $clientId = null, ?string $locationId = null): array
    {
        $clientIdFormat = $clientId ?: '\d{10}';
        $locationIdFormat = $locationId ?: '[0-9]{1,10}';

        $unique = $this->faker->unique()->regexify("/^{$clientIdFormat}_{$locationIdFormat}");

        $uniqueArr = explode('_', $unique);

        return [
            'client_id' => (int)$uniqueArr[0],
            'location_id' => $uniqueArr[1],
        ];
    }
}

Important note - fields must be declared in the same order in getPkFields and setPk methods.

Parent classes

BaseApiFactory

This class is the base for your factories of various Api responses/requests.

It also provides the generateResponseSearch method, which allows you to generate a response in the :search format of the endpoint described here

BaseModelFactory

This class is the base class for your Eloquent model factories

Factories

  • PaginationFactory - factory for generating response pieces and pagination requests
  • PromiseFactory - factory for generating GuzzleHttp\Promise\PromiseInterface

Contributing

Please see CONTRIBUTING for details.

Testing

  1. composer install
  2. composer test

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

License

The MIT License (MIT). Please see License File for more information.

ensi/laravel-test-factories 适用场景与选型建议

ensi/laravel-test-factories 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 47.99k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2023 年 03 月 14 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 ensi/laravel-test-factories 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 ensi/laravel-test-factories 我们能提供哪些服务?
定制开发 / 二次开发

基于 ensi/laravel-test-factories 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 47.99k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 6
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-03-14