er\Container;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Support\Facades\Facade;
use Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Rules\Can;
use Illuminate\Validation\ValidationServiceProvider;
use Illuminate\Validation\Validator;
use PHPUnit\Framework\TestCase;
use stdClass;

class ValidationRuleCanTest extends TestCase
{
    protected $container;
    protected $user;
    protected $router;

    protected function setUp(

turn new Gate($this->container, function () {
                return $this->user;
            });
        });

        $this->container->bind('translator', function () {
            return new Translator(
                new ArrayLoader, 'en'
            )

): void
    {
        parent::setUp();

        $this->user = new stdClass;

        Container::setInstance($this->container = new Container);

        $this->container->singleton(GateContract::class, function () {
            re


Translation\Translator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;
use PHPUnit\Framework\TestCase;

include_once 'Enums.php';

class ValidationRuleContainsTest extends TestCase
{
    public function testItCorrectlyFormatsAStringVersionOfTheRule()
    {
        $rule = Rule::contains('Taylor');
        $this->assertSame('contains:"Taylor"', (string) $rule);

        $rule = Rule::contains('Taylor', 'Abigail');
        $this->assertSame('contains:"Taylor","Abigail"', (string) $rule);

ns:"Taylor","Abigail"', (string) $rule);

        $rule = Rule::contains([ArrayKeys::key_1, ArrayKeys::key_2]);
        $this->assertSame('contains:"key_1","key_2"', (string) $rule);

        $rule = Rule::contains([ArrayKeysBacked::key_1, ArrayKeysBacked:

        $rule = Rule::contains(['Taylor', 'Abigail']);
        $this->assertSame('contains:"Taylor","Abigail"', (string) $rule);

        $rule = Rule::contains(collect(['Taylor', 'Abigail']));
        $this->assertSame('contai


Translation\Translator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;
use PHPUnit\Framework\TestCase;

include_once 'Enums.php';

class ValidationRuleDoesntContainTest extends TestCase
{
    public function testItCorrectlyFormatsAStringVersionOfTheRule()
    {
        $rule = Rule::doesntContain('Taylor');
        $this->assertSame('doesnt_contain:"Taylor"', (string) $rule);

        $rule = Rule::doesntContain('Taylor', 'Abigail');
        $this->assertSame('doesnt_contain:"Taylor","

gail']));
        $this->assertSame('doesnt_contain:"Taylor","Abigail"', (string) $rule);

        $rule = Rule::doesntContain([ArrayKeys::key_1, ArrayKeys::key_2]);
        $this->assertSame('doesnt_contain:"key_1","key_2"', (string) $rule);

        $rul

Abigail"', (string) $rule);

        $rule = Rule::doesntContain(['Taylor', 'Abigail']);
        $this->assertSame('doesnt_contain:"Taylor","Abigail"', (string) $rule);

        $rule = Rule::doesntContain(collect(['Taylor', 'Abi


            'name' => Rule::when($isAdmin, ['required', 'min:2']),
            'email' => Rule::unless($isAdmin, ['required', 'min:2']),
            'password' => Rule::when($isAdmin, 'required|min:2'),
            'username' => ['required', Rule::when($isAdmin, ['min:2'])],
            'address' => ['required', Rule::unless($isAdmin, ['min:2'])],
            'city' => ['required', Rule::when(function (Fluent $input) {
                return true;
            }, ['min:2'])],
            'state' => ['requir

 })],
            'when_cb_true' => Rule::when(fn () => true, ['required'], ['nullable']),
            'when_cb_false' => Rule::when(fn () => false, ['required'], ['nullable']),
            'unless_cb_true' => Rule::unless(fn () => true, ['required'], ['nu

ed', Rule::when($isAdmin, function (Fluent $input) {
                return 'min:2';
            })],
            'zip' => ['required', Rule::when($isAdmin, function (Fluent $input) {
                return ['min:2'];


e Illuminate\Validation\Validator;
use PHPUnit\Framework\TestCase;

class ValidationStringRuleTest extends TestCase
{
    public function testDefaultStringRule()
    {
        $rule = Rule::string();
        $this->assertSame('string', (string) $rule);

        $rule = new StringRule();
        $this->assertSame('string', (string) $rule);
    }

    public function testMinRule()
    {
        $rule = Rule::string()->min(3);
        $this->assertSame('string|min:3', (string) $rule);
    }

    public functio

    $this->assertSame('string|between:3,255', (string) $rule);
    }

    public function testExactlyRule()
    {
        $rule = Rule::string()->exactly(10);
        $this->assertSame('string|size:10', (string) $rule);
    }

    public function testAlpha

n testMaxRule()
    {
        $rule = Rule::string()->max(255);
        $this->assertSame('string|max:255', (string) $rule);
    }

    public function testBetweenRule()
    {
        $rule = Rule::string()->between(3, 255);


TestCase;

class ValidationUniqueRuleTest extends TestCase
{
    protected function setUp(): void
    {
        $db = new DB;
        $db->addConnection([
            'driver' => 'sqlite',
            'database' => ':memory:',
        ]);

        $db->bootEloquent();
        $this->createSchema();
    }

    public function testItCorrectlyFormatsAStringVersionOfTheRule()
    {
        $rule = new Unique('table');
        $rule->where('foo', 'bar');
        $this->assertSame('unique:table,NULL,NULL,id,foo,"

bleName::class);
        $rule->where('foo', 'bar');
        $this->assertSame('unique:no_table_names,NULL,NULL,id,foo,"bar"', (string) $rule);

        $rule = new Unique('Illuminate\Tests\Validation\NoTableName');
        $rule->where('foo', 'bar');

bar"', (string) $rule);

        $rule = new Unique(EloquentModelStub::class);
        $rule->where('foo', 'bar');
        $this->assertSame('unique:table,NULL,NULL,id,foo,"bar"', (string) $rule);

        $rule = new Unique(NoTa


Rules\Date;
use Illuminate\Validation\Validator;
use PHPUnit\Framework\TestCase;

class ValidationDateRuleTest extends TestCase
{
    public function testDefaultDateRule()
    {
        $rule = Rule::date();
        $this->assertSame('date', (string) $rule);

        $rule = new Date;
        $this->assertSame('date', (string) $rule);
    }

    public function testDateFormatRule()
    {
        $rule = Rule::date()->format('d/m/Y');
        $this->assertSame('date_format:d/m/Y', (string) $rule);
    }

|after_or_equal:today', (string) $rule);
    }

    public function testBeforeTodayRule()
    {
        $rule = Rule::date()->beforeToday();
        $this->assertSame('date|before:today', (string) $rule);

        $rule = Rule::date()->todayOrBefore();

 public function testAfterTodayRule()
    {
        $rule = Rule::date()->afterToday();
        $this->assertSame('date|after:today', (string) $rule);

        $rule = Rule::date()->todayOrAfter();
        $this->assertSame('date


ation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Dimensions;
use Illuminate\Validation\Validator;
use PHPUnit\Framework\TestCase;

class ValidationDimensionsRuleTest extends TestCase
{
    public function testItCorrectlyFormatsAStringVersionOfTheRule()
    {
        $rule = new Dimensions(['min_width' => 100, 'min_height' => 100]);

        $this->assertSame('dimensions:min_width=100,min_height=100', (string) $rule);

        $rule = R

ame('dimensions:max_width=1000,max_height=500,ratio=1.5', (string) $rule);

        $rule = new Dimensions(['ratio' => '2/3']);

        $this->assertSame('dimensions:ratio=2/3', (string) $rule);

        $rule = Rule::dimensions()->minWidth(300)->minHeigh

ule::dimensions()->width(200)->height(100);

        $this->assertSame('dimensions:width=200,height=100', (string) $rule);

        $rule = Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2);

        $this->assertS


ator;
use PHPUnit\Framework\TestCase;

class ValidationExceptionTest extends TestCase
{
    public function testExceptionSummarizesZeroErrors()
    {
        $exception = $this->getException([], []);

        $this->assertSame('The given data was invalid.', $exception->getMessage());
    }

    public function testExceptionSummarizesOneError()
    {
        $exception = $this->getException([], ['foo' => 'required']);

        $this->assertSame('validation.required', $exception->getMessage());
    }

    pub

essage());
    }

    public function testExceptionSummarizesThreeOrMoreErrors()
    {
        $exception = $this->getException([], [
            'foo' => 'required',
            'bar' => 'required',
            'baz' => 'required',
        ]);

        $t

lic function testExceptionSummarizesTwoErrors()
    {
        $exception = $this->getException([], ['foo' => 'required', 'bar' => 'required']);

        $this->assertSame('validation.required (and 1 more error)', $exception->getM


Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\ExcludeUnless;
use Illuminate\Validation\Validator;
use PHPUnit\Framework\TestCase;

class ValidationExcludeUnlessRuleTest extends TestCase
{
    protected Translator $translator;

    protected function setUp(): void
    {
        parent::setUp();

        $this->translator = new Translator(new ArrayLoader, 'en');
    }

    public function testInstanceOf()
    {

 }

    public function testBooleanConditionFalse()
    {
        $rule = Rule::excludeUnless(false);
        $this->assertSame('exclude', (string) $rule);
    }

    public function testClosureConditionTrue()
    {
        $rule = Rule::excludeUnless(fn (

  $this->assertInstanceOf(ExcludeUnless::class, Rule::excludeUnless(true));
    }

    public function testBooleanConditionTrue()
    {
        $rule = Rule::excludeUnless(true);
        $this->assertSame('', (string) $rule);


\Validation\PresenceVerifierInterface;
use Illuminate\Validation\Validator;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class ValidationFactoryTest extends TestCase
{
    public function testMakeMethodCreatesValidValidator()
    {
        $translator = m::mock(TranslatorInterface::class);
        $factory = new Factory($translator);
        $validator = $factory->make(['foo' => 'bar'], ['baz' => 'boom']);
        $this->assertEquals($translator, $validator->getTranslator());
        $this->assertEqua

        };
        $noop2 = function () {
            //
        };
        $noop3 = function () {
            //
        };
        $factory->extend('foo', $noop1);
        $factory->extendImplicit('implicit', $noop2);
        $factory->extendDependent('d

ls(['foo' => 'bar'], $validator->getData());
        $this->assertEquals(['baz' => ['boom']], $validator->getRules());

        $presence = m::mock(PresenceVerifierInterface::class);
        $noop1 = function () {
            //


Contains duplicate ID.
                ['discounts' => [['id' => 1], ['id' => 1], ['id' => 2]]],
                ['discounts' => [['id' => 1], ['id' => 2]]],
            ],
        ];

        $rules = [
            'items.*' => Rule::forEach(function () {
                return ['discounts.*.id' => 'distinct'];
            }),
        ];

        $trans = $this->getIlluminateArrayTranslator();

        $v = new Validator($trans, $data, $rules);

        $this->assertFalse($v->passes());

        $this->ass

acksCanBeRecursivelyNested()
    {
        $data = [
            'items' => [
                // Contains duplicate ID.
                ['discounts' => [['id' => 1], ['id' => 1], ['id' => 2]]],
                ['discounts' => [['id' => 1], ['id' => 2]]],

ertEquals([
            'items.0.discounts.0.id' => ['validation.distinct'],
            'items.0.discounts.1.id' => ['validation.distinct'],
        ], $v->getMessageBag()->toArray());
    }

    public function testForEachCallb


Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Validator;
use PHPUnit\Framework\TestCase;

class ValidationInArrayKeysTest extends TestCase
{
    public function testInArrayKeysValidation()
    {
        $trans = $this->getIlluminateArrayTranslator();

        // Test passes when array has at least one of the specified keys
        $v = new Validator($trans, ['foo' => ['first_key' => 'bar', 'second_key' => 'baz']], ['foo' => 'in_array_keys:first_key,thir

rray_keys:first_key,second_key']);
        $this->assertTrue($v->passes());

        // Test fails when array doesn't have any of the specified keys
        $v = new Validator($trans, ['foo' => ['first_key' => 'bar', 'second_key' => 'baz']], ['foo' => 'in_

d_key']);
        $this->assertTrue($v->passes());

        // Test passes when array has multiple of the specified keys
        $v = new Validator($trans, ['foo' => ['first_key' => 'bar', 'second_key' => 'baz']], ['foo' => 'in_a


ss ValidationInvokableRuleTest extends TestCase
{
    public function testItCanPass()
    {
        $trans = $this->getIlluminateArrayTranslator();
        $rule = new class() implements ValidationRule
        {
            public function validate($attribute, $value, $fail): void
            {
                //
            }
        };

        $validator = new Validator($trans, ['foo' => 'bar'], ['foo' => $rule]);

        $this->assertTrue($validator->passes());
        $this->assertSame([], $validator-

te($attribute, $value, $fail): void
            {
                $fail("The {$attribute} attribute is not 'foo'. Got '{$value}' instead.");
            }
        };

        $validator = new Validator($trans, ['foo' => 'bar'], ['foo' => $rule]);

>messages()->messages());
    }

    public function testItCanFail()
    {
        $trans = $this->getIlluminateArrayTranslator();
        $rule = new class() implements ValidationRule
        {
            public function valida


Illuminate\Tests\Validation\fixtures\Values;
use Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\NotIn;
use Illuminate\Validation\Validator;
use PHPUnit\Framework\TestCase;

include_once 'Enums.php';

class ValidationNotInRuleTest extends TestCase
{
    public function testItCorrectlyFormatsAStringVersionOfTheRule()
    {
        $rule = new NotIn(['Laravel', 'Framework', 'PHP']);

        $this->assertSame('not_in:"L

aravel","Framework","PHP"', (string) $rule);

        $rule = new NotIn(collect(['Taylor', 'Michael', 'Tim']));

        $this->assertSame('not_in:"Taylor","Michael","Tim"', (string) $rule);

        $rule = Rule::notIn(collect([


   $this->assertSame('numeric', (string) $rule);

        $rule = new Numeric();
        $this->assertSame('numeric', (string) $rule);
    }

    public function testBetweenRule()
    {
        $rule = Rule::numeric()->between(1, 10);
        $this->assertSame('numeric|between:1,10', (string) $rule);

        $rule = Rule::numeric()->between(1.5, 10.5);
        $this->assertSame('numeric|between:1.5,10.5', (string) $rule);
    }

    public function testDecimalRule()
    {
        $rule = Rule::numeric()->d

tRule()
    {
        $rule = Rule::numeric()->different('some_field');
        $this->assertSame('numeric|different:some_field', (string) $rule);
    }

    public function testDigitsRule()
    {
        $rule = Rule::numeric()->digits(10);
        $this-

ecimal(2, 4);
        $this->assertSame('numeric|decimal:2,4', (string) $rule);

        $rule = Rule::numeric()->decimal(2);
        $this->assertSame('numeric|decimal:2', (string) $rule);
    }

    public function testDifferen


ork\TestCase;

class ValidationPasswordRuleTest extends TestCase
{
    public function testString()
    {
        $this->fails(Password::min(3), [['foo' => 'bar'], ['foo']], [
            'validation.string',
            'validation.min.string',
        ]);

        $this->fails(Password::min(3), [1234567, 545], [
            'validation.string',
        ]);

        $this->passes(Password::min(3), ['abcd', '454qb^', '接2133手田']);
    }

    public function testMin()
    {
        $this->fails(new Password(8

', 'abcd']);
        $this->passes(new Password(8), ['88888888']);
    }

    public function testMax()
    {
        $this->fails(Password::min(2)->max(4), ['aaaaa', '11111111'], [
            'validation.max.string',
        ]);

        $this->passes(Pa

), ['a', 'ff', '12'], [
            'validation.min.string',
        ]);

        $this->fails(Password::min(3), ['a', 'ff', '12'], [
            'validation.min.string',
        ]);

        $this->passes(Password::min(3), ['333


Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\ProhibitedUnless;
use Illuminate\Validation\Validator;
use PHPUnit\Framework\TestCase;

class ValidationProhibitedUnlessRuleTest extends TestCase
{
    protected Translator $translator;

    protected function setUp(): void
    {
        parent::setUp();

        $this->translator = new Translator(new ArrayLoader, 'en');
    }

    public function testInstanceOf()
    {

ng) $rule);
    }

    public function testBooleanConditionFalse()
    {
        $rule = Rule::prohibitedUnless(false);
        $this->assertSame('prohibited', (string) $rule);
    }

    public function testClosureConditionTrue()
    {
        $rule = Rul

        $this->assertInstanceOf(ProhibitedUnless::class, Rule::prohibitedUnless(true));
    }

    public function testBooleanConditionTrue()
    {
        $rule = Rule::prohibitedUnless(true);
        $this->assertSame('', (stri


pace Illuminate\Tests\Queue\Fixtures;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class FakeSqsJobWithDeduplication implements ShouldQueue
{
    use Queueable;

    protected static $deduplicationIdFactory;

    public function handle(): void
    {
        //
    }

    /**
     * Deduplication ID method called by SqsQueue.
     *
     * @param  string  $payload
     * @param  string  $queue
     * @return string
     */
    public function deduplicationId($paylo

    /**
     * Set the callable that will be used to generate deduplication IDs.
     *
     * @param  callable|null  $factory
     * @return void
     */
    public static function createDeduplicationIdsUsing(?callable $factory = null)
    {
        stati

ad, $queue): string
    {
        return static::$deduplicationIdFactory
            ? (string) call_user_func(static::$deduplicationIdFactory, $payload, $queue)
            : hash('sha256', json_encode(func_get_args()));
    }


authorizedHttpException;

class AuthGuardTest extends TestCase
{
    public function testBasicReturnsNullOnValidAttempt()
    {
        [$session, $provider, $request, $cookie] = $this->getMocks();
        $guard = m::mock(SessionGuard::class.'[check,attempt]', ['default', $provider, $session]);
        $guard->shouldReceive('check')->once()->andReturn(false);
        $guard->shouldReceive('attempt')->once()->with(['email' => 'foo@bar.com', 'password' => 'secret'])->andReturn(true);
        $request = Reque

oggedIn()
    {
        [$session, $provider, $request, $cookie] = $this->getMocks();
        $guard = m::mock(SessionGuard::class.'[check]', ['default', $provider, $session]);
        $guard->shouldReceive('check')->once()->andReturn(true);
        $guard

st::create('/', 'GET', [], [], [], ['PHP_AUTH_USER' => 'foo@bar.com', 'PHP_AUTH_PW' => 'secret']);
        $guard->setRequest($request);

        $guard->basic('email');
    }

    public function testBasicReturnsNullWhenAlreadyL


asters\AblyBroadcaster;
use Illuminate\Http\Request;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

class AblyBroadcasterTest extends TestCase
{
    /**
     * @var \Illuminate\Broadcasting\Broadcasters\AblyBroadcaster
     */
    public $broadcaster;

    public $ably;

    protected function setUp(): void
    {
        parent::setUp();

        $this->ably = m::mock(AblyRest::class, ['abcd:efgh']);

        $this->broadcaster = m::m

 {
            return true;
        });

        $this->broadcaster->shouldReceive('validAuthenticationResponse')
            ->once();

        $this->broadcaster->auth(
            $this->getMockRequestWithUserForChannel('private-test')
        );
    }

ock(AblyBroadcaster::class, [$this->ably])->makePartial();
    }

    public function testAuthCallValidAuthenticationResponseWithPrivateChannelWhenCallbackReturnTrue()
    {
        $this->broadcaster->channel('test', function ()


EMAIL = 'email';
    case URL = 'url';
}

class ValidationAnyOfRuleTest extends TestCase
{
    private array $taggedUnionRules;
    private array $dotNotationNestedRules;
    private array $nestedRules;

    public function testBasicValidation()
    {
        $rule = Rule::anyOf([
            ['required', 'uuid:4'],
            ['required', 'email'],
        ]);
        $idRule = ['id' => $rule];
        $requiredIdRule = ['id' => ['required', $rule]];

        $validator = new Validator(resolve('translator

passes());

        $validator = new Validator(resolve('translator'), [], $requiredIdRule);
        $this->assertFalse($validator->passes());

        $validator = new Validator(resolve('translator'), [
            'id' => '3c8ff5cb-4bc1-457b-a477-1833c477

'), [
            'id' => 'taylor@laravel.com',
        ], $idRule);
        $this->assertTrue($validator->passes());

        $validator = new Validator(resolve('translator'), [], $idRule);
        $this->assertTrue($validator->


 must be a valid email address.']
        );

        $this->fails(
            Rule::email(),
            'foo',
            ['The '.self::ATTRIBUTE_REPLACED.' must be a valid email address.']
        );

        $this->fails(
            Email::default(),
            12345,
            ['The '.self::ATTRIBUTE_REPLACED.' must be a valid email address.']
        );

        $this->fails(
            Rule::email(),
            12345,
            ['The '.self::ATTRIBUTE_REPLACED.' must be a valid email addres

es(
            Rule::email(),
            ['taylor@laravel.com'],
        );

        $this->passes(
            Email::default(),
            ['taylor@laravel.com'],
        );

        $this->passes(Email::default(), null);

        $this->passes(Rule::

s.']
        );

        $this->passes(
            Email::default(),
            'taylor@laravel.com'
        );

        $this->passes(
            Rule::email(),
            'taylor@laravel.com'
        );

        $this->pass


Exception;
use Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Rules\ExcludeIf;
use Illuminate\Validation\Validator;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use stdClass;

class ValidationExcludeIfTest extends TestCase
{
    public function testItReturnsStringVersionOfRuleWhenCast()
    {
        $rule = new ExcludeIf(function () {
            return true;
        });

        $this->assertSame('exclude', (string) $rule);

        $r

 new ExcludeIf(false);

        $this->assertSame('', (string) $rule);
    }

    public function testItValidatesCallableAndBooleanAreAcceptableArguments()
    {
        new ExcludeIf(false);
        new ExcludeIf(true);
        new ExcludeIf(fn () => true

ule = new ExcludeIf(function () {
            return false;
        });

        $this->assertSame('', (string) $rule);

        $rule = new ExcludeIf(true);

        $this->assertSame('exclude', (string) $rule);

        $rule =


on\Validator;
use PHPUnit\Framework\TestCase;

class ValidationFileRuleTest extends TestCase
{
    public function testBasic()
    {
        $this->fails(
            File::default(),
            'foo',
            ['validation.file'],
        );

        $this->passes(
            File::default(),
            UploadedFile::fake()->create('foo.bar'),
        );

        $this->passes(File::default(), null);
    }

    protected function fails($rule, $values, $messages)
    {
        $this->assertValidationR

ew Validator(
                resolve('translator'),
                ['my_file' => $value],
                ['my_file' => is_object($rule) ? clone $rule : $rule]
            );

            $this->assertSame($result, $v->passes());

            $this->asse

ules($rule, $values, false, $messages);
    }

    protected function assertValidationRules($rule, $values, $result, $messages)
    {
        $values = Arr::wrap($values);

        foreach ($values as $value) {
            $v = n


Illuminate\Tests\Validation\fixtures\Values;
use Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\In;
use Illuminate\Validation\Validator;
use PHPUnit\Framework\TestCase;

include_once 'Enums.php';

class ValidationInRuleTest extends TestCase
{
    public function testItCorrectlyFormatsAStringVersionOfTheRule()
    {
        $rule = new In(['Laravel', 'Framework', 'PHP']);

        $this->assertSame('in:"Laravel","Fram

g', 'this is a "quote"']);

        $this->assertSame('in:"Life, the Universe and Everything","this is a ""quote"""', (string) $rule);

        $rule = Rule::in(collect([1, 2, 3, 4]));

        $this->assertSame('in:"1","2","3","4"', (string) $rule);

ework","PHP"', (string) $rule);

        $rule = new In(collect(['Taylor', 'Michael', 'Tim']));

        $this->assertSame('in:"Taylor","Michael","Tim"', (string) $rule);

        $rule = new In(['Life, the Universe and Everythin


?php

namespace Illuminate\Tests\Validation;

use Illuminate\Validation\Rule;
use PHPUnit\Framework\TestCase;

class ValidationMacroTest extends TestCase
{
    public function testMacroable()
    {
        // Define a phone validation macro
        Rule::macro('phone', function () {
            return 'regex:/^([0-9\s\-\+\(\)]*)$/';
        });

        $actualRule = Rule::phone();
        $this->assertSame('regex:/^([0-9\s\-\+\(\)]*)$/', $actualRule);
    }

    public function testMacroArguments()
    {

tMacroDefaultArguments()
    {
        Rule::macro('maxLength', function ($length = 255) {
            return "max:{$length}";
        });

        $actualRule = Rule::maxLength();  // No argument provided, should use default value
        $this->assertSam

       Rule::macro('maxLength', function (int $length) {
            return "max:{$length}";
        });

        $actualRule = Rule::maxLength(10);
        $this->assertSame('max:10', $actualRule);
    }

    public function tes


Exception;
use Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Rules\RequiredIf;
use Illuminate\Validation\Validator;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;

class ValidationRequiredIfTest extends TestCase
{
    public function testItClosureReturnsFormatsAStringVersionOfTheRule()
    {
        $rule = new RequiredIf(function () {
            return true;
        });

        $this->assertSame('required', (string) $rule);

        $r

e = new RequiredIf(false);

        $this->assertSame('', (string) $rule);
    }

    public function testItOnlyCallableAndBooleanAreAcceptableArgumentsOfTheRule()
    {
        $rule = new RequiredIf(false);

        $rule = new RequiredIf(true);

ule = new RequiredIf(function () {
            return false;
        });

        $this->assertSame('', (string) $rule);

        $rule = new RequiredIf(true);

        $this->assertSame('required', (string) $rule);

        $rul


e\Contracts\Auth\PasswordBroker as PasswordBrokerContract;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Support\Arr;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use UnexpectedValueException;

class AuthPasswordBrokerTest extends TestCase
{
    public function testIfUserIsNotFoundErrorRedirectIsReturned()
    {
        $mocks = $this->getMocks();
        $broker = m::mock(PasswordBroker::class, array_values($mocks))->makePartial();
        $broker->shouldReceive('getUser')->once()->andRet

oker = m::mock(PasswordBroker::class, array_values($mocks))->makePartial();
        $mocks['users']->shouldReceive('retrieveByCredentials')->once()->with(['foo'])->andReturn($user = m::mock(CanResetPassword::class));
        $mocks['tokens']->shouldReceive

urnNull();

        $this->assertSame(PasswordBrokerContract::INVALID_USER, $broker->sendResetLink(['credentials']));
    }

    public function testIfTokenIsRecentlyCreated()
    {
        $mocks = $this->getMocks();
        $br


onent\HttpKernel\Exception\AccessDeniedHttpException;

class PusherBroadcasterTest extends TestCase
{
    /**
     * @var \Illuminate\Broadcasting\Broadcasters\PusherBroadcaster
     */
    public $broadcaster;

    public $pusher;

    protected function setUp(): void
    {
        parent::setUp();

        $this->pusher = m::mock('Pusher\Pusher');
        $this->broadcaster = m::mock(PusherBroadcaster::class, [$this->pusher])->makePartial();
    }

    public function testAuthCallValidAuthenticationRespon

   ->once();

        $this->broadcaster->auth(
            $this->getMockRequestWithUserForChannel('private-test')
        );
    }

    public function testAuthThrowAccessDeniedHttpExceptionWithPrivateChannelWhenCallbackReturnFalse()
    {
        $this-

seWithPrivateChannelWhenCallbackReturnTrue()
    {
        $this->broadcaster->channel('test', function () {
            return true;
        });

        $this->broadcaster->shouldReceive('validAuthenticationResponse')


viceProvider;
use Illuminate\Validation\Validator;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

include_once 'Enums.php';

class ValidationEnumRuleTest extends TestCase
{
    public function testValidationPassesWhenPassingCorrectEnum()
    {
        $v = new Validator(
            resolve('translator'),
            [
                'status' => 'pending',
                'int_status' => 1,
            ],
            [
                'status' => new Enum(StringStatus::clas

new Validator(
            resolve('translator'),
            [
                'status' => StringStatus::done,
            ],
            [
                'status' => new Enum(StringStatus::class),
            ]
        );

        $this->assertFalse($v-

s),
                'int_status' => new Enum(IntegerStatus::class),
            ]
        );

        $this->assertFalse($v->fails());
    }

    public function testValidationPassesWhenPassingInstanceOfEnum()
    {
        $v =


lation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\File;
use Illuminate\Validation\ValidationServiceProvider;
use Illuminate\Validation\Validator;
use PHPUnit\Framework\TestCase;

class ValidationImageFileRuleTest extends TestCase
{
    public function testDimensions()
    {
        $this->fails(
            File::image()->dimensions(Rule::dimensions()->width(100)->height(100)),
            UploadedFile::fake()->image('foo.png', 101, 10

   );
    }

    public function testDimensionsWithCustomImageSizeMethod()
    {
        $this->fails(
            File::image()->dimensions(Rule::dimensions()->width(100)->height(100)),
            new UploadedFileWithCustomImageSizeMethod(stream_get_meta

1),
            ['validation.dimensions'],
        );

        $this->passes(
            File::image()->dimensions(Rule::dimensions()->width(100)->height(100)),
            UploadedFile::fake()->image('foo.png', 100, 100),


nt\Factory as HttpFactory;
use Illuminate\Http\Client\Response;
use Illuminate\Validation\NotPwnedVerifier;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class ValidationNotPwnedVerifierTest extends TestCase
{
    protected function tearDown(): void
    {
        Container::setInstance(null);

        parent::tearDown();
    }

    public function testEmptyValues()
    {
        $httpFactory = m::mock(HttpFactory::class);
        $verifier = new NotPwnedVerifier($httpFactory);

        foreach (['', fa

   {
        $httpFactory = m::mock(HttpFactory::class);
        $response = m::mock(Response::class);

        $httpFactory = m::mock(HttpFactory::class);

        $httpFactory
            ->shouldReceive('withHeaders')
            ->once()
            ->

lse, 0] as $password) {
            $this->assertFalse($verifier->verify([
                'value' => $password,
                'threshold' => 0,
            ]));
        }
    }

    public function testApiResponseGoesWrong()


Exception;
use Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Rules\ProhibitedIf;
use Illuminate\Validation\Validator;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use stdClass;

class ValidationProhibitedIfTest extends TestCase
{
    public function testItReturnsStringVersionOfRuleWhenCast()
    {
        $rule = new ProhibitedIf(function () {
            return true;
        });

        $this->assertSame('prohibited', (string) $rule);

le);

        $rule = new ProhibitedIf(false);

        $this->assertSame('', (string) $rule);
    }

    public function testItValidatesCallableAndBooleanAreAcceptableArguments()
    {
        new ProhibitedIf(false);
        new ProhibitedIf(true);

        $rule = new ProhibitedIf(function () {
            return false;
        });

        $this->assertSame('', (string) $rule);

        $rule = new ProhibitedIf(true);

        $this->assertSame('prohibited', (string) $ru


Interface;
use Illuminate\Validation\DatabasePresenceVerifier;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use stdClass;

class ValidationDatabasePresenceVerifierTest extends TestCase
{
    public function testBasicCount()
    {
        $verifier = new DatabasePresenceVerifier($db = m::mock(ConnectionResolverInterface::class));
        $verifier->setConnection('connection');
        $db->shouldReceive('connection')->once()->with('connection')->andReturn($conn = m::mock(stdClass::class));
        $conn

, '=', 'value')->andReturn($builder);
        $extra = ['foo' => 'NULL', 'bar' => 'NOT_NULL', 'baz' => 'taylor', 'faz' => true, 'not' => '!admin'];
        $builder->shouldReceive('whereNull')->with('foo');
        $builder->shouldReceive('whereNotNull')->

->shouldReceive('table')->once()->with('table')->andReturn($builder = m::mock(stdClass::class));
        $builder->shouldReceive('useWritePdo')->once()->andReturn($builder);
        $builder->shouldReceive('where')->with('column'


te\Tests\Cache;

use BadMethodCallException;
use Illuminate\Cache\ArrayStore;
use Illuminate\Cache\MemoizedStore;
use Illuminate\Cache\NullStore;
use Illuminate\Cache\Repository;
use Illuminate\Contracts\Cache\Store;
use Illuminate\Support\Carbon;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class CacheMemoizedStoreTest extends TestCase
{
    public function testTouchExtendsTtl(): void
    {
        $store = new MemoizedStore('test', new Repository(new ArrayStore));

        Carbon::setTestNow($now =

cksCanBeFlushedWhenUnderlyingStoreSupportsIt(): void
    {
        $store = new MemoizedStore('test', new Repository(new ArrayStore));
        $this->assertTrue($store->flushLocks());
    }

    public function testFlushLocksThrowsWhenUnderlyingStoreDoesNo

Carbon::now());

        $store->put('foo', 'bar', 30);
        $store->touch('foo', 60);

        Carbon::setTestNow($now->addSeconds(45));

        $this->assertSame('bar', $store->get('foo'));
    }

    public function testLo


 public static function segmentsProvider()
    {
        return [
            ['', []],
            ['foo/bar', ['foo', 'bar']],
            ['foo/bar//baz', ['foo', 'bar', 'baz']],
            ['foo/0/bar', ['foo', '0', 'bar']],
        ];
    }

    public function testUrlMethod()
    {
        $request = Request::create('http://foo.com/foo/bar?name=taylor');
        $this->assertSame('http://foo.com/foo/bar', $request->url());

        $request = Request::create('http://foo.com/foo/bar/?');
        $this

/bar?name=taylor', $request->fullUrl());

        $request = Request::create('https://foo.com');
        $this->assertSame('https://foo.com', $request->fullUrl());

        $request = Request::create('https://foo.com');
        $this->assertSame('https://f

->assertSame('http://foo.com/foo/bar', $request->url());
    }

    public function testFullUrlMethod()
    {
        $request = Request::create('http://foo.com/foo/bar?name=taylor');
        $this->assertSame('http://foo.com/foo


ag;
use Illuminate\Support\ViewErrorBag;
use JsonSerializable;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

class HttpResponseTest extends TestCase
{
    public function testJsonResponsesAreConvertedAndHeadersAreSet()
    {
        $response = new Response(new ArrayableStub);
        $this->assertSame('{"foo":"bar"}', $response->getContent());
        $th

son', $response->headers->get('Content-Type'));

        $response = new Response(new ArrayableAndJsonableStub);
        $this->assertSame('{"foo":"bar"}', $response->getContent());
        $this->assertSame('application/json', $response->headers->get('Con

is->assertSame('application/json', $response->headers->get('Content-Type'));

        $response = new Response(new JsonableStub);
        $this->assertSame('foo', $response->getContent());
        $this->assertSame('application/j


k\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
use PHPUnit\Framework\TestCase;

/**
 * @link https://www.php.net/manual/en/function.gd-info.php
 */
#[RequiresPhpExtension('gd')]
class HttpTestingFileFactoryTest extends TestCase
{
    public function testImagePng()
    {
        if (! $this->isGDSupported('PNG Support')) {
            $this->markTestSkipped('Requires PNG support.');
        }

        $image = (new FileFactory)->image('test.png', 15, 20);

        $info = g

  if (! $this->isGDSupported('JPEG Support')) {
            $this->markTestSkipped('Requires JPEG support.');
        }

        $jpeg = (new FileFactory)->image('test.jpeg', 15, 20);
        $jpg = (new FileFactory)->image('test.jpg');

        $info = ge

etimagesize($image->getRealPath());

        $this->assertSame('image/png', $info['mime']);
        $this->assertSame(15, $info[0]);
        $this->assertSame(20, $info[1]);
    }

    public function testImageJpeg()
    {


ase;
use Symfony\Component\HttpFoundation\File\UploadedFile as SymfonyUploadedFile;

class HttpUploadedFileTest extends TestCase
{
    public function testUploadedFileCanRetrieveContentsFromTextFile()
    {
        $file = new UploadedFile(
            __DIR__.'/fixtures/test.txt',
            'test.txt',
            null,
            null,
            true
        );

        $this->assertSame('This is a story about something that happened long ago when your grandfather was a child.', trim($file->get()));

this->assertSame('', $symfonyFile->getClientOriginalPath());
        $file = UploadedFile::createFromBase($symfonyFile);
        $this->assertSame('', $file->getClientOriginalName());
        $this->assertSame('', $file->getClientOriginalPath());

    }

    public function testUploadedFileInRequestContainsOriginalPathAndName()
    {
        $symfonyFile = new SymfonyUploadedFile(__FILE__, '');
        $this->assertSame('', $symfonyFile->getClientOriginalName());
        $


nate\Database\Eloquent\Model;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\MissingValue;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class JsonResourceTest extends TestCase
{
    public function testJsonResourceNullAttributes()
    {
        $model = new class extends Model {
        };

        $model->setAttribute('relation_sum_column', null);
        $model->setAttribute('relation_count', null);
        $model->setAttribute('relation_exists', null);

        $reso

lation'));
        $this->assertNotInstanceOf(MissingValue::class, $resource->whenExistsLoaded('relation'));

        $this->assertNull($resource->whenAggregated('relation', 'column', 'sum'));
        $this->assertNull($resource->whenCounted('relation'));

urce = new JsonResource($model);

        $this->assertNotInstanceOf(MissingValue::class, $resource->whenAggregated('relation', 'column', 'sum'));
        $this->assertNotInstanceOf(MissingValue::class, $resource->whenCounted('re


nvalidArgumentException;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;

class CacheTest extends TestCase
{
    public function testItCanGenerateDefinitionViaStaticMethod()
    {
        $signature = (string) Cache::using('max_age=120;no-transform;s_maxage=60;');
        $this->assertSame('Illuminate\Http\Middleware\SetCacheHeaders:max_age=120;no-transform;s_maxage=60;', $signature);

        $signature = (strin

        'max_age=120',
            'no-transform',
            's_maxage=60',
            'etag' => true,
        ]);
        $this->assertSame('Illuminate\Http\Middleware\SetCacheHeaders:max_age=120;no-transform;s_maxage=60;etag', $signature);

        $s

g) Cache::using('max_age=120;no-transform;s_maxage=60');
        $this->assertSame('Illuminate\Http\Middleware\SetCacheHeaders:max_age=120;no-transform;s_maxage=60', $signature);

        $signature = (string) Cache::using([


esponse;

class PrefersJsonResponsesTest extends TestCase
{
    public function testItRewritesMissingAcceptHeader()
    {
        $request = Request::create('/', 'GET');
        $request->headers->remove('Accept');

        $this->runMiddleware($request);

        $this->assertSame('application/json', $request->headers->get('Accept'));
        $this->assertFalse($request->headers->has('X-Original-Accept'));
        $this->assertTrue($request->wantsJson());
        $this->assertTrue($request->expectsJson());

on/json', $request->headers->get('Accept'));
    }

    public function testItRewritesStarSlashStarAcceptHeader()
    {
        $request = Request::create('/', 'GET', [], [], [], ['HTTP_ACCEPT' => '*/*']);

        $this->runMiddleware($request);

    }

    public function testItRewritesEmptyAcceptHeader()
    {
        $request = Request::create('/', 'GET', [], [], [], ['HTTP_ACCEPT' => '']);

        $this->runMiddleware($request);

        $this->assertSame('applicati


 Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Session\Session;
use Illuminate\Foundation\Http\Middleware\PreventRequestForgery;
use Illuminate\Http\Exceptions\OriginMismatchException;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Session\TokenMismatchException;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class PreventRequestForgeryTest extends TestCase
{
    protected function tearDown(): void
    {
        PreventRequestForgery::flushState();

   $response = $middleware->handle($request, fn () => new Response('OK'));

        $this->assertSame('OK', $response->getContent());
    }

    public function test_same_site_header_rejected_by_default()
    {
        $middleware = $this->createMiddleware

     parent::tearDown();
    }

    public function test_same_origin_header_passes()
    {
        $middleware = $this->createMiddleware();
        $request = $this->createRequest(['HTTP_SEC_FETCH_SITE' => 'same-origin']);


ase
{
    /**
     * Test no zero-width space character returns the same string.
     */
    public function test_no_zero_width_space_character_returns_the_same_string()
    {
        $request = new Request;

        $request->merge([
            'title' => 'This title does not contain any zero-width space',
        ]);

        $middleware = new TrimStrings;

        $middleware->handle($request, function ($req) {
            $this->assertSame('This title does not contain any zero-width space', $req->title

est->merge([
            'title' => 'This title contains a zero-width space at the beginning',
        ]);

        $middleware = new TrimStrings;

        $middleware->handle($request, function ($req) {
            $this->assertSame('This title contains

);
        });
    }

    /**
     * Test leading zero-width space character is trimmed [ZWSP].
     */
    public function test_leading_zero_width_space_character_is_trimmed()
    {
        $request = new Request;

        $requ


st()
    {
        $req = $this->createProxiedRequest();

        $this->assertSame('192.168.10.10', $req->getClientIp(), 'Assert untrusted proxy x-forwarded-for header not used');
        $this->assertSame('http', $req->getScheme(), 'Assert untrusted proxy x-forwarded-proto header not used');
        $this->assertSame('localhost', $req->getHost(), 'Assert untrusted proxy x-forwarded-host header not used');
        $this->assertEquals(8888, $req->getPort(), 'Assert untrusted proxy x-forwarded-port header no

roxies.
     *
     * Again, this re-tests Symfony's Request class.
     */
    public function test_does_trust_trusted_proxy()
    {
        $req = $this->createProxiedRequest();
        $req::setTrustedProxies(['192.168.10.10'], $this->headerAll);

t used');
        $this->assertSame('', $req->getBaseUrl(), 'Assert untrusted proxy x-forwarded-prefix header not used');
    }

    /**
     * Test that Symfony DOES indeed trust X-Forwarded-*
     * headers when given trusted p


\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Facade;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;

class VitePreloadingTest extends TestCase
{
    protected function tearDown(): void
    {
        Facade::setFacadeApplication(null);
        Facade::clearResolvedInstances();

        parent::tearDown();
    }

    public function testItDoesNotSetLinkTagWhenNoTagsHaveBeenPreloaded()
    {
        $app = new Container;
        $app-

Request, function () {
            return new Response('Hello Laravel');
        });

        $this->assertNull($response->headers->get('Link'));
    }

    public function testItAddsPreloadLinkHeader()
    {
        $app = new Container;
        $app->ins

>instance(Vite::class, new class extends Vite
        {
            protected $preloadedAssets = [];
        });
        Facade::setFacadeApplication($app);

        $response = (new AddLinkHeadersForPreloadedAssets)->handle(new


te\Tests\Http\Resources\JsonApi;

use BadMethodCallException;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\JsonApi\JsonApiResource;
use PHPUnit\Framework\TestCase;

class JsonApiResourceTest extends TestCase
{
    protected function tearDown(): void
    {
        JsonResource::flushState();
        JsonApiResource::flushState();

        parent::tearDown();
    }

    public function testResponseWrapperIsHardCodedToData()
    {
        JsonResource::wrap('laravel');

\Http\Resources\JsonApi\JsonApiResource::wrap() method is not allowed.');

        JsonApiResource::wrap('laravel');
    }

    public function testUnableToUnsetWrapper()
    {
        $this->expectException(BadMethodCallException::class);
        $this->e

  $this->assertSame('data', JsonApiResource::$wrap);
    }

    public function testUnableToSetWrapper()
    {
        $this->expectException(BadMethodCallException::class);
        $this->expectExceptionMessage('Using Illuminate


 $this->repository = new Repository($this->config = [
            'foo' => 'bar',
            'bar' => 'baz',
            'baz' => 'bat',
            'null' => null,
            'boolean' => true,
            'integer' => 1,
            'float' => 1.1,
            'associate' => [
                'x' => 'xxx',
                'y' => 'yyy',
            ],
            'array' => [
                'aaa',
                'zzz',
            ],
            'x' => [
                'z' => 'zoo',
            ],

  'c', $this->repository->get('a.b')
        );
        $this->assertNull(
            $this->repository->get('a.b.c')
        );

        $this->assertNull($this->repository->get('x.y.z'));
        $this->assertNull($this->repository->get('.'));
    }

         'a.b' => 'c',
            'a' => [
                'b.c' => 'd',
            ],
        ]);

        parent::setUp();
    }

    public function testGetValueWhenKeyContainDot()
    {
        $this->assertSame(


nection;
use Illuminate\Redis\Connections\PredisConnection;
use Illuminate\Redis\Limiters\ConcurrencyLimiter;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class ConcurrencyLimiterTest extends TestCase
{
    public function testAcquireUsesHashTagsOnPhpRedisClusterConnection()
    {
        $connection = m::mock(PhpRedisClusterConnection::class);
        $connection->shouldReceive('isCluster')->andReturn(true);

        // acquire() calls eval → command('eval', ...) with the lock script
        $connect

 && $args[1][1] === '{test-limiter}2'
                && $args[1][2] === '{test-limiter}3'
                && $args[1][3] === '{test-limiter}'; // ARGV[1] = hash-tagged prefix
        }))->andReturn('{test-limiter}1');

        // release() also calls eval

ion->shouldReceive('command')->once()->with('eval', m::on(function ($args) {
            return str_contains($args[0], 'mget')
                && $args[2] === 3
                && $args[1][0] === '{test-limiter}1'


ption;
use Illuminate\Foundation\Testing\Concerns\InteractsWithRedis;
use Illuminate\Redis\Limiters\ConcurrencyLimiter;
use PHPUnit\Framework\TestCase;
use Throwable;

class ConcurrentLimiterTest extends TestCase
{
    use InteractsWithRedis;

    protected function setUp(): void
    {
        parent::setUp();

        $this->setUpRedis();
    }

    protected function tearDown(): void
    {
        $this->tearDownRedis();

        parent::tearDown();
    }

    public function testItLocksTasksWhenNoSlotAva

= $i;
            });
        }

        try {
            (new ConcurrencyLimiterMockThatDoesntRelease($this->redis(), 'key', 2, 5))->block(0, function () use (&$store) {
                $store[] = 3;
            });
        } catch (Throwable $e) {

ilable()
    {
        $store = [];

        foreach (range(1, 2) as $i) {
            (new ConcurrencyLimiterMockThatDoesntRelease($this->redis(), 'key', 2, 5))->block(2, function () use (&$store, $i) {
                $store[]


Illuminate\Foundation\Testing\Concerns\InteractsWithRedis;
use Illuminate\Redis\Limiters\DurationLimiter;
use PHPUnit\Framework\TestCase;
use Throwable;

class DurationLimiterTest extends TestCase
{
    use InteractsWithRedis;

    protected function setUp(): void
    {
        parent::setUp();

        $this->setUpRedis();
    }

    protected function tearDown(): void
    {
        $this->tearDownRedis();

        parent::tearDown();
    }

    public function testItLocksTasksWhenNoSlotAvailable()
    {

ction () use (&$store) {
            $store[] = 2;
        });

        try {
            (new DurationLimiter($this->redis(), 'key', 2, 2))->block(0, function () use (&$store) {
                $store[] = 3;
            });
        } catch (Throwable $e)

       $store = [];

        (new DurationLimiter($this->redis(), 'key', 2, 2))->block(0, function () use (&$store) {
            $store[] = 1;
        });

        (new DurationLimiter($this->redis(), 'key', 2, 2))->block(0, fun


r_name' => false,
        ]);

        $this->assertSame([
            'stream' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
            ],
        ], $result);
    }

    public function testNormalizeContextConvertsSslKeyToStream()
    {
        $connector = new TestablePhpRedisConnector;

        $result = $connector->testNormalizeContext([
            'ssl' => [
                'verify_peer' => false,
                'cafile' => '/path/to/ca.pem',

lizeContextPassesThroughStreamKey()
    {
        $connector = new TestablePhpRedisConnector;

        $context = [
            'stream' => [
                'verify_peer' => false,
            ],
        ];

        $result = $connector->testNormalizeCont

],
        ]);

        $this->assertSame([
            'stream' => [
                'verify_peer' => false,
                'cafile' => '/path/to/ca.pem',
            ],
        ], $result);
    }

    public function testNorma


inate\Redis\Connectors\PredisConnector;
use PHPUnit\Framework\TestCase;

class PredisConnectorTest extends TestCase
{
    public function testFormatHostLeavesConfigUnchangedWhenHostIsMissing()
    {
        $connector = new TestablePredisConnector;

        $config = ['scheme' => 'tls'];

        $this->assertSame($config, $connector->testFormatHost($config));
    }

    public function testFormatHostLeavesConfigUnchangedWhenHostHasNoScheme()
    {
        $connector = new TestablePredisConnector;

ctor = new TestablePredisConnector;

        $this->assertSame([
            'host' => '127.0.0.1',
            'scheme' => 'tls',
        ], $connector->testFormatHost([
            'host' => 'tls://127.0.0.1',
        ]));
    }

    public function test

$config = ['host' => '127.0.0.1', 'scheme' => 'tls'];

        $this->assertSame($config, $connector->testFormatHost($config));
    }

    public function testFormatHostUsesHostSchemeWhenSchemeNotConfigured()
    {
        $conne


>set('one', 'mohamed', 'EX', 5, 'NX');
            $this->assertSame('mohamed', $redis->get('one'));
            $this->assertNotEquals(-1, $redis->ttl('one'));

            // It doesn't override when NX mode
            $redis->set('one', 'taylor', 'EX', 5, 'NX');
            $this->assertSame('mohamed', $redis->get('one'));

            // It overrides when XX mode
            $redis->set('one', 'taylor', 'EX', 5, 'XX');
            $this->assertSame('taylor', $redis->get('one'));

            // It fail

ertSame('mohamed', $redis->get('three'));
            $this->assertNotEquals(-1, $redis->ttl('three'));
            $this->assertNotEquals(-1, $redis->pttl('three'));

            $redis->flushall();
        }
    }

    public function testItDeletesKeys()

s if XX mode is on and key doesn't exist
            $redis->set('two', 'taylor', 'PX', 5, 'XX');
            $this->assertNull($redis->get('two'));

            $redis->set('three', 'mohamed', 'PX', 5000);
            $this->ass


cted function tearDown(): void
    {
        $this->tearDownRedis();

        parent::tearDown();
    }

    public function testDefaultConfiguration()
    {
        $host = env('REDIS_HOST', '127.0.0.1');
        $port = env('REDIS_PORT', 6379);

        $predisClient = $this->redis['predis']->connection()->client();
        $parameters = $predisClient->getConnection()->getParameters();
        $this->assertSame('tcp', $parameters->scheme);
        $this->assertEquals($host, $parameters->host);
        $th

Client->getPort());
        $this->assertSame('default', $phpRedisClient->client('GETNAME'));
    }

    public function testUrl()
    {
        $host = env('REDIS_HOST', '127.0.0.1');
        $port = env('REDIS_PORT', 6379);

        $predis = new RedisMa

is->assertEquals($port, $parameters->port);

        $phpRedisClient = $this->redis['phpredis']->connection()->client();
        $this->assertEquals($host, $phpRedisClient->getHost());
        $this->assertEquals($port, $phpRedis


se Illuminate\Redis\Connections\PhpRedisConnection;
use Illuminate\Redis\Events\CommandExecuted;
use Illuminate\Redis\Events\CommandFailed;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use Redis;

class RedisEventsTest extends TestCase
{
    public function testCommandFailedEventIsDispatched()
    {
        $exception = new Exception('Test exception');

        $client = m::mock(Redis::class);
        $client->shouldReceive('get')->with('key')->andThrow($exception);

        $events = m::mock(Dispatche

ent->parameters === ['key']
                && $event->exception === $exception;
        }));

        $connection = new PhpRedisConnection($client);
        $connection->setEventDispatcher($events);

        $this->expectException(Exception::class);

r::class);
        $events->shouldReceive('dispatch')->once()->with(m::on(function ($event) use ($exception) {
            return $event instanceof CommandFailed
                && $event->command === 'get'
                && $ev


ndation\Application;
use Illuminate\Redis\RedisManager;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class RedisManagerExtensionTest extends TestCase
{
    /**
     * @var \Illuminate\Redis\RedisManager
     */
    protected $redis;

    protected function setUp(): void
    {
        parent::setUp();

        $this->redis = new RedisManager(new Application, 'my_custom_driver', [
            'default' => [
                'host' => 'some-host',
                'port' => 'some-port',
                'da

some-port',
                        'database' => 5,
                        'timeout' => 0.5,
                    ],
                ],
            ],
        ]);

        $this->redis->extend('my_custom_driver', function () {
            return new FakeR

tabase' => 5,
                'timeout' => 0.5,
            ],
            'clusters' => [
                'my-cluster' => [
                    [
                        'host' => 'some-host',
                        'port' => '


Connection;
use Mockery as m;
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
use PHPUnit\Framework\TestCase;

#[RequiresPhpExtension('redis')]
class PhpRedisClusterConnectionTest extends TestCase
{
    public function testItScansUsingDefaultNode()
    {
        $client = m::mock(\RedisCluster::class);
        $client->shouldReceive('_masters')->once()->andReturn([['127.0.0.1', '6379']]);
        $client->shouldReceive('scan')
            ->once()
            ->with(0, ['127.0.0.1', '6379'], '*', 10)

{
        $client = m::mock(\RedisCluster::class);
        $client->shouldReceive('_masters')->once()->andReturn([['127.0.0.1', '6379']]);
        $client->shouldReceive('scan')->twice();

        $connection = new PhpRedisClusterConnection($client);

            ->andReturn(['key']);

        $connection = new PhpRedisClusterConnection($client);
        $this->assertEquals([0, ['key']], $connection->scan(0));
    }

    public function testItOnlyFetchesDefaultNodeOnce()


Illuminate\Foundation\AliasLoader;
use PHPUnit\Framework\TestCase;

class FoundationAliasLoaderTest extends TestCase
{
    public function setUp(): void
    {
        parent::setUp();

        AliasLoader::setInstance(null);
        AliasLoader::setFacadeNamespace('Facades\\');
    }

    public function testLoaderCanBeCreatedAndRegisteredOnce()
    {
        $loader = AliasLoader::getInstance(['foo' => 'bar']);

        $this->assertEquals(['foo' => 'bar'], $loader->getAliases());
        $this->assertFals

=> 'bar']);
        $this->assertSame($loader, AliasLoader::getInstance());
    }

    public function testLoaderCanBeCreatedAndRegisteredMergingAliases()
    {
        $loader = AliasLoader::getInstance(['foo' => 'bar']);
        $this->assertEquals(['foo

e($loader->isRegistered());
        $loader->register();

        $this->assertTrue($loader->isRegistered());
    }

    public function testGetInstanceCreatesOneInstance()
    {
        $loader = AliasLoader::getInstance(['foo'


act;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
use Illuminate\Http\Middleware\PrefersJsonResponses;
use PHPUnit\Framework\TestCase;

class FoundationApplicationBuilderTest extends TestCase
{
    protected function tearDown(): void
    {
        unset($_ENV['APP_BASE_PATH'], $_ENV['LARAVEL_STORAGE_PATH'], $_SERVER['LARAVEL_STORAGE_PATH']);

        parent::tearDown();
    }

    public function testBaseDirectoryWithArg()
    {
        $_ENV['APP_BASE_PATH'] =

APP_BASE_PATH'] = __DIR__.'/as-env';

        $app = Application::configure()->create();

        $this->assertSame(__DIR__.'/as-env', $app->basePath());
    }

    public function testBaseDirectoryWithComposer()
    {
        $app = Application::configure

 __DIR__.'/as-env';

        $app = Application::configure(__DIR__.'/as-arg')->create();

        $this->assertSame(__DIR__.'/as-arg', $app->basePath());
    }

    public function testBaseDirectoryWithEnv()
    {
        $_ENV['


$config->shouldReceive('set')->once()->with('app.locale', 'foo');
        $app['translator'] = $trans = m::mock(stdClass::class);
        $trans->shouldReceive('setLocale')->once()->with('foo');
        $app['events'] = $events = m::mock(stdClass::class);
        $events->shouldReceive('dispatch')->once()->with(m::on(function (LocaleUpdated $event) {
            return $event->locale === 'foo' && $event->previousLocale === 'bar';
        }));

        $app->setLocale('foo');
    }

    public function testS

w Application;
        $app->register($provider);

        $this->assertArrayHasKey($class, $app->getLoadedProviders());
    }

    public function testClassesAreBoundWhenServiceProviderIsRegistered()
    {
        $app = new Application;
        $app->reg

erviceProvidersAreCorrectlyRegistered()
    {
        $provider = m::mock(ApplicationBasicServiceProviderStub::class);
        $class = get_class($provider);
        $provider->shouldReceive('register')->once();
        $app = ne


ts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Testing\Concerns\InteractsWithAuthentication;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class FoundationAuthenticationTest extends TestCase
{
    use InteractsWithAuthentication;

    /**
     * @var \Mockery
     */
    protected $app;

    /**
     * @var array
     */
    protected $credentials = [
        'email' => 'someone@l

uard = m::mock(Guard::class);

        $auth = m::mock(AuthManager::class);
        $auth->shouldReceive('guard')
            ->once()
            ->andReturn($guard);

        $this->app = m::mock(Application::class);
        $this->app->shouldReceive('ma

aravel.com',
        'password' => 'secret_password',
    ];

    /**
     * @return \Illuminate\Contracts\Auth\Guard|\Mockery\LegacyMockInterface|\Mockery\MockInterface
     */
    protected function mockGuard()
    {
        $g


use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use PHPUnit\Framework\TestCase;

class FoundationAuthorizesRequestsTraitTest extends TestCase
{
    protected function tearDown(): void
    {
        Container::setInstance(null);

        parent::tearDown();
    }

    public function testBasicGateCheck()
    {
        unset($_SERVER['_test.authorizes.trait']);

        $gate = $this->getBasicGate();

        $gate->define('baz', function ()

sponse);
        $this->assertTrue($_SERVER['_test.authorizes.trait']);
    }

    public function testAcceptsBackedEnumAsAbility()
    {
        unset($_SERVER['_test.authorizes.trait.enum']);

        $gate = $this->getBasicGate();

        $gate->define

 {
            $_SERVER['_test.authorizes.trait'] = true;

            return true;
        });

        $response = (new FoundationTestAuthorizeTraitClass)->authorize('baz');

        $this->assertInstanceOf(Response::class, $re


Illuminate\Contracts\Cache\Factory;
use Illuminate\Contracts\Cache\Repository;
use Illuminate\Foundation\CacheBasedMaintenanceMode;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class FoundationCacheBasedMaintenanceModeTest extends TestCase
{
    public function test_it_determines_whether_maintenance_mode_is_active()
    {
        $cache = m::mock(Factory::class, Repository::class);
        $cache->shouldReceive('store')->with('store-key')->andReturnSelf();

        $manager = new CacheBasedMaintenance

True();
        $this->assertTrue($manager->active());
    }

    public function test_it_retrieves_payload_from_cache()
    {
        $cache = m::mock(Factory::class, Repository::class);
        $cache->shouldReceive('store')->with('store-key')->andReturn

Mode($cache, 'store-key', 'key');

        $cache->shouldReceive('has')->once()->with('key')->andReturnFalse();
        $this->assertFalse($manager->active());

        $cache->shouldReceive('has')->once()->with('key')->andReturn


string|null
     */
    protected $openedUrl;

    /**
     * The command registered to the container.
     *
     * @var \Illuminate\Foundation\Console\DocsCommand
     */
    protected $command;

    protected function setUp(): void
    {
        parent::setUp();

        Http::preventStrayRequests()->fake([
            'https://laravel.com/docs/8.x/index.json' => Http::response(file_get_contents(__DIR__.'/fixtures/docs.json')),
        ]);

        $this->app[Kernel::class]->registerCommand($this->comman

Documentation(): void
    {
        $this->artisan('docs')
            ->expectsQuestion('Which page would you like to open?', '')
            ->expectsOutputToContain('Opening the docs to: https://laravel.com/docs/8.x/installation')
            ->assertSu

d());
    }

    protected function tearDown(): void
    {
        putenv('ARTISAN_DOCS_ASK_STRATEGY');
        putenv('ARTISAN_DOCS_OPEN_STRATEGY');

        parent::tearDown();
    }

    public function testItCanOpenTheLaravel


Illuminate\Foundation\EnvironmentDetector;
use PHPUnit\Framework\TestCase;

class FoundationEnvironmentDetectorTest extends TestCase
{
    public function testClosureCanBeUsedForCustomEnvironmentDetection()
    {
        $env = new EnvironmentDetector;

        $result = $env->detect(function () {
            return 'foobar';
        });
        $this->assertSame('foobar', $result);
    }

    public function testConsoleEnvironmentDetection()
    {
        $env = new EnvironmentDetector;

        $result =

 new EnvironmentDetector;

        $result = $env->detect(function () {
            return 'foobar';
        }, ['--env', 'local']);
        $this->assertSame('local', $result);
    }

    public function testConsoleEnvironmentDetectionWithNoValue()
    {

$env->detect(function () {
            return 'foobar';
        }, ['--env=local']);
        $this->assertSame('local', $result);
    }

    public function testConsoleEnvironmentDetectionSeparatedWithSpace()
    {
        $env =


{
    use InteractsWithExceptionHandling;

    protected $config;

    protected $viewFactory;

    protected $container;

    protected $handler;

    protected $request;

    protected function setUp(): void
    {
        $this->config = m::mock(Config::class);

        $this->viewFactory = m::mock(ViewFactory::class);

        $this->request = m::mock(stdClass::class);

        $this->container = Container::setInstance(new Container);

        $this->container->instance('config', $this->config);

        ));

        $this->handler = new Handler($this->container);
    }

    protected function tearDown(): void
    {
        Container::setInstance(null);

        parent::tearDown();
    }

    public function testHandlerReportsExceptionAsContext()

 $this->container->instance(ViewFactory::class, $this->viewFactory);

        $this->container->instance(ResponseFactoryContract::class, new ResponseFactory(
            $this->viewFactory,
            m::mock(Redirector::class)


Case
{
    public function testGetReturnsNullWhenNotFound()
    {
        $redis = $this->getRedis();
        $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());
        $redis->getRedis()->shouldReceive('get')->once()->with('prefix:foo')->andReturn(null);
        $this->assertNull($redis->get('foo'));
    }

    public function testRedisValueIsReturned()
    {
        $redis = $this->getRedis();
        $redis->getRedis()->shouldReceive('connection')->on

lic function testRedisMultipleValuesAreReturned()
    {
        $redis = $this->getRedis();
        $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());
        $redis->getRedis()->shouldReceive('mget')->

ce()->with('default')->andReturn($redis->getRedis());
        $redis->getRedis()->shouldReceive('get')->once()->with('prefix:foo')->andReturn(serialize('foo'));
        $this->assertSame('foo', $redis->get('foo'));
    }

    pub


lass;

class CacheRepositoryTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        Carbon::setTestNow(Carbon::parse(self::getTestDate()));
    }

    protected function tearDown(): void
    {
        Carbon::setTestNow();
        Repository::handleUnserializableClassUsing(null);

        parent::tearDown();
    }

    public function testGetReturnsValueFromCache()
    {
        $repo = $this->getRepository();
        $repo->getStore()->shouldReceive('get')->once

o->getStore()->shouldReceive('many')->once()->with(['foo', 'bar'])->andReturn(['foo' => 'bar', 'bar' => 'baz']);
        $this->assertEquals(['foo' => 'bar', 'bar' => 'baz'], $repo->get(['foo', 'bar']));
    }

    public function testGetReturnsMultipleVal

()->with('foo')->andReturn('bar');
        $this->assertSame('bar', $repo->get('foo'));
    }

    public function testGetReturnsMultipleValuesFromCacheWhenGivenAnArray()
    {
        $repo = $this->getRepository();
        $rep


TestCase;
use stdClass;

class CacheSessionStoreTest extends TestCase
{
    protected function tearDown(): void
    {
        Carbon::setTestNow();

        parent::tearDown();
    }

    public function testItemsCanBeSetAndRetrieved()
    {
        $store = new SessionStore(self::getSession());
        $result = $store->put('foo', 'bar', 10);
        $this->assertTrue($result);
        $this->assertSame('bar', $store->get('foo'));
    }

    public function testCacheTtl(): void
    {
        $store = new S

 seconds
        $this->assertSame('world', $store->get('hello'));

        Carbon::setTestNow('2000-01-01 00:00:01.500'); // progress 0.001 seconds. 1 second since putting into cache.
        $this->assertNull($store->get('hello'));
    }

    public func

essionStore(self::getSession());

        Carbon::setTestNow('2000-01-01 00:00:00.500'); // 500 milliseconds past
        $store->put('hello', 'world', 1);

        Carbon::setTestNow('2000-01-01 00:00:01.499'); // progress 0.999


n testCacheCanBeSavedWithMultipleTags()
    {
        $store = new ArrayStore;
        $tags = ['bop', 'zap'];
        $store->tags($tags)->put('foo', 'bar', 10);
        $this->assertSame('bar', $store->tags($tags)->get('foo'));
    }

    public function testCacheCanBeSetWithDatetimeArgument()
    {
        $store = new ArrayStore;
        $tags = ['bop', 'zap'];
        $duration = new DateTime;
        $duration->add(new DateInterval('PT10M'));
        $store->tags($tags)->put('foo', 'bar', $duration);

gs($tags1)->put('foo', 'bar', 10);
        $tags2 = ['bam', 'pow'];
        $store->tags($tags2)->put('foo', 'bar', 10);
        $store->tags('zap')->flush();
        $this->assertNull($store->tags($tags1)->get('foo'));
        $this->assertSame('bar', $st

        $this->assertSame('bar', $store->tags($tags)->get('foo'));
    }

    public function testCacheSavedWithMultipleTagsCanBeFlushed()
    {
        $store = new ArrayStore;
        $tags1 = ['bop', 'zap'];
        $store->ta


eoutException;
use Illuminate\Cache\Repository;
use Illuminate\Contracts\Cache\LockProvider;
use Illuminate\Contracts\Cache\Store;
use PHPUnit\Framework\TestCase;
use Throwable;

class ConcurrencyLimiterTest extends TestCase
{
    protected Repository $repository;

    protected function setUp(): void
    {
        parent::setUp();

        $this->repository = new Repository(new ArrayStore);
    }

    public function testItLocksTasksWhenNoSlotAvailable()
    {
        $store = [];

        foreach (range(1

            (new ConcurrencyLimiterMockThatDoesntRelease($this->repository->getStore(), 'key', 2, 5))->block(0, function () use (&$store) {
                $store[] = 3;
            });
        } catch (Throwable $e) {
            $this->assertInstanceOf(

, 2) as $i) {
            (new ConcurrencyLimiterMockThatDoesntRelease($this->repository->getStore(), 'key', 2, 5))->block(2, function () use (&$store, $i) {
                $store[] = $i;
            });
        }

        try {


inate\Cache\ArrayStore;
use Illuminate\Cache\RateLimiter;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Cache\Repository;
use Illuminate\Contracts\Cache\Repository as Cache;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use ReflectionProperty;

class RateLimiterTest extends TestCase
{
    public static function registerNamedRateLimiterDataProvider(): array
    {
        return [
            'uses BackedEnum' => [BackedEnumNamedRateLimiter::API, 'api'],

erDataProvider')]
    public function testRegisterNamedRateLimiter(mixed $name, string $expected): void
    {
        $reflectedLimitersProperty = new ReflectionProperty(RateLimiter::class, 'limiters');

        $rateLimiter = new RateLimiter($this->create

'uses UnitEnum' => [UnitEnumNamedRateLimiter::THIRD_PARTY, 'THIRD_PARTY'],
            'uses normal string' => ['yolo', 'yolo'],
            'uses int' => [100, '100'],
        ];
    }

    #[DataProvider('registerNamedRateLimit


RuleTest extends TestCase
{
    /**
     * Setup the database schema.
     *
     * @return void
     */
    protected function setUp(): void
    {
        $db = new DB;

        $db->addConnection([
            'driver' => 'sqlite',
            'database' => ':memory:',
        ]);

        $db->bootEloquent();
        $db->setAsGlobal();

        $this->createSchema();
    }

    public function testItCorrectlyFormatsAStringVersionOfTheRule()
    {
        $rule = new Exists('table');
        $rule->where

ing) $rule);

        $rule = new Exists(UserWithPrefixedTable::class);
        $rule->where('foo', 'bar');
        $this->assertSame('exists:'.UserWithPrefixedTable::class.',NULL,foo,"bar"', (string) $rule);

        $rule = new Exists('table', 'column');

('foo', 'bar');
        $this->assertSame('exists:table,NULL,foo,"bar"', (string) $rule);

        $rule = new Exists(User::class);
        $rule->where('foo', 'bar');
        $this->assertSame('exists:users,NULL,foo,"bar"', (str


er;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class CacheApcStoreTest extends TestCase
{
    public function testGetReturnsNullWhenNotFound()
    {
        $apc = $this->getMockBuilder(ApcWrapper::class)->onlyMethods(['get'])->getMock();
        $apc->expects($this->once())->method('get')->with('foobar')->willReturn(null);
        $store = new ApcStore($apc, 'foo');
        $this->assertNull($store->get('bar'));
    }

    public function testAPCValueIsReturned()
    {
        $apc = $this->getMock

    public function testAPCFalseValueIsReturned()
    {
        $apc = $this->getMockBuilder(ApcWrapper::class)->onlyMethods(['get'])->getMock();
        $apc->expects($this->once())->method('get')->willReturn(false);
        $store = new ApcStore($apc);

Builder(ApcWrapper::class)->onlyMethods(['get'])->getMock();
        $apc->expects($this->once())->method('get')->willReturn('bar');
        $store = new ApcStore($apc);
        $this->assertSame('bar', $store->get('foo'));
    }


$result = $store->put('foo', 'bar', 10);
        $this->assertTrue($result);
        $this->assertSame('bar', $store->get('foo'));
    }

    public function testCacheTtl(): void
    {
        $store = new ArrayStore();

        Carbon::setTestNow('2000-01-01 00:00:00.500'); // 500 milliseconds past
        $store->put('hello', 'world', 1);

        Carbon::setTestNow('2000-01-01 00:00:01.499'); // progress 0.999 seconds
        $this->assertSame('world', $store->get('hello'));

        Carbon::setTestNow('

ew ArrayStore;
        $result = $store->put('foo', 'bar', 10);
        $resultMany = $store->putMany([
            'fizz' => 'buz',
            'quz' => 'baz',
        ], 10);
        $this->assertTrue($result);
        $this->assertTrue($resultMany);

2000-01-01 00:00:01.500'); // progress 0.001 seconds. 1 second since putting into cache.
        $this->assertNull($store->get('hello'));
    }

    public function testMultipleItemsCanBeSetAndRetrieved()
    {
        $store = n


namespace Illuminate\Tests\Cache;

use Aws\DynamoDb\DynamoDbClient;
use Illuminate\Cache\DynamoDbStore;
use PHPUnit\Framework\TestCase;

class CacheDynamoDbStoreTest extends TestCase
{
    public function testTouchMethodCorrectlyCallsDynamoDb(): void
    {
        $table = 'table';
        $key = 'key';
        $ttl = 60;

        $this->assertTrue((new DynamoDbStore($dynamo = new TestDynamo, $table))->touch($key, $ttl));

        $this->assertTrue(
            isset($dynamo->args['UpdateExpression'], $dyn

Expression'], 'SET')
        );

        $this->assertTrue(
            $ttl === $dynamo->args['ExpressionAttributeValues'][':expiry']['N']
            - $dynamo->args['ExpressionAttributeValues'][':now']['N']
        );
    }
}

class TestDynamo extends D

amo->args['TableName'], $dynamo->args['Key']['key']['S'])
                && $dynamo->args['TableName'] === $table
                && $dynamo->args['Key']['key']['S'] === $key
                && str_contains($dynamo->args['Update


inate\Contracts\Cache\Store;
use Illuminate\Events\Dispatcher;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class CacheEventsTest extends TestCase
{
    public function testHasTriggersEvents()
    {
        $dispatcher = $this->getDispatcher();
        $repository = $this->getRepository($dispatcher);

        $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(RetrievingKey::class, ['storeName' => 'array', 'key' => 'foo']));
        $dispatcher->shouldReceive('dispatch')->on

EventMatches(RetrievingKey::class, ['storeName' => 'array', 'key' => 'baz']));
        $dispatcher->shouldReceive('dispatch')->once()->with($this->assertEventMatches(CacheHit::class, ['storeName' => 'array', 'key' => 'baz', 'value' => 'qux']));
        $th

ce()->with($this->assertEventMatches(CacheMissed::class, ['storeName' => 'array', 'key' => 'foo']));
        $this->assertFalse($repository->has('foo'));

        $dispatcher->shouldReceive('dispatch')->once()->with($this->assert


eption;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use stdClass;

class CacheManagerTest extends TestCase
{
    public function testCustomDriverClosureBoundObjectIsCacheManager()
    {
        $manager = new CacheManager($this->getApp([
            'cache' => [
                'stores' => [
                    __CLASS__ => [
                        'driver' => __CLASS__,
                    ],
                ],
            ],
        ]));
        $manager->extend(__CLASS__, fn () => $this);

                    __CLASS__ => [
                        'driver' => __CLASS__,
                    ],
                ],
            ],
        ]));

        $driver = new stdClass;

        $manager->extend(__CLASS__, static fn () => $driver);

$this->assertSame($manager, $manager->store(__CLASS__));
    }

    public function testCustomDriverStaticClosure()
    {
        $manager = new CacheManager($this->getApp([
            'cache' => [
                'stores' => [


use Illuminate\Contracts\Filesystem\Filesystem;

class ArrayFilesystem implements Filesystem
{
    public array $files = [];

    public function path($path)
    {
        return $path;
    }

    public function exists($path)
    {
        return array_key_exists($path, $this->files) || $this->files($path) !== [];
    }

    public function get($path)
    {
        return $this->files[$path] ?? null;
    }

    public function readStream($path)
    {
        return null;
    }

    public function put($pat

leAs($path, $file, $name = null, $options = [])
    {
        return false;
    }

    public function writeStream($path, $resource, array $options = [])
    {
        return false;
    }

    public function getVisibility($path)
    {
        return Files

h, $contents, $options = [])
    {
        $this->files[$path] = $contents;

        return true;
    }

    public function putFile($path, $file = null, $options = [])
    {
        return false;
    }

    public function putFi


ntracts\Support\Jsonable;
use Illuminate\Http\JsonResponse;
use InvalidArgumentException;
use JsonSerializable;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use stdClass;

class HttpJsonResponseTest extends TestCase
{
    #[DataProvider('setAndRetrieveDataProvider')]
    public function testSetAndRetrieveData($data)
    {
        $response = new JsonResponse($data);

        $this->assertInstanceOf(stdClass::class, $response->getData());
        $this->assertSame('bar', $re

esponseTestJsonSerializeObject],
            'Arrayable data' => [new JsonResponseTestArrayableObject],
            'Array data' => [['foo' => 'bar']],
            'stdClass data' => [(object) ['foo' => 'bar']],
        ];
    }

    public function testGe

sponse->getData()->foo);
    }

    public static function setAndRetrieveDataProvider()
    {
        return [
            'Jsonable data' => [new JsonResponseTestJsonableObject],
            'JsonSerializable data' => [new JsonR


.com' => $this->factory::response('', HttpResponse::HTTP_MOVED_PERMANENTLY),
            'forge.laravel.com' => $this->factory::response('', HttpResponse::HTTP_OK),
        ]);

        $response = $this->factory->post('http://vapor.laravel.com');
        $this->assertTrue($response->movedPermanently());

        $response = $this->factory->post('http://forge.laravel.com');
        $this->assertFalse($response->movedPermanently());
    }

    public function testNoContentRequest()
    {
        $this->facto

this->factory->post('http://vapor.laravel.com');
        $this->assertTrue($response->noContent());

        $response = $this->factory->post('http://forge.laravel.com');
        $this->assertFalse($response->noContent());
    }

    public function testFo

ry->fake([
            'vapor.laravel.com' => $this->factory::response('', HttpResponse::HTTP_NO_CONTENT),
            'forge.laravel.com' => $this->factory::response('', HttpResponse::HTTP_OK),
        ]);

        $response = $


namespace Illuminate\Tests\Cache;

use Illuminate\Cache\NullStore;
use PHPUnit\Framework\TestCase;

class CacheNullStoreTest extends TestCase
{
    public function testItemsCanNotBeCached()
    {
        $store = new NullStore;
        $store->put('foo', 'bar', 10);
        $this->assertNull($store->get('foo'));
    }

    public function testGetMultipleReturnsMultipleNulls()
    {
        $store = new NullStore;

        $this->assertEquals([
            'foo' => null,
            'bar' => null,
        ]

     $this->assertFalse($store->decrement('foo'));
    }

    public function testTouchReturnsFalse(): void
    {
        $this->assertFalse((new NullStore)->touch('foo', 30));
    }

    public function testLocksCanBeFlushed(): void
    {
        $store =

, $store->many([
            'foo',
            'bar',
        ]));
    }

    public function testIncrementAndDecrementReturnFalse()
    {
        $store = new NullStore;
        $this->assertFalse($store->increment('foo'));


rbon;
use Illuminate\Tests\Cache\Fixtures\ArrayFilesystem;
use PHPUnit\Framework\TestCase;

class CacheStorageStoreTest extends TestCase
{
    protected function tearDown(): void
    {
        Carbon::setTestNow();

        parent::tearDown();
    }

    public function testValuesCanBeStoredAndRetrieved()
    {
        $disk = new ArrayFilesystem;
        $store = new StorageStore($disk, 'cache', 'prefix:');

        $this->assertTrue($store->put('foo', 'bar', 60));
        $this->assertSame('bar', $store->

lesystem;
        $store = new StorageStore($disk, 'cache');

        $store->put('foo', 'bar', 1);

        Carbon::setTestNow(Carbon::now()->addSeconds(2));

        $this->assertNull($store->get('foo'));
        $this->assertFalse($disk->exists($store->

get('foo'));
        $this->assertStringStartsWith('cache/', $store->path('foo'));
    }

    public function testExpiredItemsReturnNullAndGetDeleted()
    {
        Carbon::setTestNow(Carbon::now());

        $disk = new ArrayFi


e\Filesystem\Filesystem;
use Illuminate\Foundation\Application;
use InvalidArgumentException;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;

class ClearCommandTest extends TestCase
{
    /**
     * @var \Illuminate\Tests\Cache\ClearCommandTestStub
     */
    private $command;

    /**
     * @var \Illuminate\Cache\CacheManager|\Mockery\MockInterface
     */
    private $cacheManager;

    /**
     * @var \I

doc}
     */
    protected function setUp(): void
    {
        parent::setUp();

        $this->cacheManager = m::mock(CacheManager::class);
        $this->files = m::mock(Filesystem::class);
        $this->cacheRepository = m::mock(Repository::class);

lluminate\Filesystem\Filesystem|\Mockery\MockInterface
     */
    private $files;

    /**
     * @var \Illuminate\Contracts\Cache\Repository|\Mockery\MockInterface
     */
    private $cacheRepository;

    /**
     * {@inherit


', $v->validated());

        $v = new Validator($trans, [
            'x' => null,
        ], [
            'x' => 'array',
            'x.key' => 'string',
        ]);
        $this->assertFalse($v->passes());
    }

    public function testNullableMakesNoDifferenceIfImplicitRuleExists()
    {
        $trans = $this->getIlluminateArrayTranslator();

        $v = new Validator($trans, [
            'x' => null, 'y' => null,
        ], [
            'x' => 'nullable|required_with:y|integer',
            'y'

|integer',
            'y' => 'nullable|required_with:x|integer',
        ]);
        $this->assertTrue($v->fails());
        $this->assertSame('validation.integer', $v->messages()->get('x')[0]);

        $v = new Validator($trans, [
            'x' => 123

 => 'nullable|required_with:x|integer',
        ]);
        $this->assertTrue($v->passes());

        $v = new Validator($trans, [
            'x' => 'value', 'y' => null,
        ], [
            'x' => 'nullable|required_with:y


is->getStore();
        $table = m::mock(stdClass::class);
        $store->getConnection()->shouldReceive('table')->once()->with('table')->andReturn($table);
        $table->shouldReceive('whereIn')->once()->with('key', ['prefixfoo'])->andReturn($table);
        $table->shouldReceive('get')->once()->andReturn(collect([]));

        $this->assertNull($store->get('foo'));
    }

    public function testNullIsReturnedAndItemDeletedWhenItemIsExpired()
    {
        $store = $this->getMockBuilder(DatabaseStore::

($getQuery);
        $getQuery->shouldReceive('get')->once()->andReturn(collect([(object) ['key' => 'prefixfoo', 'expiration' => 1]]));

        $deleteQuery = m::mock(stdClass::class);
        $deleteQuery->shouldReceive('whereIn')->once()->with('key', ['

class)->onlyMethods(['forgetIfExpired'])->setConstructorArgs($this->getMocks())->getMock();

        $getQuery = m::mock(stdClass::class);
        $getQuery->shouldReceive('whereIn')->once()->with('key', ['prefixfoo'])->andReturn


c function testPutCreatesMissingDirectories()
    {
        $files = $this->mockFilesystem();
        $hash = sha1('foo');
        $contents = '0000000000';
        $full_dir = __DIR__.'/'.substr($hash, 0, 2).'/'.substr($hash, 2, 2);
        $files->expects($this->once())->method('makeDirectory')->with($full_dir, 0777, true);
        $files->expects($this->once())->method('put')->with($full_dir.'/'.$hash)->willReturn(strlen($contents));
        $store = new FileStore($files, __DIR__);
        $result = $sto

ePath = __DIR__.'/'.substr($hash, 0, 2).'/'.substr($hash, 2, 2).'/'.$hash;
        $ten9s = '9999999999'; // The "forever" time value.
        $fileContents = $ten9s.serialize('gold');
        $exclusiveLock = true;

        $files->expects($this->once())-

re->put('foo', $contents, 0);
        $this->assertTrue($result);
    }

    public function testPutWillConsiderZeroAsEternalTime()
    {
        $files = $this->mockFilesystem();

        $hash = sha1('O--L / key');
        $fil


namespace Illuminate\Tests\Http;

use Illuminate\Http\Testing\MimeType;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Mime\MimeTypesInterface;

class HttpMimeTypeTest extends TestCase
{
    public function testMimeTypeFromFileNameExistsTrue()
    {
        $this->assertSame('image/jpeg', MimeType::from('foo.jpg'));
    }

    public function testMimeTypeFromFileNameExistsFalse()
    {
        $this->assertSame('application/octet-stream', MimeType::from('foo.bar'));
    }

    public function testMi

meType::get('bar'));
    }

    public function testMimeTypeSymfonyInstance()
    {
        $this->assertInstanceOf(MimeTypesInterface::class, MimeType::getMimeTypes());
    }

    public function testSearchExtensionFromMimeType()
    {
        $this->asse

meTypeFromExtensionExistsTrue()
    {
        $this->assertSame('image/jpeg', MimeType::get('jpg'));
    }

    public function testMimeTypeFromExtensionExistsFalse()
    {
        $this->assertSame('application/octet-stream', Mi


Carbon;
use Memcached;
use Mockery as m;
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
use PHPUnit\Framework\TestCase;

#[RequiresPhpExtension('memcached')]
class CacheMemcachedStoreTest extends TestCase
{
    public function testGetReturnsNullWhenNotFound()
    {
        $memcache = $this->getMockBuilder(Memcached::class)->onlyMethods(['get', 'getResultCode'])->getMock();
        $memcache->expects($this->once())->method('get')->with('foo:bar')->willReturn(null);
        $memcache->expects($this->

che = $this->getMockBuilder(Memcached::class)->onlyMethods(['get', 'getResultCode'])->getMock();
        $memcache->expects($this->once())->method('get')->willReturn('bar');
        $memcache->expects($this->once())->method('getResultCode')->willReturn(0);

once())->method('getResultCode')->willReturn(1);
        $store = new MemcachedStore($memcache, 'foo:');
        $this->assertNull($store->get('bar'));
    }

    public function testMemcacheValueIsReturned()
    {
        $memca


re;
use Illuminate\Cache\CacheManager;
use Illuminate\Config\Repository as ConfigRepository;
use Illuminate\Container\Container;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Facade;
use Mockery as m;
use Mockery\LegacyMockInterface;
use PHPUnit\Framework\TestCase;

class CacheSpyMemoTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        $container = new Container;

        $container->instance('config', new ConfigRepository([

        $container->instance('cache', new CacheManager($container));

        Facade::setFacadeApplication($container);
    }

    protected function tearDown(): void
    {
        Facade::clearResolvedInstances();
        Facade::setFacadeApplication(nul

'cache' => [
                'default' => 'array',
                'stores' => [
                    'array' => [
                        'driver' => 'array',
                    ],
                ],
            ],
        ]));


te\Tests\Cache;

use Illuminate\Cache\RateLimiting\GlobalLimit;
use Illuminate\Cache\RateLimiting\Limit;
use PHPUnit\Framework\TestCase;

class LimitTest extends TestCase
{
    public function testConstructors()
    {
        $limit = new Limit('', 3, 1);
        $this->assertSame(1, $limit->decaySeconds);
        $this->assertSame(3, $limit->maxAttempts);

        $limit = Limit::perSecond(3);
        $this->assertSame(1, $limit->decaySeconds);
        $this->assertSame(3, $limit->maxAttempts);

        $l

     $this->assertSame(3, $limit->maxAttempts);

        $limit = Limit::perMinute(3, 4);
        $this->assertSame(240, $limit->decaySeconds);
        $this->assertSame(3, $limit->maxAttempts);

        $limit = Limit::perMinutes(2, 3);
        $this->ass

imit = Limit::perSecond(3, 5);
        $this->assertSame(5, $limit->decaySeconds);
        $this->assertSame(3, $limit->maxAttempts);

        $limit = Limit::perMinute(3);
        $this->assertSame(60, $limit->decaySeconds);


namespace Illuminate\Tests\Validation;

use Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Validator;
use PHPUnit\Framework\TestCase;

class ValidatorAfterRuleTest extends TestCase
{
    public function testAfterAcceptsArrayOfRules()
    {
        $validator = new Validator(new Translator(new ArrayLoader, 'en'), [], []);

        $validator->after([
            fn ($validator) => $validator->errors()->add('closure', 'true'),
            new InvokableAft

        ], $validator->messages()->messages());
    }
}

class InvokableAfterRule
{
    public function __invoke($validator)
    {
        $validator->errors()->add('invokableAfterRule', 'true');
    }
}

class AfterMethodRule
{
    public function __invo

erRule,
            new AfterMethodRule,
        ])->messages()->messages();

        $this->assertSame([
            'closure' => ['true'],
            'invokableAfterRule' => ['true'],
            'afterMethodRule' => ['true'],


te\Tests\Cache;

use Illuminate\Cache\ArrayStore;
use Illuminate\Cache\CacheManager;
use Illuminate\Cache\FailoverStore;
use Illuminate\Cache\Repository;
use Illuminate\Contracts\Cache\CanFlushLocks;
use Illuminate\Contracts\Events\Dispatcher;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class CacheFailoverStoreTest extends TestCase
{
    protected function tearDown(): void
    {
        m::close();
    }

    public function testImplementsCanFlushLocks()
    {
        $store = $this->makeFailoverStor

  $storeA->lock('lock-a', 60)->get();
        $storeB->lock('lock-b', 60)->get();

        $cache = m::mock(CacheManager::class);
        $cache->shouldReceive('store')->with('store-a')->andReturn(new Repository($storeA));
        $cache->shouldReceive('st

e([]);

        $this->assertInstanceOf(CanFlushLocks::class, $store);
    }

    public function testFlushLocksCallsFlushLocksOnAllBackingStores()
    {
        $storeA = new ArrayStore;
        $storeB = new ArrayStore;


as m;
use PHPUnit\Framework\TestCase;

class CacheRateLimiterTest extends TestCase
{
    public function testTooManyAttemptsReturnTrueIfAlreadyLockedOut()
    {
        $cache = m::mock(Cache::class);
        $cache->shouldReceive('get')->once()->with('key', 0)->andReturn(1);
        $cache->shouldReceive('has')->once()->with('key:timer')->andReturn(true);
        $cache->shouldReceive('add')->never();
        $cache->shouldReceive('getStore')->andReturn(new ArrayStore);
        $rateLimiter = new RateLimit

)->once()->with('key:timer', m::type('int'), 1)->andReturn(true);
        $cache->shouldReceive('add')->once()->with('key', 0, 1)->andReturn(true);
        $cache->shouldReceive('increment')->once()->with('key', 1)->andReturn(1);
        $cache->shouldRece

er($cache);

        $this->assertTrue($rateLimiter->tooManyAttempts('key', 1));
    }

    public function testHitProperlyIncrementsAttemptCount()
    {
        $cache = m::mock(Cache::class);
        $cache->shouldReceive('add'


BufferedOutput;
use Symfony\Component\VarDumper\Caster\ReflectionCaster;
use Symfony\Component\VarDumper\Cloner\VarCloner;

class CliDumperTest extends TestCase
{
    protected function setUp(): void
    {
        CliDumper::resolveDumpSourceUsing(function () {
            return [
                '/my-work-director/app/routes/console.php',
                'app/routes/console.php',
                18,
            ];
        });
    }

    public function testString()
    {
        $output = $this->dump('str

app/routes/console.php:18\n";

        $this->assertSame($expected, $output);
    }

    public function testFloat()
    {
        $output = $this->dump(1.1);

        $expected = "1.1 // app/routes/console.php:18\n";

        $this->assertSame($expected,

ing');

        $expected = "\"string\" // app/routes/console.php:18\n";

        $this->assertSame($expected, $output);
    }

    public function testInteger()
    {
        $output = $this->dump(1);

        $expected = "1 //


rk\Attributes\RequiresOperatingSystem;
use PHPUnit\Framework\TestCase;
use Symfony\Component\ErrorHandler\Exception\FlattenException;

class FrameTest extends TestCase
{
    #[RequiresOperatingSystem('Linux|Darwin')]
    #[DataProvider('unixFileDataProvider')]
    public function test_it_normalizes_file_path_on_unix($frameData, $basePath, $expected)
    {
        $exception = m::mock(FlattenException::class);
        $classMap = [];
        $frame = new Frame($exception, $classMap, $frameData, $basePath);

  '[internal function]',
        ];
        yield 'unknown file' => [
            ['file' => 123, 'line' => 10],
            '/path/to/your-app',
            '[unknown file]',
        ];
        yield 'file with base path' => [
            ['file' => '/pat

        $this->assertEquals($expected, $frame->file());
    }

    public static function unixFileDataProvider()
    {
        yield 'internal function' => [
            ['line' => 10],
            '/path/to/your-app',


work\TestCase;

class ListenerTest extends TestCase
{
    public function test_queries_returns_expected_shape_after_query_executed()
    {
        $connection = m::mock();

        $connection->shouldReceive('getName')->andReturn('testing');
        $connection->shouldReceive('prepareBindings')->with(['foo'])->andReturn(['foo']);

        $event = new QueryExecuted('select * from users where id = ?', ['foo'], 5.2, $connection);

        $listener = new Listener();

        $listener->onQueryExecuted($event)

is->assertArrayHasKey('time', $query);
        $this->assertArrayHasKey('sql', $query);
        $this->assertArrayHasKey('bindings', $query);

        $this->assertSame('testing', $query['connectionName']);
        $this->assertSame(5.2, $query['time']);

;

        $queries = $listener->queries();

        $this->assertIsArray($queries);
        $this->assertCount(1, $queries);

        $query = $queries[0];

        $this->assertArrayHasKey('connectionName', $query);
        $th


ected function setUp(): void
    {
        HtmlDumper::resolveDumpSourceUsing(function () {
            return [
                '/my-work-director/app/routes/console.php',
                'app/routes/console.php',
                18,
            ];
        });

        $this->app = Container::getInstance();
    }

    public function testString()
    {
        $output = $this->dump('string');

        $expected = "string\" // app/routes/console.php:18\n
";

e.php:18\n
";

        $this->assertStringContainsString($expected, $output);
    }

    public function testFloat()
    {
        $output = $this->dump(1.1);

        $expected = "1.1 // app/routes/consol

$this->assertStringContainsString($expected, $output);
    }

    public function testInteger()
    {
        $output = $this->dump(1);

        $expected = "1 // app/routes/consol