hp

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class DynamicContentIsShown extends Migration
{
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->increments('id');
            $table->string('url')->nullable();
            $table->string('name')->nullable();
        });

        DB::table('blogs')->insert([
            ['url' =>

*/
        $tablesList = DB::withoutPretending(function () {
            return DB::table('people')->get();
        });

        $tablesList->each(function ($person, $key) {
            DB::table('blogs')->where('blog_id', '=', $person->blog_id)->insert([

 'www.janedoe.com'],
            ['url' => 'www.johndoe.com'],
        ]);

        DB::statement("ALTER TABLE 'pseudo_table_name' MODIFY 'column_name' VARCHAR(191)");

        /** @var \Illuminate\Support\Collection $tablesList


tabase\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class DynamicContentNotShown extends Migration
{
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->increments('id');
            $table->string('url')->nullable();
            $table->string('name')->nullable();
        });

        DB::table('blogs')->insert([
            ['url' => 'www.janedoe.com'],
            ['url' => 'www.johndoe.com'],

_table_name' MODIFY 'column_name' VARCHAR(191)");

        DB::table('people')->get()->each(function ($person, $key) {
            DB::table('blogs')->where('blog_id', '=', $person->blog_id)->insert([
                'id' => $key + 1,
                'name

     ]);

        DB::statement("ALTER TABLE 'pseudo


pace Illuminate\Tests\Integration\Redis;

use Illuminate\Redis\Connections\PredisConnection;
use Illuminate\Redis\Events\CommandExecuted;
use Illuminate\Support\Facades\Event;
use Mockery as m;
use Orchestra\Testbench\Attributes\WithConfig;
use Orchestra\Testbench\TestCase;
use Predis\Client;
use Predis\Command\Argument\Search\SearchArguments;

#[WithConfig('database.redis.client', 'predis')]
class PredisConnectionTest extends TestCase
{
    public function testPredisCanEmitEventWithArrayableArgumentObject(

     $command = 'ftSearch';
        $parameters = ['test', '*', (new SearchArguments())->dialect('3')->withScores()];

        $predis = new PredisConnection($client = m::mock(Client::class));
        $predis->setEventDispatcher($event);

        $client->

)
    {
        if (! class_exists(SearchArguments::class)) {
            return $this->markTestSkipped('Skipped tests on predis/predis dependency without '.SearchArguments::class);
        }

        $event = Event::fake();


tra\Testbench\Attributes\WithConfig;
use Orchestra\Testbench\TestCase;

class CloudTest extends TestCase
{
    #[WithConfig('database.connections.pgsql', ['host' => 'test-pooler.pg.laravel.cloud', 'username' => 'test-username', 'password' => 'test-password'])]
    public function test_it_can_resolve_core_container_aliases()
    {
        Cloud::configureUnpooledPostgresConnection($this->app);

        $this->assertEquals([
            'host' => 'test.pg.laravel.cloud',
            'username' => 'test-userna

FIG'] = json_encode(
            [
                [
                    'disk' => 'test-disk',
                    'access_key_id' => 'test-access-key-id',
                    'access_key_secret' => 'test-access-key-secret',
                    'bucket' =

me',
            'password' => 'test-password',
        ], $this->app['config']->get('database.connections.pgsql-unpooled'));
    }

    public function test_it_can_configure_disks()
    {
        $_SERVER['LARAVEL_CLOUD_DISK_CON


;

use Illuminate\Cache\RateLimiter;
use Illuminate\Cache\RedisStore;
use Illuminate\Cache\Repository;
use Illuminate\Foundation\Testing\Concerns\InteractsWithRedis;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
use PHPUnit\Framework\TestCase;

#[RequiresPhpExtension('redis')]
class RedisCacheIntegrationTest extends TestCase
{
    use InteractsWithRedis;

    protected function setUp(): void
    {
        parent::setUp();
        $this->setUpRedis();

 testRedisCacheAddTwice($driver)
    {
        $store = new RedisStore($this->redis[$driver]);
        $repository = new Repository($store);
        $this->assertTrue($repository->add('k', 'v', 3600));
        $this->assertFalse($repository->add('k', 'v',

   }

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

        parent::tearDown();
    }

    /**
     * @param  string  $driver
     */
    #[DataProvider('redisDriverProvider')]
    public function


t\Framework\Attributes\TestWith;
use RuntimeException;

#[RequiresPhpExtension('redis')]
class RedisStoreTest extends TestCase
{
    use InteractsWithRedis;

    /** {@inheritdoc} */
    #[\Override]
    protected function setUp(): void
    {
        $this->afterApplicationCreated(function () {
            $this->setUpRedis();
        });

        $this->beforeApplicationDestroyed(function () {
            $this->tearDownRedis();
        });

        parent::setUp();
    }

    public function testCacheTtl(

, 1);
        $putAt = microtime(true);

        Sleep::for(600)->milliseconds();
        $this->assertTrue((microtime(true) - $putAt) < 1);
        $this->assertSame('world', $store->get('hello'));

        // Although this key expires after exactly 1 sec

): void
    {
        $store = Cache::store('redis');
        $store->clear();

        while ((microtime(true) - time()) > 0.5 && (microtime(true) - time()) < 0.6) {
            //
        }

        $store->put('hello', 'world'


use Illuminate\Http\Client\Pool;
use Illuminate\Http\Client\Request;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Facade;
use Illuminate\Support\Facades\Http;
use Orchestra\Testbench\TestCase;
use RuntimeException;

class HttpClientTest extends TestCase
{
    public function testGlobalMiddlewarePersistsBeforeWeDispatchEvent(): void
    {
        Event::fake();
        Http::fake();

        Http::globalRequestMi

llection($event->request->header('User-Agent')))->contains('Facade/1.0');
        });
    }

    public function testGlobalMiddlewarePersistsAfterFacadeFlush(): void
    {
        Http::macro('getGlobalMiddleware', fn () => $this->globalMiddleware);

ddleware(fn ($request) => $request->withHeader('User-Agent', 'Facade/1.0'));

        Http::get('laravel.com');

        Event::assertDispatched(RequestSending::class, function (RequestSending $event) {
            return (new Co


on;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Route;
use Orchestra\Testbench\TestCase;

class RequestDurationThresholdTest extends TestCase
{
    public function testItCanHandleExceedingRequestDuration()
    {
        Route::get('test-route', fn () => 'ok');
        $request = Request::create('http://localhost/test-route');
        $response = new Response();
        $called = false;
        $kernel = $this->app[Kernel::class];
        $kernel->whenRequestLifecycleIsLongerThan(Ca

ddMillisecond());
        $kernel->terminate($request, $response);

        $this->assertTrue($called);
    }

    public function testItDoesntCallWhenExactlyThresholdDuration()
    {
        Route::get('test-route', fn () => 'ok');
        $request = Requ

rbonInterval::second(), function () use (&$called) {
            $called = true;
        });

        Carbon::setTestNow(Carbon::now());
        $kernel->handle($request);

        Carbon::setTestNow(Carbon::now()->addSecond()->a


Http\Fixtures\PostResourceWithOptionalMerging;
use Illuminate\Tests\Integration\Http\Fixtures\PostResourceWithOptionalPivotRelationship;
use Illuminate\Tests\Integration\Http\Fixtures\PostResourceWithOptionalRelationship;
use Ill


minate\Foundation\Testing\Concerns\InteractsWithRedis;
use Illuminate\Http\Request;
use Illuminate\Routing\Middleware\ThrottleRequestsWithRedis;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
use Orchestra\Testbench\Attributes\WithConfig;
use Orchestra\Testbench\TestCase;
use Throwable;

#[WithConfig('hashing.driver', 'bcrypt')]
class ThrottleRequestsWithRedisTest extends TestCase
{
    use InteractsWithRedis;

    public function testLockOpe

       })->middleware(ThrottleRequestsWithRedis::class.':2,1');

            $response = $this->withoutExceptionHandling()->get('/');
            $this->assertSame('yes', $response->getContent());
            $this->assertEquals(2, $response->headers->get(

nsImmediatelyAfterDecay()
    {
        $this->ifRedisAvailable(function () {
            $now = Carbon::now();

            Carbon::setTestNow($now);

            Route::get('/', function () {
                return 'yes';


namespace Illuminate\Tests\Integration\Http\Fixtures;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResourceWithOptionalAppendedAttributes extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'first' => $this->whenAppended('is_published'),
            'second' => $this->whenAppended('is_published', 'override value'),
            'third' => $this->whenAppended('is_published', function () {
                return 'overr

          }),
            'fourth' => $this->whenAppended('is_published', $this->is_published, 'default'),
            'fifth' => $this->whenAppended('is_published', $this->is_published, function () {
                return 'default';
            }),


)
    {
        $app['config']['cors'] = [
            'paths' => ['api/*'],
            'supports_credentials' => false,
            'allowed_origins' => ['http://localhost'],
            'allowed_headers' => ['X-Custom-1', 'X-Custom-2'],
            'allowed_methods' => ['GET', 'POST'],
            'exposed_headers' => [],
            'max_age' => 0,
        ];

        $kernel = $app->make(Kernel::class);
        $kernel->prependMiddleware(HandleCors::class);
    }

    protected function defineRoutes($r

all('OPTIONS', 'api/ping', [], [], [], [
            'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
        ]);

        $this->assertSame('http://localhost', $crawler->headers->get('Access-Control-Allow-Origin'));
        $this->assertEquals(204, $crawle

outer)
    {
        $this->addWebRoutes($router);
        $this->addApiRoutes($router);
    }

    public function testShouldReturnHeaderAssessControlAllowOriginWhenDontHaveHttpOriginOnRequest()
    {
        $crawler = $this->c


use Illuminate\Auth\Access\Events\GateEvaluated;
use Illuminate\Database\Eloquent\Attributes\UsePolicy;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Gate;
use Illuminate\Tests\Integration\Auth\Fixtures\AuthenticationTestUser;
use Illuminate\Tests\Integration\Auth\Fixtures\Models\Policies\Nested\SubTestUserPolicy;
use Illuminate\Tests\Integration\Auth\Fixtures\Policies\AuthenticationTestUserPolicy;
use Illuminate\Tests\Integration\Auth\Fixture

');

        Event::assertDispatched(GateEvaluated::class);
    }

    public function testPolicyCanBeGuessedUsingClassConventions()
    {
        $this->assertInstanceOf(
            AuthenticationTestUserPolicy::class,
            Gate::getPolicyFor(Auth

s\Policies\Nested\TopTestUserPolicy;
use Orchestra\Testbench\TestCase;

class GatePolicyResolutionTest extends TestCase
{
    public function testGateEvaluationEventIsFired()
    {
        Event::fake();

        Gate::check('foo


dcasting\ShouldBroadcastNow;
use Illuminate\Contracts\Broadcasting\ShouldRescue;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Queue;
use InvalidArgumentException;
use Orchestra\Testbench\TestCase;
use Psr\Log\LoggerInterface;
use RuntimeException;
use stdClass;

class BroadcastManagerTest extends TestCase
{
    public function testEventCanBeBroadcastNow()
    {
        Bus::fake();
        Que

      Bus::fake();
        Queue::fake();

        Broadcast::queue(new TestEvent);

        Bus::assertNotDispatched(BroadcastEvent::class);
        Queue::assertPushed(BroadcastEvent::class);
    }

    public function testEventsCanBeBroadcastUsingQueueR

ue::fake();

        Broadcast::queue(new TestEventNow);

        Bus::assertDispatched(BroadcastEvent::class);
        Queue::assertNotPushed(BroadcastEvent::class);
    }

    public function testEventsCanBeBroadcast()
    {


 Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Illuminate\Tests\Integration\Database\DatabaseTestCase;
use Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\DatabasePresenceVerifier;
use Illuminate\Validation\Validator;

class ValidatorTest extends DatabaseTestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        Schema::create('users', function (Blueprint $table) {

e(['uuid' => (string) Str::uuid(), 'first_name' => 'Jim']);
    }

    public function testExists(): void
    {
        $validator = $this->getValidator(['first_name' => ['John', 'Taylor']], ['first_name' => 'exists:users']);
        $this->assertFalse($va

            $table->increments('id');
            $table->string('uuid');
            $table->string('first_name');
        });

        User::create(['uuid' => (string) Str::uuid(), 'first_name' => 'John']);
        User::creat


ption;
use Illuminate\Contracts\Cache\Repository;
use Orchestra\Testbench\TestCase;
use Throwable;

abstract class CacheFunnelTestCase extends TestCase
{
    abstract protected function cache(): Repository;

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

        try {
            $this->releaseFunnelLocks();
        } catch (Throwable) {
        }
    }

    public function testFunnelBasicHappyPath()
    {
        $result = $this->cache()->funnel('test')
            ->limit(2)

 $i++) {
            $result = $this->cache()->funnel('test')
                ->limit(1)
                ->releaseAfter(60)
                ->block(0)
                ->then(fn () => 'ok');

            $this->assertSame('ok', $result);
        }
    }

    ->releaseAfter(60)
            ->block(0)
            ->then(fn () => 'hello');

        $this->assertSame('hello', $result);
    }

    public function testFunnelReleasesLockAfterCallback()
    {
        for ($i = 0; $i < 5;


on\AwsException;
use Illuminate\Contracts\Cache\Repository;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Orchestra\Testbench\Attributes\RequiresEnv;
use Orchestra\Testbench\TestCase;

#[RequiresEnv('DYNAMODB_CACHE_TABLE')]
class DynamoDbStoreTest extends TestCase
{
    public function testItemsCanBeStoredAndRetrieved()
    {
        Cache::driver('dynamodb')->put('name', 'Taylor', 10);
        $this->assertSame('Taylor', Cache::driver('dynamodb')->get('name'));

        Cache::drive

ertEquals([
            'name' => 'Abigail',
            'age' => 28,
            'height' => null,
        ], Cache::driver('dynamodb')->many(['name', 'age', 'height']));

        Cache::driver('dynamodb')->forget('name');
        $this->assertNull(Cache:

r('dynamodb')->put(['name' => 'Abigail', 'age' => 28], 10);
        $this->assertSame('Abigail', Cache::driver('dynamodb')->get('name'));
        $this->assertEquals(28, Cache::driver('dynamodb')->get('age'));

        $this->ass


Case
{
    use InteractsWithRedis;

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

        $this->setUpRedis();

        $connection = $this->app['redis']->connection();
        $this->markTestSkippedUnless(
            $connection instanceof PhpRedisConnection || $connection instanceof PhpRedisClusterConnection,
            'This test is for phpredis only',
        );
    }

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

        parent::tearDown();

connection', 'default');
        $this->app['config']->set('cache.stores.redis.lock_connection', 'default');

        /** @var \Illuminate\Cache\RedisStore $store */
        $store = Cache::store('redis');
        /** @var \Redis $client */
        $client

}

    public function testRedisLockCanBeAcquiredAndReleasedWithoutSerializationAndCompression()
    {
        $this->app['config']->set('database.redis.client', 'phpredis');
        $this->app['config']->set('cache.stores.redis.


;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\DB;
use Orchestra\Testbench\Attributes\WithMigration;

#[WithMigration]
#[WithMigration('cache')]
#[WithMigration('queue')]
class UniqueUntilProcessingJobTest extends QueueTestCase
{
    protected function defineEnvironment($app)
    {
        parent::defin

ingReleasesLockWhenJobIsReleasedByAMiddleware()
    {
        // Job that does not release and gets processed
        UniqueTestJobThatDoesNotRelease::dispatch();
        $lockKey = DB::table('cache_locks')->orderBy('id')->first()->key;
        $this->asse

eEnvironment($app);
        $app['config']->set('queue.default', 'database');
        $app['config']->set('cache.default', 'database');
        $this->driver = 'database';
    }

    public function testShouldBeUniqueUntilProcess


ts\Queue\Job;
use Illuminate\Queue\CallQueuedHandler;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Mockery as m;

class WithoutOverlappingJobsTest extends QueueTestCase
{
    public function testNonOverlappingJobsAreExecuted()
    {
        OverlappingTestJob::$handled = false;
        $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app);

        $job = m::mock(Job::class);

        $job->shouldReceive('hasFailed')->andReturn(false);

nd' => serialize($command = new OverlappingTestJob),
        ]);

        $lockKey = (new WithoutOverlapping)->getLockKey($command);

        $this->assertTrue(OverlappingTestJob::$handled);
        $this->assertTrue($this->app->get(Cache::class)->lock($lo

        $job->shouldReceive('isReleased')->andReturn(false);
        $job->shouldReceive('isDeletedOrReleased')->andReturn(false);
        $job->shouldReceive('delete')->once();

        $instance->call($job, [
            'comma


use Exception;
use Illuminate\Http\StreamedEvent;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Orchestra\Testbench\TestCase;

class EventStreamResponseTest extends TestCase
{
    public function testEventStreamResponse()
    {
        Route::get('/stream', function () {
            return response()->eventStream(function () {
                yield new StreamedEvent(
                    event: 'update',
                    data: ['message' => 'hello'],
                );

esponse->assertOk();
        $response->assertHeader('Content-Type', 'text/event-stream; charset=utf-8');
        $response->assertHeader('X-Accel-Buffering', 'no');

        $content = $response->streamedContent();

        $this->assertStringContainsStri

               yield new StreamedEvent(
                    event: 'update',
                    data: ['message' => 'world'],
                );
            });
        });

        $response = $this->get('/stream');

        $r


amespace Illuminate\Tests\Integration\Http;

use Illuminate\Http\Response;
use Illuminate\Support\Facades\Route;
use JsonSerializable;
use Orchestra\Testbench\TestCase;

class ResponseTest extends TestCase
{
    public function testResponseWithInvalidJsonThrowsException()
    {
        $this->expectException('InvalidArgumentException');
        $this->expectExceptionMessage('Malformed UTF-8 characters, possibly incorrectly encoded');

        Route::get('/response', function () {
            return (new Res

izable
            {
                public function jsonSerialize(): string
                {
                    return "\xB1\x31";
                }
            });
        });

        $this->withoutExceptionHandling();

        $this->get('/response')

ponse())->setContent(new class implements JsonSerial


on\JsonResource;

class PostResourceWithAnonymousResourceCollectionWithPaginationInformation extends JsonResource
{
    public function toArray($request)
    {
        return ['id' => $this->id, 'title' => $this->title, 'custom' => true];
    }

    /**
     * Create a new anonymous resource collection.
     *
     * @param  mixed  $resource
     * @return \Illuminate\Tests\Integration\Http\Fixtures\AnonymousResourceCollectionWithPaginationInformation
     */
    public static function collection($resource)

ctionWithPaginationInformation($resource, static::class), function ($collection) {
            if (property_exists(static::class, 'preserveKeys')) {
                $collection->preserveKeys = (new static([]))->preserveKeys === true;
            }

    {
        return tap(new AnonymousResourceColle


t;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Support\Facades\Broadcast as BroadcastFacade;
use Illuminate\Support\Facades\Event as EventFacade;
use Orchestra\Testbench\TestCase;
use ReflectionClass;

class SendingBroadcastsViaAnonymousEventTest extends TestCase
{
    public function testBroadcastIsSent()
    {
        EventFacade::fake();

        BroadcastFacade::on('test-channel')
            ->with(['some' => 'data'])
            ->as('test-ev

   $event->broadcastOn() === ['test-channel'] &&
                $event->broadcastAs() === 'test-event' &&
                $event->broadcastWith() === ['some' => 'data'];
        });
    }

    public function testBroadcastIsSentNow()
    {
        EventFa

ent')
            ->send();

        EventFacade::assertDispatched(AnonymousEvent::class, function ($event) {
            return (new ReflectionClass($event))->getProperty('connection')->getValue($event) === null &&


Config('cache.default', 'redis')]
#[WithConfig('cache.prefix', 'laravel-cache-')]
class MemoizedStoreTest extends TestCase
{
    use InteractsWithRedis;

    /** {@inheritdoc} */
    #[\Override]
    protected function setUp(): void
    {
        $this->afterApplicationCreated(function () {
            $this->setUpRedis();

            Redis::connection(Config::get('cache.stores.redis.connection'))->flushDb();
            Redis::connection(Config::get('cache.stores.redis.lock_connection'))->flushDb();

 Cache::put('name', 'Tim', 60);

        $live = Cache::get('name');
        $memoized = Cache::memo()->get('name');
        $this->assertSame('Tim', $live);
        $this->assertSame('Tim', $memoized);

        Cache::put('name', 'Taylor', 60);

        $

   });

        $this->beforeApplicationDestroyed(function () {
            $this->tearDownRedis();
        });

        parent::setUp();
    }

    public function test_it_can_memoize_when_retrieving_single_value()
    {


Queue\Job;
use Illuminate\Foundation\Testing\Concerns\InteractsWithRedis;
use Illuminate\Queue\CallQueuedHandler;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\ThrottlesExceptionsWithRedis;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Mockery as m;
use Orchestra\Testbench\TestCase;
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
use RuntimeException;

#[RequiresPhpExtension('redis')]
class ThrottlesExceptionsWithRedisTest extends TestCase
{
    use Interac

ownRedis();

        parent::tearDown();
    }

    public function testCircuitIsOpenedForJobErrors()
    {
        $this->assertJobWasReleasedImmediately(CircuitBreakerWithRedisTestJob::class, $key = Str::random());
        $this->assertJobWasReleasedImme

tsWithRedis;

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

        $this->setUpRedis();

        Carbon::setTestNow(Carbon::now());
    }

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


    use LazilyRefreshDatabase;

    public function testStaleWhileRevalidate(): void
    {
        Carbon::setTestNow('2000-01-01 00:00:00');
        $cache = Cache::driver('array');
        $count = 0;

        // Cache is empty. The value should be populated...
        $value = $cache->flexible('foo', [10, 20], function () use (&$count) {
            return ++$count;
        });

        $this->assertSame(1, $value);
        $this->assertCount(0, defer());
        $this->assertSame(1, $cache->get('foo'));

function () use (&$count) {
            return ++$count;
        });
        $this->assertSame(1, $value);
        $this->assertCount(0, defer());
        $this->assertSame(1, $cache->get('foo'));
        $this->assertSame(946684800, $cache->get('illuminat

        $this->assertSame(946684800, $cache->get('illuminate:cache:flexible:created:foo'));

        // Cache is fresh. The value should be retrieved from the cache and used...
        $value = $cache->flexible('foo', [10, 20],


use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Tests\Integration\Auth\Fixtures\AuthenticationTestUser;
use Orchestra\Testbench\Attributes\WithMigration;
use Orchestra\Testbench\Factories\UserFactory;
use Orchestra\Testbench\TestCase;

#[Wit

     parent::tearDown();
    }

    protected function defineEnvironment($app)
    {
        $app['config']->set('app.key', Str::random(32));
        $app['config']->set('auth.providers.users.model', AuthenticationTestUser::class);
    }

    protected fun

hMigration]
class ForgotPasswordTest extends TestCase
{
    use RefreshDatabase;

    protected function tearDown(): void
    {
        ResetPassword::$createUrlCallback = null;
        ResetPassword::$toMailCallback = null;


namespace Illuminate\Tests\Integration\Foundation\Configuration;

use Illuminate\Console\Scheduling\ScheduleListCommand;
use Illuminate\Foundation\Application;
use Illuminate\Support\Carbon;
use Orchestra\Testbench\TestCase;

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

        Carbon::setTestNow('2023-01-01');
        ScheduleListCommand::resolveTerminalWidthUsing(fn () => 80);
    }

    protected function resolveApplication()
    {

([__DIR__.'/stubs/console.php'])
            ->create();
    }

    public function testDisplaySchedule()
    {
        $this->artisan(ScheduleListCommand::class)
            ->assertSuccessful()
            ->expectsOutputToContain('  0 * * * *  php artis

  return Application::configure(static::applicationBasePath())
            ->withSchedule(function ($schedule) {
                $schedule->command('schedule:clear-cache')->everyMinute();
            })
            ->withCommands


te\Tests\Integration\Notifications;

use Illuminate\Database\Eloquent\Casts\AsStringable;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Schema;
use Orchestra\Testbench\Attributes\DefineDatabase;
use Orchestra\Testbench\Attributes\WithMigration;
use Orchestra\Testbench\TestCase;

#[WithMigration(

eKey()
    {
        Notification::fake();

        $user = UuidUserFactoryStub::new()->create();

        $user->notify(new NotificationStub);

        Notification::assertSentTo($user, NotificationStub::class, function ($notification, $channels, $notifia

'laravel', 'notifications')]
class DatabaseNotificationTest extends TestCase
{
    use RefreshDatabase;

    #[DefineDatabase('defineDatabaseAndConvertUserIdToUuid')]
    public function testAssertSentToWhenNotifiableHasStringabl


tions\Messages\MailMessage;
use Illuminate\Notifications\Notifiable;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Mockery as m;
use Orchestra\Testbench\TestCase;

class SendingMailNotificationsTest extends TestCase
{
    public $mailFactory;
    public $mailer;
    public $markdown;

    protected function defineEnvironment($app)
    {
        $this->mailFactory = m::mock(MailFactory::class);
        $this->mailer = m::mock(Mailer::class);

});

        $app->extend(Mailer::class, function () {
            return $this->mailer;
        });

        $app->extend(MailFactory::class, function () {
            return $this->mailFactory;
        });

        $app['view']->addLocation(__DIR__.'/Fix

        $this->mailFactory->shouldReceive('mailer')->andReturn($this->mailer);
        $this->markdown = m::mock(Markdown::class);

        $app->extend(Markdown::class, function () {
            return $this->markdown;


use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notifiable;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Stringable;
use Orchestra\Testbench\TestCase;

class SendingMailableNotificationsTest extends TestCase
{
    use RefreshDatabase;

    protected function defineEnvironment($app)
    {
        $app['config']->set('mail.driv

Database()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email');
            $table->string('name')->nullable();
        });
    }

    protected function beforeRefres

er', 'array');

        $app['config']->set('app.locale', 'en');

        $app['config']->set('mail.markdown.theme', 'blank');

        $app['view']->addLocation(__DIR__.'/Fixtures');
    }

    protected function afterRefreshing


ications;

use Illuminate\Notifications\AnonymousNotifiable;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Notification as NotificationFacade;
use Illuminate\Support\Testing\Fakes\NotificationFake;
use Orchestra\Testbench\TestCase;

class SendingNotificationsViaAnonymousNotifiableTest extends TestCase
{
    public function testMailIsSent()
    {
        $notifiable = (new AnonymousNotifiable)
            ->route('testchannel', 'enzo')
            ->route('anothertestchannel', 'en

], $_SERVER['__notifiable.route']);
    }

    public function testAnonymousNotifiableWithMultipleRoutes()
    {
        $_SERVER['__notifiable.route'] = [];

        NotificationFacade::routes([
            'testchannel' => 'enzo',
            'anothertes

zo@deepblue.com');

        NotificationFacade::send(
            $notifiable,
            new TestMailNotificationForAnonymousNotifiable
        );

        $this->assertEquals([
            'enzo', 'enzo@deepblue.com',


e Illuminate\Foundation\Events\LocaleUpdated;
use Illuminate\Mail\Mailable;
use Illuminate\Notifications\Channels\MailChannel;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notifiable;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Notification as NotificationFacade;
use Illuminate\Support\Facades\Schema;
use Illuminate\Testing\Assert;
use Orchestra\Testbench\TestCase;

class Sen

dingNotificationsWithLocaleTest extends TestCase
{
    protected function defineEnvironment($app)
    {
        $app['config']->set('mail.driver', 'array');

        $app['config']->set('app.locale', 'en');

        $app['view']-


HPUnit\Framework\TestCase;

class AfterResolvingAttributeCallbackTest extends TestCase
{
    public function testCallbackIsCalledAfterDependencyResolutionWithAttribute()
    {
        $container = new Container();

        $container->afterResolvingAttribute(ContainerTestOnTenant::class, function (ContainerTestOnTenant $attribute, HasTenantImpl $hasTenantImpl, Container $container) {
            $hasTenantImpl->onTenant($attribute->tenant);
        });

        $hasTenantA = $container->make(ContainerTestHa

>make(ContainerTestHasTenantImplPropertyWithTenantB::class);
        $this->assertInstanceOf(HasTenantImpl::class, $hasTenantB->property);
        $this->assertEquals(Tenant::TenantB, $hasTenantB->property->tenant);
    }

    public function testCallbackI

sTenantImplPropertyWithTenantA::class);
        $this->assertInstanceOf(HasTenantImpl::class, $hasTenantA->property);
        $this->assertEquals(Tenant::TenantA, $hasTenantA->property->tenant);

        $hasTenantB = $container-


this->expectExceptionMessage('Call to undefined function ContainerTestCallStub()');

        $container = new Container;
        $container->call('ContainerTestCallStub');
    }

    public function testCallWithAtSignBasedClassReferences()
    {
        $container = new Container;
        $result = $container->call(ContainerTestCallStub::class.'@work', ['foo', 'bar']);
        $this->assertEquals(['foo', 'bar'], $result);

        $container = new Container;
        $result = $container->call(ContainerTestC

ntainerTestCallStub::class.'@inject', ['default' => 'foo']);
        $this->assertInstanceOf(ContainerCallConcreteStub::class, $result[0]);
        $this->assertSame('foo', $result[1]);

        $container = new Container;
        $result = $container->cal

allStub::class.'@inject');
        $this->assertInstanceOf(ContainerCallConcreteStub::class, $result[0]);
        $this->assertSame('taylor', $result[1]);

        $container = new Container;
        $result = $container->call(Co


edBindings()
    {
        $container = new Container;
        $container['foo'] = 'foo';
        $container->extend('foo', function ($old, $container) {
            return $old.'bar';
        });

        $this->assertSame('foobar', $container->make('foo'));

        $container = new Container;

        $container->singleton('foo', function () {
            return (object) ['name' => 'taylor'];
        });
        $container->extend('foo', function ($old, $container) {
            $old->age = 26;

'));
    }

    public function testExtendInstancesArePreserved()
    {
        $container = new Container;
        $container->bind('foo', function () {
            $obj = new stdClass;
            $obj->foo = 'bar';

            return $obj;
        });

    return $old;
        });

        $result = $container->make('foo');

        $this->assertSame('taylor', $result->name);
        $this->assertEquals(26, $result->age);
        $this->assertSame($result, $container->make('foo


te\Tests\Container;

use Illuminate\Container\Container;
use PHPUnit\Framework\TestCase;

class ContainerResolveNonInstantiableTest extends TestCase
{
    public function testResolvingNonInstantiableWithDefaultRemovesWiths()
    {
        $container = new Container;
        $object = $container->make(ParentClass::class, ['i' => 42]);

        $this->assertSame(42, $object->i);
    }

    public function testResolvingNonInstantiableWithVariadicRemovesWiths()
    {
        $container = new Container;

  {
        $container = new Container;
        $parent = $container->make(VariadicPrimitive::class);

        $this->assertSame([], $parent->params);
    }
}

interface TestInterface
{
}

class ParentClass
{
    /**
     * @var int
     */
    public $i;

$parent = $container->make(VariadicParentClass::class, ['i' => 42]);

        $this->assertCount(0, $parent->child->objects);
        $this->assertSame(42, $parent->i);
    }

    public function testResolveVariadicPrimitive()


k\TestCase;

class ContainerTaggingTest extends TestCase
{
    public function testContainerTags()
    {
        $container = new Container;
        $container->tag(ContainerImplementationTaggedStub::class, 'foo', 'bar');
        $container->tag(ContainerImplementationTaggedStubTwo::class, ['foo']);

        $this->assertCount(1, $container->tagged('bar'));
        $this->assertCount(2, $container->tagged('foo'));

        $fooResults = [];
        foreach ($container->tagged('foo') as $foo) {
            $

, $fooResults[0]);
        $this->assertInstanceOf(ContainerImplementationTaggedStub::class, $barResults[0]);
        $this->assertInstanceOf(ContainerImplementationTaggedStubTwo::class, $fooResults[1]);

        $container = new Container;
        $contai

fooResults[] = $foo;
        }

        $barResults = [];
        foreach ($container->tagged('bar') as $bar) {
            $barResults[] = $bar;
        }

        $this->assertInstanceOf(ContainerImplementationTaggedStub::class


leton(function (): ContainerConcreteStub {
            return new ContainerConcreteStub;
        });

        $this->assertInstanceOf(
            IContainerContractStub::class,
            $container->make(IContainerContractStub::class)
        );

        $this->assertTrue($container->isShared(ContainerConcreteStub::class));
    }

    public function testBindIfDoesntRegisterIfServiceAlreadyRegistered()
    {
        $container = new Container;
        $container->bind('name', function () {
            re

IfServiceNotRegisteredYet()
    {
        $container = new Container;
        $container->bind('surname', function () {
            return 'Taylor';
        });
        $container->bindIf('name', function () {
            return 'Dayle';
        });

turn 'Taylor';
        });
        $container->bindIf('name', function () {
            return 'Dayle';
        });

        $this->assertSame('Taylor', $container->make('name'));
    }

    public function testBindIfDoesRegister


windableGenerator;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Guard as GuardContract;
use Illuminate\Contracts\Container\ContextualAttribute;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Database\Connection;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Filesystem\FilesystemManager;
use Illuminate\Http\Request;
use Illuminate\Log\Context\Repository as ContextRepository;
use Illumi

  {
        $container = new Container;

        $container->bind(ContainerTestContract::class, fn (): ContainerTestImplB => new ContainerTestImplB);
        $container->whenHasAttribute(ContainerTestAttributeThatResolvesContractImpl::class, function (Cont

nate\Log\LogManager;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;

class ContextualAttributeBindingTest extends TestCase
{
    public function testDependencyCanBeResolvedFromAttributeBinding()


ass);
        $two = $container->make(ContainerTestContextInjectTwo::class);

        $this->assertInstanceOf(ContainerContextImplementationStub::class, $one->impl);
        $this->assertInstanceOf(ContainerContextImplementationStubTwo::class, $two->impl);

        // Test With Closures
        $container = new Container;

        $container->bind(IContainerContextContractStub::class, ContainerContextImplementationStub::class);

        $container->when(ContainerTestContextInjectOne::class)->needs(IContaine

return $container->make(ContainerContextImplementationStubTwo::class);
        });

        $one = $container->make(ContainerTestContextInjectOne::class);
        $two = $container->make(ContainerTestContextInjectTwo::class);

        $this->assertInstance

rContextContractStub::class)->give(ContainerContextImplementationStub::class);
        $container->when(ContainerTestContextInjectTwo::class)->needs(IContainerContextContractStub::class)->give(function ($container) {


ontainer->bind('foo', function () {
            return new stdClass;
        });
        $instance = $container->make('foo');

        $this->assertSame('taylor', $instance->name);
    }

    public function testResolvingCallbacksAreCalledForType()
    {
        $container = new Container;
        $container->resolving(stdClass::class, function ($object) {
            return $object->name = 'taylor';
        });
        $container->bind('foo', function () {
            return new stdClass;
        });

  $container->alias(stdClass::class, 'std');
        $container->resolving('std', function ($object) {
            return $object->name = 'taylor';
        });
        $container->bind('foo', function () {
            return new stdClass;
        });

   $instance = $container->make('foo');

        $this->assertSame('taylor', $instance->name);
    }

    public function testResolvingCallbacksShouldBeFiredWhenCalledWithAliases()
    {
        $container = new Container;


ontainer;

use Illuminate\Container\RewindableGenerator;
use PHPUnit\Framework\TestCase;

class RewindableGeneratorTest extends TestCase
{
    public function testCountUsesProvidedValue()
    {
        $generator = new RewindableGenerator(function () {
            yield 'foo';
        }, 999);

        $this->assertCount(999, $generator);
    }

    public function testCountUsesProvidedValueAsCallback()
    {
        $called = 0;

        $generator = new RewindableGenerator(function () {
            yield

       $called++;

            return 500;
        });

        // the count callback is called lazily
        $this->assertSame(0, $called);

        $this->assertCount(500, $generator);

        count($generator);

        // the count callback is called

'foo';
        }, function () use (&$called) {


te\Tests\Container;

use Illuminate\Container\Util;
use PHPUnit\Framework\TestCase;
use ReflectionParameter;
use stdClass;

class UtilTest extends TestCase
{
    public function testUnwrapIfClosure()
    {
        $this->assertSame('foo', Util::unwrapIfClosure('foo'));
        $this->assertSame('foo', Util::unwrapIfClosure(function () {
            return 'foo';
        }));
    }

    public function testArrayWrap()
    {
        $string = 'a';
        $array = ['a'];
        $object = new stdClass;

assertSame([], Util::arrayWrap(null));
        $this->assertEquals([null], Util::arrayWrap([null]));
        $this->assertEquals([null, null], Util::arrayWrap([null, null]));
        $this->assertEquals([''], Util::arrayWrap(''));
        $this->assertEqua

  $object->value = 'a';
        $this->assertEquals(['a'], Util::arrayWrap($string));
        $this->assertEquals($array, Util::arrayWrap($array));
        $this->assertEquals([$object], Util::arrayWrap($object));
        $this->


\Testing\File;
use Illuminate\Mail\Attachment;
use Illuminate\Mail\Mailable;
use PHPUnit\Framework\TestCase;

class AttachableTest extends TestCase
{
    public function testItCanHaveMacroConstructors(): void
    {
        Attachment::macro('fromInvoice', function ($name) {
            return Attachment::fromData(fn () => 'pdf content', $name);
        });
        $mailable = new Mailable;

        $mailable->attach(new class() implements Attachable
        {
            public function toMailAttachment()

ntent',
            'name' => 'bar',
            'options' => [
                'mime' => 'image/jpeg',
            ],
        ], $mailable->rawAttachments[0]);
    }

    public function testItCanUtiliseExistingApisOnNonMailBasedResourcesWithPath(): void

           {
                return Attachment::fromInvoice('foo')
                    ->as('bar')
                    ->withMime('image/jpeg');
            }
        });

        $this->assertSame([
            'data' => 'pdf co


use PHPUnit\Framework\TestCase;

class AttachmentTest extends TestCase
{
    public function testFromUrlWithHttpScheme(): void
    {
        $attachment = Attachment::fromUrl('http://example.com/file.pdf');

        $this->assertInstanceOf(Attachment::class, $attachment);
    }

    public function testFromUrlWithHttpsScheme(): void
    {
        $attachment = Attachment::fromUrl('https://example.com/file.pdf');

        $this->assertInstanceOf(Attachment::class, $attachment);
    }

    public function te

'ftp://example.com/file.pdf');
    }

    public function testFromUrlThrowsForFileScheme(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Attachment URLs must use the http or https scheme

stFromUrlThrowsForFtpScheme(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Attachment URLs must use the http or https scheme.');

        Attachment::fromUrl(


it\Framework\TestCase;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;

class MailCloudflareTransportTest extends TestCase
{
    public function testGetTransport(): void
    {
        $container = new Container;

        $container->singleton('config', function () {
            return new Repository([
                'servic

     $manager = new MailManager($container);

        $transport = $manager->createSymfonyTransport(['transport' => 'cloudflare']);

        $this->assertInstanceOf(CloudflareTransport::class, $transport);
        $this->assertSame('cloudflare', (string) $

es' => [
                    'cloudflare' => [
                        'account_id' => 'test-account-id',
                        'token' => 'test-token',
                    ],
                ],
            ]);
        });


pace Illuminate\Tests\Mail;

use Orchestra\Testbench\TestCase;
use Symfony\Component\Mailer\Transport\FailoverTransport;

class MailFailoverTransportTest extends TestCase
{
    public function testGetFailoverTransportWithConfiguredTransports(): void
    {
        $this->app['config']->set('mail.default', 'failover');

        $this->app['config']->set('mail.mailers', [
            'failover' => [
                'transport' => 'failover',
                'mailers' => [
                    'sendmail',

         'transport' => 'array',
            ],
        ]);

        $transport = app('mailer')->getSymfonyTransport();
        $this->assertInstanceOf(FailoverTransport::class, $transport);
    }

    public function testGetFailoverTransportWithLaravel6St

              'array',
                ],
            ],

            'sendmail' => [
                'transport' => 'sendmail',
                'path' => '/usr/sbin/sendmail -bs',
            ],

            'array' => [


use Illuminate\Mail\Transport\LogTransport;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Orchestra\Testbench\TestCase;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\Mime\Email;

class MailLogTransportTest extends TestCase
{
    public function testGetLogTransportWithConfiguredChannel(): void
    {
        $this->app['config']->set('mail.driver', 'log');

        $this->app['config']->set('mail.log_channel', 'mail');

        $this->app['config']->set('logging.chann

logger = $transport->logger();
        $this->assertInstanceOf(LoggerInterface::class, $logger);

        $this->assertInstanceOf(Logger::class, $monolog = $logger->getLogger());
        $this->assertCount(1, $handlers = $monolog->getHandlers());
        $

els.mail', [
            'driver' => 'single',
            'path' => 'mail.log',
        ]);

        $transport = app('mailer')->getSymfonyTransport();
        $this->assertInstanceOf(LogTransport::class, $transport);

        $


public function testMailableAssertSeeInTextPassesWhenPresent(): void
    {
        $mailable = new MailableAssertionsStub;

        $mailable->assertSeeInText('First Item');
    }

    public function testMailableAssertSeeInTextFailsWhenAbsent(): void
    {
        $mailable = new MailableAssertionsStub;

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

        $mailable->assertSeeInText('Fourth Item');
    }

    public function testMailableAssertDontSeeInTextPassesWhenAbsent(): void
    {

onsStub;

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

        $mailable->assertDontSeeInText('First Item');
    }

    public function testMailableAssertSeeInHtmlPassesWhenPresent(): void
    {
        $mailable = new MailableAssertionsSt

     $mailable = new MailableAssertionsStub;

        $mailable->assertDontSeeInText('Fourth Item');
    }

    public function testMailableAssertDontSeeInTextFailsWhenPresent(): void
    {
        $mailable = new MailableAsserti


<?php

namespace Illuminate\Tests\Mail;

use Illuminate\Mail\Mailable;
use PHPUnit\Framework\TestCase;

class MailMailableDataTest extends TestCase
{
    public function testMailableDataIsNotLost(): void
    {
        $mailable = new MailableStub;

        $testData = [
            'first_name' => 'James',
            '__laravel_mailable' => get_class($mailable),
        ];

        $mailable->build(function ($m) use ($testData) {
            $m->view('view', $testData);
        });
        $this->assertSam

      $this->assertSame($testData, $mailable->buildViewData());
    }
}

class MailableStub extends Mailable
{
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build($builder)
    {
        $builder($this);
    }
}

e($testData, $mailable->buildViewData());

        $mailable = new MailableStub;
        $mailable->build(function ($m) use ($testData) {
            $m->view('view', $testData)
                ->text('text-view');
        });


?php

namespace Illuminate\Tests\Mail;

use Illuminate\Mail\Mailables\Headers;
use PHPUnit\Framework\TestCase;

class MailMailableHeadersTest extends TestCase
{
    public function test(): void
    {
        $headers = new Headers(
            '434571BC.8070702@example.net',
            [
                '<19980506192030.26456.qmail@cr.yp.to>',
                '<19980507220459.5655.qmail@warren.demon.co.uk>',
                '<19980508103652.B21462@iconnect.co.ke>',
                '<19980509035615.40087@ru


To('taylor@laravel.com', 'Taylor Otwell');
        $mailable->assertHasTo('taylor@laravel.com');

        $mailable = new WelcomeMailableStub;
        $mailable->to(['taylor@laravel.com']);
        $this->assertEquals([['name' => null, 'address' => 'taylor@laravel.com']], $mailable->to);
        $this->assertTrue($mailable->hasTo('taylor@laravel.com'));
        $this->assertFalse($mailable->hasTo('taylor@laravel.com', 'Taylor Otwell'));
        $mailable->assertHasTo('taylor@laravel.com');
        try {

.\nExpected: [taylor@laravel.com (Taylor Otwell)]\nActual: [taylor@laravel.com]\nFailed asserting that false is true.", $e->getMessage());
        }

        $mailable = new WelcomeMailableStub;
        $mailable->to([['name' => 'Taylor Otwell', 'email' =>

         $mailable->assertHasTo('taylor@laravel.com', 'Taylor Otwell');
            $this->fail();
        } catch (AssertionFailedError $e) {
            $this->assertSame("Did not see expected recipient in email 'to' recipients


ework\TestCase;
use Symfony\Component\Mime\Address;

class MailMailerTest extends TestCase
{
    protected function tearDown(): void
    {
        unset($_SERVER['__mailer.test']);

        parent::tearDown();
    }

    public function testMailerSendSendsMessageWithProperViewContent(): void
    {
        $view = m::mock(Factory::class);
        $view->shouldReceive('make')->once()->andReturn($view);
        $view->shouldReceive('render')->once()->andReturn('rendered.view');

        $mailer = new Mailer('a

StringContainsString('rendered.view', $sentMessage->toString());
    }

    public function testMailerSendSendsMessageWithCcAndBccRecipients(): void
    {
        $view = m::mock(Factory::class);
        $view->shouldReceive('make')->once()->andReturn($vie

rray', $view, new ArrayTransport);

        $sentMessage = $mailer->send('foo', ['data'], function (Message $message) {
            $message->to('taylor@laravel.com')->from('hello@laravel.com');
        });

        $this->assert


ny\Component\Mailer\Transport\Smtp\EsmtpTransport;

class MailManagerTest extends TestCase
{
    #[DataProvider('emptyTransportConfigDataProvider')]
    public function testEmptyTransportConfig($transport): void
    {
        $this->app['config']->set('mail.mailers.custom_smtp', [
            'transport' => $transport,
            'host' => null,
            'port' => null,
            'encryption' => null,
            'username' => null,
            'password' => null,
            'timeout' => null,

estWith([null, 5876])]
    #[TestWith([null, 465])]
    #[TestWith(['smtp', 25])]
    #[TestWith(['smtp', 2525])]
    #[TestWith(['smtps', 465])]
    #[TestWith(['smtp', 465])]
    public function testMailUrlConfig($scheme, $port): void
    {
        $this

  ]);

        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage("Unsupported mail transport [{$transport}]");
        $this->app['mail.manager']->mailer('custom_smtp');
    }

    #[T


unction setUp(): void
    {
        parent::setUp();

        $this->message = new Message(new Email());
    }

    public function testFromMethod(): void
    {
        $this->assertSame($this->message, $this->message->from('foo@bar.baz', 'Foo'));
        $this->assertEquals(new Address('foo@bar.baz', 'Foo'), $this->message->getSymfonyMessage()->getFrom()[0]);
    }

    public function testSenderMethod(): void
    {
        $this->assertSame($this->message, $this->message->sender('foo@bar.baz', 'Foo'));

e->returnPath('foo@bar.baz'));
        $this->assertEquals(new Address('foo@bar.baz'), $this->message->getSymfonyMessage()->getReturnPath());
    }

    public function testToMethod(): void
    {
        $this->assertSame($this->message, $this->message->to

      $this->assertEquals(new Address('foo@bar.baz', 'Foo'), $this->message->getSymfonyMessage()->getSender());
    }

    public function testReturnPathMethod(): void
    {
        $this->assertSame($this->message, $this->messag


pace Illuminate\Tests\Mail;

use Orchestra\Testbench\TestCase;
use Symfony\Component\Mailer\Transport\RoundRobinTransport;

class MailRoundRobinTransportTest extends TestCase
{
    public function testGetRoundRobinTransportWithConfiguredTransports(): void
    {
        $this->app['config']->set('mail.default', 'roundrobin');

        $this->app['config']->set('mail.mailers', [
            'roundrobin' => [
                'transport' => 'roundrobin',
                'mailers' => [
                    'sendm

=> [
                'transport' => 'array',
            ],
        ]);

        $transport = app('mailer')->getSymfonyTransport();
        $this->assertInstanceOf(RoundRobinTransport::class, $transport);
    }

    public function testGetRoundRobinTranspo

ail',
                    'array',
                ],
            ],

            'sendmail' => [
                'transport' => 'sendmail',
                'path' => '/usr/sbin/sendmail -bs',
            ],

            'array'


SesClient;
use Illuminate\Config\Repository;
use Illuminate\Container\Container;
use Illuminate\Mail\MailManager;
use Illuminate\Mail\Transport\SesTransport;
use Illuminate\View\Factory;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mailer\Header\MetadataHeader;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;

class MailSesTransportTest extends TestCase
{
    public function testGetTransport(): void

t' => 'bar',
                    'region' => 'us-east-1',
                ],
            ]);
        });

        $manager = new MailManager($container);

        /** @var \Illuminate\Mail\Transport\SesTransport $transport */
        $transport = $manager-

  {
        $container = new Container;

        $container->singleton('config', function () {
            return new Repository([
                'services.ses' => [
                    'key' => 'foo',
                    'secre


2\SesV2Client;
use Illuminate\Config\Repository;
use Illuminate\Container\Container;
use Illuminate\Mail\MailManager;
use Illuminate\Mail\Transport\SesV2Transport;
use Illuminate\View\Factory;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mailer\Header\MetadataHeader;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;

class MailSesV2TransportTest extends TestCase
{
    public function testGetTransport():

  'secret' => 'bar',
                    'region' => 'us-east-1',
                ],
            ]);
        });

        $manager = new MailManager($container);

        /** @var \Illuminate\Mail\Transport\SesV2Transport $transport */
        $transport =

 void
    {
        $container = new Container;

        $container->singleton('config', function () {
            return new Repository([
                'services.ses' => [
                    'key' => 'foo',


ddress;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use PHPUnit\Framework\TestCase;
use ReflectionClass;

class MailableAlternativeSyntaxTest extends TestCase
{
    public function testBasicMailableInspection(): void
    {
        $mailable = new MailableWithAlternativeSyntax;

        $this->assertTrue($mailable->hasTo('taylor@laravel.com'));
        $this->assertTrue($mailable->hasCc('adam@laravel.com'));
        $this->assertTrue($mailable->hasBcc('tyler@laravel.com'));

gail Otwell'));
        $this->assertTrue($mailable->hasTo('taylor@laravel.com', 'Taylor Otwell'));

        $this->assertTrue($mailable->hasSubject('Test Subject'));
        $this->assertFalse($mailable->hasSubject('Wrong Subject'));
        $this->assert

        $this->assertTrue($mailable->hasTo('taylor@laravel.com', 'Taylor Otwell'));
        $this->assertFalse($mailable->hasTo('taylor@laravel.com', 'Wrong Name'));

        $mailable->to(new Address('abigail@laravel.com', 'Abi


ation\Testing\Concerns;

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Auth\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
use Orchestra\Testbench\Attributes\WithMigration;
use Orchestra\Testbench\TestCase;

#[WithMigration]
class InteractsWithAuthenticationTest extends TestCase
{
    use RefreshDatabase;

    protected function define

tabase()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->renameColumn('name', 'username');
        });

        Schema::table('users', function (Blueprint $table) {
            $table->tinyInteger('is_active')->defaul

Environment($app)
    {
        $app['config']->set('auth.guards.api', [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ]);
    }

    protected function afterRefreshingDa


pace Illuminate\Tests\Integration\Http;

use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Route;
use JsonSerializable;
use Orchestra\Testbench\TestCase;

class JsonResponseTest extends TestCase
{
    public function testResponseWithInvalidJsonThrowsException()
    {
        $this->expectException('InvalidArgumentException');
        $this->expectExceptionMessage('Malformed UTF-8 characters, possibly incorrectly encoded');

        Route::get('/respo

        }
            });
        });

        $this->withoutExceptionHandling();

        $this->get('/response');
    }

    public function testResponseSetDataPassesWithPriorJsonErrors()
    {
        $response = new JsonResponse();

        // Trigger

nse', function () {
            return new JsonResponse(new class implements JsonSerializable
            {
                public function jsonSerialize(): string
                {
                    return "\xB1\x31";


\Concerns\InteractsWithRedis;
use Illuminate\Support\Facades\Cache;
use Orchestra\Testbench\TestCase;

class RedisCacheLockTest extends TestCase
{
    use InteractsWithRedis;

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

        $this->setUpRedis();
    }

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

        parent::tearDown();
    }

    public function testRedisLocksCanBeAcquiredAndReleased()
    {
        Cache::store('redis')->lock('foo')->forceR

he::store('redis')->lock('foo', 10);
        $this->assertTrue($lock->get());
        $this->assertFalse(Cache::store('redis')->lock('foo', 10)->get());
        Cache::store('redis')->lock('foo')->release();
    }

    public function testRedisLockCanHaveA

elease();

        $lock = Cache::store('redis')->lock('foo', 10);
        $this->assertTrue($lock->get());
        $this->assertFalse(Cache::store('redis')->lock('foo', 10)->get());
        $lock->release();

        $lock = Cac


ckTimeoutException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Sleep;
use Orchestra\Testbench\Attributes\WithConfig;
use Orchestra\Testbench\TestCase;
use Throwable;

#[WithConfig('cache.default', 'file')]
class FileCacheLockTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        // flush lock from previous tests
        Cache::lock('foo')->forceRelease();
    }

    public function testLocksCanBeAcquiredAndReleased()
    {
        $lock = Cache

      $this->assertFalse(Cache::lock('foo', 10)->get());
        Cache::lock('foo')->release();
    }

    public function testLocksCanBlockForSeconds()
    {
        $this->assertSame('taylor', Cache::lock('foo', 10)->block(1, function () {
            re

::lock('foo', 10);
        $this->assertTrue($lock->get());
        $this->assertFalse(Cache::lock('foo', 10)->get());
        $lock->release();

        $lock = Cache::lock('foo', 10);
        $this->assertTrue($lock->get());


estbench\Attributes\WithConfig;
use Orchestra\Testbench\TestCase;

class FoundationHelpersTest extends TestCase
{
    public function testRescue()
    {
        $this->assertSame(
            'rescued!',
            rescue(function () {
                throw new Exception;
            }, 'rescued!')
        );

        $this->assertSame(
            'rescued!',
            rescue(function () {
                throw new Exception;
            }, function () {
                return 'rescued!';
            })

            public function test(int $a)
            {
                return $a;
            }
        };

        $this->assertSame(
            'rescued!',
            rescue(function () use ($testClass) {
                $testClass->test([]);

        );

        $this->assertSame(
            'no need to rescue',
            rescue(function () {
                return 'no need to rescue';
            }, 'rescued!')
        );

        $testClass = new class
        {


ingMaintenance;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Route;
use Orchestra\Testbench\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;
use Symfony\Component\HttpFoundation\Cookie;

class MaintenanceModeTest extends TestCase
{
    protected function setUp(): void
    {
        $this->beforeApplicationDestroyed(function () {
            @unlink(storage_path('framework/down'));
        });

        parent::setUp();
    }

    public function

       return 'Hello World';
        })->middleware(PreventRequestsDuringMaintenance::class);

        $response = $this->get('/foo');

        $response->assertStatus(503);
        $response->assertHeader('Retry-After', '60');
        $response->assertHea

testBasicMaintenanceModeResponse()
    {
        file_put_contents(storage_path('framework/down'), json_encode([
            'retry' => 60,
            'refresh' => 60,
        ]));

        Route::get('/foo', function () {


te\Tests\Integration\Foundation\Console;

use Illuminate\Testing\Assert;
use Orchestra\Testbench\Attributes\WithEnv;
use Orchestra\Testbench\TestCase;

use function Orchestra\Testbench\remote;

class AboutCommandTest extends TestCase
{
    public function testItCanDisplayAboutCommandAsJson()
    {
        $process = remote('about --json', ['APP_ENV' => 'local'])->mustRun();

        tap(json_decode($process->getOutput(), true), function ($output) {
            Assert::assertArraySubset([
                'ap

=> false,
            ], $output['environment']);

            Assert::assertArraySubset([
                'config' => false,
                'events' => false,
                'routes' => false,
            ], $output['cache']);

            Assert::asser

plication_name' => 'Laravel',
                'php_version' => PHP_VERSION,
                'environment' => 'local',
                'debug_mode' => true,
                'url' => 'localhost',
                'maintenance_mode'


ation\Console;

use Illuminate\Filesystem\Filesystem;
use Illuminate\Foundation\Bootstrap\LoadConfiguration;
use Illuminate\Support\ServiceProvider;
use Orchestra\Testbench\Concerns\InteractsWithPublishedFiles;
use Orchestra\Testbench\TestCase;

use function Orchestra\Testbench\package_path;

class ConfigPublishCommandTest extends TestCase
{
    use InteractsWithPublishedFiles;

    protected array $files = [
        'config-stubs/*.php',
    ];

    #[\Override]
    protected function setUp(): void
    {

stroyed(function () use ($files) {
            $files->deleteDirectory($this->app->basePath('config-stubs'));
        });

        parent::setUp();
    }

    #[\Override]
    protected function resolveApplicationConfiguration($app)
    {
        $app->ins

       $files = new Filesystem();

        $this->afterApplicationCreated(function () use ($files) {
            $files->ensureDirectoryExists($this->app->basePath('config-stubs'));
        });

        $this->beforeApplicationDe


te\Tests\Integration\Foundation\Console;

use Illuminate\Foundation\Console\ClosureCommand;
use Illuminate\Support\ServiceProvider;
use Illuminate\Tests\Integration\Generators\TestCase;
use Orchestra\Testbench\Concerns\InteractsWithPublishedFiles;

class OptimizeCommandTest extends TestCase
{
    use InteractsWithPublishedFiles;

    protected $files = [
        'bootstrap/cache/config.php',
        'bootstrap/cache/events.php',
        'bootstrap/cache/routes-v7.php',
    ];

    protected function getPack

timize')
            ->assertSuccessful()
            ->expectsOutputToContain('my package');
    }

    public function testCanExcludeCommandsByKey(): void
    {
        $this->artisan('optimize', ['--except' => 'my package'])
            ->assertSuccessf

ageProviders($app): array
    {
        return [ServiceProviderWithOptimize::class];
    }

    public function testCanListenToOptimizingEvent(): void
    {
        $this->withoutDeprecationHandling();

        $this->artisan('op


Illuminate\Tests\Integration\Foundation\Fixtures\Providers;

use Illuminate\Console\Application;
use Illuminate\Support\ServiceProvider;
use Illuminate\Tests\Integration\Foundation\Fixtures\Console\ThrowExceptionCommand;
use Illuminate\Tests\Integration\Foundation\Fixtures\Logs\ThrowExceptionLogHandler;

class ThrowUncaughtExceptionServiceProvider extends ServiceProvider
{
    public function register()
    {
        $config = $this->app['config'];

        $config->set('logging.default', 'throw_exception')

ption', [
            'driver' => 'monolog',
            'handler' => ThrowExceptionLogHandler::class,
        ]);
    }

    public function boot()
    {
        Application::starting(function ($artisan) {
            $artisan->add(new ThrowExceptionComma

;

        $config->set('logging.channels.throw_exce


hp

namespace Illuminate\Tests\Integration\Foundation\Testing\Concerns;

use Illuminate\Http\Request;
use Illuminate\Support\Uri;
use Orchestra\Testbench\Attributes\WithConfig;
use Orchestra\Testbench\TestCase;

#[WithConfig('app.key', 'base64:IUHRqAQ99pZ0A1MPjbuv1D6ff3jxv0GIvS2qIW4JNU4=')]
class MakeHttpRequestsTest extends TestCase
{
    /** {@inheritDoc} */
    protected function defineWebRoutes($router)
    {
        $router->get('decode', fn (Request $request) => [
            'url' => $request->fullUr

arch' => 'Laravel']))
            ->assertSuccessful()
            ->assertJson([
                'url' => 'http://localhost/decode?editMode=create&editing=1&search=Laravel',
                'query' => [
                    'editing' => '1',

l(),
            'query' => $request->query(),
        ]);
    }

    public function test_it_can_use_uri_to_make_request()
    {
        $this->getJson(Uri::of('decode')->withQuery(['editing' => true, 'editMode' => 'create', 'se


\Attributes\WithConfig;
use Orchestra\Testbench\TestCase;

use function Orchestra\Testbench\after_resolving;
use function Orchestra\Testbench\package_path;

#[WithConfig('app.debug', true)]
class RenderBladeFilesTest extends TestCase
{
    protected function defineEnvironment($app)
    {
        after_resolving($app, 'view.engine.resolver', function ($resolver) {
            $resolver->resolve('blade')->getCompiler()->withoutComponentTags();
        });
    }

    public function testFormattedSourceTooltipR

       return '';
            }

            public function callable()
            {
                return 'throw';
            }

            public function source()
            {
                return "Foo::bar(1)\nAnother line";
            }

endersMultilineSafely(): void
    {
        $frame = new class
        {
            public function class()
            {
                return null;
            }

            public function operator()
            {


te\Tests\Integration\Cookie;

use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Http\Response;
use Illuminate\Session\NullSessionHandler;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
use Mockery as m;
use Orchestra\Testbench\TestCase;

class CookieTest extends TestCase
{
    public function test_cookie_is_sent_back_with_proper_expire_time_when_should_expire_on_close()
    {
        $this->app['config']-

->getCookies());
        $this->assertEquals(0, $response->headers->getCookies()[1]->getExpiresTime());
    }

    public function test_cookie_is_sent_back_with_proper_expire_time_with_respect_to_lifetime()
    {
        $this->app['config']->set('session.

>set('session.expire_on_close', true);

        Route::get('/', function () {
            return 'hello world';
        })->middleware('web');

        $response = $this->get('/');
        $this->assertCount(2, $response->headers


te\Tests\Integration\Events;

use Illuminate\Database\DatabaseTransactionsManager;
use Illuminate\Support\Facades\Event;
use Mockery as m;
use Orchestra\Testbench\TestCase;

class ListenerTest extends TestCase
{
    protected function tearDown(): void
    {
        ListenerTestListener::$ran = false;
        ListenerTestListenerAfterCommit::$ran = false;

        parent::tearDown();
    }

    public function testClassListenerRunsNormallyIfNoTransactions()
    {
        $this->app->singleton('db.transaction

        });

        Event::listen(ListenerTestEvent::class, ListenerTestListener::class);

        Event::dispatch(new ListenerTestEvent);

        $this->assertTrue(ListenerTestListener::$ran);
    }

    public function testClassListenerDoesntRunInsideT

s', function () {
            $transactionManager = m::mock(DatabaseTransactionsManager::class);
            $transactionManager->shouldNotReceive('addCallback')->once()->andReturn(null);

            return $transactionManager;


mitTestEvent::$ran = false;
        AnotherShouldDispatchAfterCommitTestEvent::$ran = false;

        parent::tearDown();
    }

    public function testEventIsDispatchedIfThereIsNoTransaction()
    {
        Event::listen(ShouldDispatchAfterCommitTestEvent::class, ShouldDispatchAfterCommitListener::class);

        Event::dispatch(new ShouldDispatchAfterCommitTestEvent);

        $this->assertTrue(ShouldDispatchAfterCommitTestEvent::$ran);
    }

    public function testEventIsNotDispatchedIfTransactionFai

erCommitTestEvent);

                throw new \Exception;
            });
        } catch (\Exception) {
        }

        $this->assertFalse(ShouldDispatchAfterCommitTestEvent::$ran);
    }

    public function testEventIsDispatchedIfTransactionSucceeds

ls()
    {
        Event::listen(ShouldDispatchAfterCommitTestEvent::class, ShouldDispatchAfterCommitListener::class);

        try {
            DB::transaction(function () {
                Event::dispatch(new ShouldDispatchAft


ation\Support\Providers;

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider;
use Illuminate\Support\Facades\Route;
use Illuminate\Testing\Assert;
use Orchestra\Testbench\Attributes\WithConfig;
use Orchestra\Testbench\TestCase;

#[WithConfig('filesystems.disks.local.serve', false)]
class RouteServiceProviderTest extends TestCase
{
    /**
     * Resolve

thProviders([
                AppRouteServiceProvider::class,
            ])
            ->withRouting(
                using: function () {
                    Route::get('login', fn () => 'Login')->name('login');
                }
            )

 application implementation.
     *
     * @return \Illuminate\Foundation\Application
     */
    protected function resolveApplication()
    {
        return Application::configure(static::applicationBasePath())
            ->wi


stra\Testbench\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;
use Throwable;

#[WithConfig('hashing.driver', 'bcrypt')]
#[WithMigration]
class ThrottleRequestsTest extends TestCase
{
    use RefreshDatabase;

    public function testLockOpensImmediatelyAfterDecay()
    {
        Carbon::setTestNow(Carbon::create(2018, 1, 1, 0, 0, 0));

        Route::get('/', function () {
            return 'yes';
        })->middleware(ThrottleRequests::class.':2,1');

        $response = $this->withoutException

maining'));

        $response = $this->withoutExceptionHandling()->get('/');
        $this->assertSame('yes', $response->getContent());
        $this->assertEquals(2, $response->headers->get('X-RateLimit-Limit'));
        $this->assertEquals(0, $response-

Handling()->get('/');
        $this->assertSame('yes', $response->getContent());
        $this->assertEquals(2, $response->headers->get('X-RateLimit-Limit'));
        $this->assertEquals(1, $response->headers->get('X-RateLimit-Re


ents;
use Illuminate\Support\Stringable;
use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\Events\EventOne;
use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\Events\EventTwo;
use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\Listeners\AbstractListener;
use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\Listeners\Listener;
use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\Listeners\ListenerInterface;
use Illuminate\Tests

\Integration\Foundation\Fixtures\EventDiscovery\UnionListeners\UnionListener;
use Orchestra\Testbench\TestCase;
use SplFileInfo;

class DiscoverEventsTest extends TestCase
{
    protected function tearDown(): void
    {
        DiscoverEvents::$guessClassN


der;
use Orchestra\Testbench\TestCase;

class FoundationServiceProvidersTest extends TestCase
{
    protected function getPackageProviders($app)
    {
        return [HeadServiceProvider::class];
    }

    public function testItCanBootServiceProviderRegisteredFromAnotherServiceProvider()
    {
        $this->assertTrue($this->app['tail.registered']);
        $this->assertTrue($this->app['tail.booted']);
    }
}

class HeadServiceProvider extends ServiceProvider
{
    public function register()
    {

 $this->app->register(TailServiceProvider::class);
    }
}

class TailServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app['tail.registered'] = true;
    }

    public function boot()
    {
        $this->app['t

  //
    }

    public function boot()
    {


class RoutingServiceProviderTest extends TestCase
{
    public function testItIncludesMergedDataInServerRequestInterfaceInstancesUsingGetRequests()
    {
        Route::get('test-route', function (ServerRequestInterface $request) {
            return $request->getParsedBody();
        })->middleware(MergeDataMiddleware::class);

        $response = $this->withoutExceptionHandling()->get('test-route?'.http_build_query([
            'sent' => 'sent-data',
            'overridden' => 'overridden-sent-data',

()
    {
        Route::get('test-route', function (ServerRequestInterface $request) {
            return $request->getParsedBody();
        });

        $response = $this->withoutExceptionHandling()->get('test-route', [
            'content-type' => 'appl

        ]));

        $response->assertOk();
        $response->assertExactJson([
            'request-data' => 'request-data',
        ]);
    }

    public function testItWorksNormallyWithoutMergeDataMiddlewareWithEmptyRequests


hp

namespace Illuminate\Tests\Integration\Foundation\Configuration;

use Illuminate\Auth\Middleware\Authenticate;
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Route;
use Orchestra\Testbench\TestCase;

class PrefersJsonDisabledTest extends TestCase
{
    protected function resolveApplication()
    {
        return Application::configure(static::applicationBasePath())
            ->withMiddleware()
            ->create();
    }

    public function testPlainStringRouteReturnsHtmlUnde

pe', 'text/html; charset=UTF-8');
    }

    public function testUnauthenticatedWildcardStillRedirectsWhenDisabled()
    {
        Route::get('login', fn () => 'login page')->name('login');

        Route::get('protected', fn () => 'secret')->middleware(Au

rWildcardAcceptWhenDisabled()
    {
        Route::get('plain', fn () => 'hello');

        $this->get('plain', ['Accept' => '*/*'])
            ->assertOk()
            ->assertSee('hello')
            ->assertHeader('Content-Ty


s\Renderer\Listener;
use Illuminate\Foundation\Exceptions\Renderer\Renderer;
use Illuminate\Foundation\Providers\FoundationServiceProvider;
use Mockery as m;
use Orchestra\Testbench\Attributes\WithConfig;
use Orchestra\Testbench\TestCase;
use RuntimeException;

class RendererTest extends TestCase
{
    protected function defineRoutes($router)
    {
        $router->get('failed', fn () => throw new RuntimeException('Bad route!'));
        $router->get('failed-with-previous', function () {
            throw n

           )
            );
        });
    }

    #[WithConfig('app.debug', true)]
    public function testItCanRenderExceptionPage()
    {
        $this->assertTrue($this->app->bound(Renderer::class));

        $this->get('/failed')
            ->assertI

ew RuntimeException(
                'First exception', previous: new RuntimeException(
                    'Second exception', previous: new RuntimeException(
                        'Third exception'
                    )


uminate\Support\Facades\Event;
use Orchestra\Testbench\TestCase;

class DeferEventsTest extends TestCase
{
    public function testDeferEvents()
    {
        unset($_SERVER['__event.test']);

        Event::listen('foo', function ($foo) {
            $_SERVER['__event.test'] = $foo;
        });

        $response = Event::defer(function () {
            Event::dispatch('foo', ['bar']);

            $this->assertArrayNotHasKey('__event.test', $_SERVER);

            return 'callback_result';
        });

Model::saved(function () {
            $_SERVER['__model_event.test'][] = 'saved';
        });

        $response = Event::defer(function () {
            $model = new TestModel();
            $model->fireModelEvent('saved', false);

            $this->ass

      $this->assertSame('callback_result', $response);
        $this->assertSame('bar', $_SERVER['__event.test']);
    }

    public function testDeferModelEvents()
    {
        $_SERVER['__model_event.test'] = [];

        Test


ation\Support\Providers;

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Events\DiagnosingHealth;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Str;
use Orchestra\Testbench\Attributes\WithConfig;
use Orchestra\Testbench\TestCase;
use RuntimeException;

#[WithConfig('app.debug', false)]
#[WithConfig('filesystems.disks.local.serve', false)]
class RouteServiceProviderHealthTest extends TestCase
{
    /**
     * Resolve application implementation.
     *
     * @return \Illumina

                health: '/up',
            )->create();
    }

    protected function defineEnvironment($app)
    {
        $app['config']->set('app.key', Str::random(32));
    }

    public function test_it_can_load_health_page()
    {
        $this->get

te\Foundation\Application
     */
    protected function resolveApplication()
    {
        return Application::configure(static::applicationBasePath())
            ->withRouting(
                web: __DIR__.'/fixtures/web.php',


ts\Support\Responsable;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Middleware\PrefersJsonResponses;
use Illuminate\Routing\ResponseFactory;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Monolog\Handler\TestHandler;
use Orchestra\Testbench\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;
use Symfony\Component\Process\PhpProcess;
use Throwa

lveApplicationExceptionHandler($app)
    {
        $app->singleton('Illuminate\Contracts\Debug\ExceptionHandler', 'Illuminate\Foundation\Exceptions\Handler');
    }

    public function testItRendersAuthorizationExceptions()
    {
        Route::get('test-

ble;

class ExceptionHandlerTest extends TestCase
{
    /**
     * Resolve application HTTP exception handler.
     *
     * @param  \Illuminate\Foundation\Application  $app
     * @return void
     */
    protected function reso


pace Illuminate\Tests\Integration\Foundation\Console;

use Illuminate\Foundation\Console\ClosureCommand;
use Illuminate\Support\ServiceProvider;
use Illuminate\Tests\Integration\Generators\TestCase;

class OptimizeClearCommandTest extends TestCase
{
    protected function getPackageProviders($app): array
    {
        return [ServiceProviderWithOptimizeClear::class];
    }

    public function testCanListenToOptimizingEvent(): void
    {
        $this->withoutDeprecationHandling();

        $this->artisan('

ar', ['--except' => 'my package'])
            ->assertSuccessful()
            ->doesntExpectOutputToContain('my package');
    }

    public function testCanExcludeCommandsByCommand(): void
    {
        $this->artisan('optimize:clear', ['--except' => 'm

optimize:clear')
            ->assertSuccessful()
            ->expectsOutputToContain('ServiceProviderWithOptimizeClear');
    }

    public function testCanExcludeCommandsByKey(): void
    {
        $this->artisan('optimize:cle


\Auth\Middleware\Authenticate;
use Illuminate\Auth\Middleware\EnsureEmailIsVerified;
use Illuminate\Auth\Middleware\RequirePassword;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Validation\ValidationException;
use Orchestra\Testbench\TestCase;

class PrefersJsonTest extends Te

eReturnsJsonUnderWildcardAccept()
    {
        Route::get('payload', fn () => ['message' => 'hello']);

        $this->get('payload', ['Accept' => '*/*'])
            ->assertOk()
            ->assertHeader('Content-Type', 'application/json')

stCase
{
    protected function resolveApplication()
    {
        return Application::configure(static::applicationBasePath())
            ->prefersJsonResponses()
            ->create();
    }

    public function testArrayRout


Middleware;

use Illuminate\Auth\Middleware\RedirectIfAuthenticated;
use Illuminate\Contracts\Routing\Registrar;
use Illuminate\Support\Str;
use Illuminate\Tests\Integration\Auth\Fixtures\AuthenticationTestUser;
use Orchestra\Testbench\Factories\UserFactory;
use Orchestra\Testbench\TestCase;

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

        $this->withoutExceptionHandling();

        /** @var \Illuminate\Contracts\Routing\Regis

       UserFactory::new()->create();

        $user = AuthenticationTestUser::first();
        $this->router->get('/login', function () {
            return response('Login Form');
        })->middleware(RedirectIfAuthenticated::class);

        UserFactor

trar $router */
        $this->router = $this->app->make(Registrar::class);

        $this->router->get('/login', function () {
            return response('Login Form');
        })->middleware(RedirectIfAuthenticated::class);


m;
use Illuminate\Tests\Integration\Generators\TestCase;
use LogicException;
use Orchestra\Testbench\Concerns\InteractsWithPublishedFiles;

class ConfigCacheCommandTest extends TestCase
{
    use InteractsWithPublishedFiles;

    protected $files = [
        'bootstrap/cache/config.php',
        'config/testconfig.php',
    ];

    protected function setUp(): void
    {
        $files = new Filesystem;

        $this->afterApplicationCreated(function () use ($files) {
            $files->ensureDirectoryExis

  public function testConfigurationCanBeCachedSuccessfully()
    {
        $files = new Filesystem;
        $files->put($this->app->configPath('testconfig.php'), <<<'PHP'
            <?php

            return [
                'string' => 'value',

ts($this->app->configPath());
        });

        $this->beforeApplicationDestroyed(function () use ($files) {
            $files->delete($this->app->configPath('testconfig.php'));
        });

        parent::setUp();
    }


s;

use Illuminate\Events\CallQueuedListener;
use Illuminate\Events\InvokeQueuedClosure;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Event;
use Laravel\SerializableClosure\SerializableClosure;
use Orchestra\Testbench\TestCase;

class QueuedClosureListenerTest extends TestCase
{
    public function testAnonymousQueuedListenerIsQueued()
    {
        Bus::fake();

        Event::listen(\Illuminate\Events\queueable(function (TestEvent $event) {
            //
        })->catch(function (

s == InvokeQueuedClosure::class;
        });
    }

    public function testAnonymousQueuedListenerIsQueuedOnMessageGroup()
    {
        $messageGroup = 'group-1';

        Bus::fake();

        Event::listen(\Illuminate\Events\queueable(function (TestEve

TestEvent $event) {
            //
        })->onConnection(null)->onQueue(null));

        Event::dispatch(new TestEvent);

        Bus::assertDispatched(CallQueuedListener::class, function ($job) {
            return $job->clas


e\Schema\Blueprint;
use Illuminate\Foundation\Testing\LazilyRefreshDatabase;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Schema;
use Orchestra\Testbench\TestCase;
use PHPUnit\Framework\ExpectationFailedException;

class EventFakeTest extends TestCase
{
    use LazilyRefreshDatabase;

    protected function afterRefreshingDatabase()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->in

fExists('posts');
    }

    public function testNonFakedEventGetsProperlyDispatched()
    {
        Event::fake(NonImportantEvent::class);
        Post::observe([PostObserver::class]);

        $post = new Post;
        $post->title = 'xyz';
        $post

crements('id');
            $table->string('title');
            $table->string('slug')->unique();
            $table->timestamps();
        });
    }

    protected function beforeRefreshingDatabase()
    {
        Schema::dropI


uminate\Container\Container;
use Illuminate\Routing\Attributes\Controllers\Middleware;
use Illuminate\Routing\Controller as RoutingController;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Route;
use Override;
use PHPUnit\Framework\TestCase;

class RoutingControllerAttributeTest extends TestCase
{
    public function testControllerMiddlewareAttributesAreInherited()
    {
        $route = new Route('GET', 'foo', ['uses' => InheritMiddlewareController::class.'@index']);
        $rou

Route('GET', 'foo', ['uses' => InheritMiddlewareDeclarationOrderController::class.'@index']);
        $route->setContainer(new Container);

        $this->assertEquals(['middleware1', 'middleware2', 'middleware3'], $route->gatherMiddleware());
    }

    p

te->setContainer(new Container);

        $this->assertEquals(['auth', 'log'], $route->gatherMiddleware());
    }

    public function testControllerMiddlewareAttributesAreInheritedInDeclarationOrder()
    {
        $route = new


espace Illuminate\Tests\Console\Fixtures;

use Illuminate\Console\Command;
use Illuminate\Contracts\Console\PromptsForMissingInput;
use Laravel\Prompts\Prompt;
use Laravel\Prompts\TextPrompt;
use Symfony\Component\Console\Input\InputInterface;

class FakeCommandWithArrayInputPrompting extends Command implements PromptsForMissingInput
{
    protected $signature = 'fake-command-for-testing-array {names* : An array argument}';

    public $prompted = false;

    protected function configurePrompts(InputInterfa

 {
        Prompt::interactive(true);
        Prompt::fallbackWhen(true);

        TextPrompt::fallbackUsing(function () {
            $this->prompted = true;

            return 'foo';
        });
    }

    public function handle(): int
    {
        ret


      return 'hello';
        });
        $router->post('foo/bar', function () {
            return 'post hello';
        });
        $this->assertSame('hello', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent());
        $this->assertSame('post hello', $router->dispatch(Request::create('foo/bar', 'POST'))->getContent());

        $router = $this->getRouter();
        $router->get('foo/{bar}', function ($name) {
            return $name;
        });
        $this->assertSame('taylor', $route

his->assertSame('taylor25', $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent());

        $router = $this->getRouter();
        $router->get('foo/{name}/boom/{age?}/{location?}', function ($name, $age = 25, $location = 'AR') {

r->dispatch(Request::create('foo/taylor', 'GET'))->getContent());

        $router = $this->getRouter();
        $router->get('foo/{bar}/{baz?}', function ($name, $age = 25) {
            return $name.$age;
        });
        $t


aseController;

class FooController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return \Illuminate\Http\Response
     */
    public f

     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *

unction store()
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**


{
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function store()
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)

cified resource in storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update($id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id

   {
        //
    }

    /**
     * Update the spe


te\Tests\Bus;

use Illuminate\Bus\Batchable;
use Illuminate\Bus\BatchRepository;
use Illuminate\Container\Container;
use Illuminate\Support\Testing\Fakes\BatchFake;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class BusBatchableTest extends TestCase
{
    public function test_batch_may_be_retrieved()
    {
        $class = new class
        {
            use Batchable;
        };

        $this->assertSame($class, $class->withBatchId('test-batch-id'));
        $this->assertSame('test-batch-id', $class

        $container->instance(BatchRepository::class, $repository);

        $this->assertSame('test-batch', $class->batch());

        Container::setInstance(null);
    }

    public function test_with_fake_batch_sets_and_returns_fake()
    {
        $job

->batchId);

        Container::setInstance($container = new Container);

        $repository = m::mock(BatchRepository::class);
        $repository->shouldReceive('find')->once()->with('test-batch-id')->andReturn('test-batch');


m;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use stdClass;

class PendingDispatchWithoutDestructor extends PendingDispatch
{
    public function __destruct()
    {
        // Prevent the job from being dispatched
    }
}

class BusPendingDispatchTest extends TestCase
{
    protected $job;

    /**
     * @var PendingDispatchWithoutDestructor
     */
    protected $pendingDispatch;

    protected function setUp(): void
    {
        $this->job = m::mock(stdClass::class);
        $this->pendingDisp

his->pendingDispatch->onConnection('test-connection');
    }

    public function testOnQueue()
    {
        $this->job->shouldReceive('onQueue')->once()->with('test-queue');
        $this->pendingDispatch->onQueue('test-queue');
    }

    public functio

atch = new PendingDispatchWithoutDestructor($this->job);

        parent::setUp();
    }

    public function testOnConnection()
    {
        $this->job->shouldReceive('onConnection')->once()->with('test-connection');
        $t


ate\Bus\Queueable;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

class QueueableTest extends TestCase
{
    public static function connectionDataProvider(): array
    {
        return [
            'uses string' => ['redis', 'redis'],
            'uses BackedEnum #1' => [ConnectionEnum::SQS, 'sqs'],
            'uses BackedEnum #2' => [ConnectionEnum::REDIS, 'redis'],
            'uses null' => [null, null],
        ];
    }

    #[DataProvider('connectionDataProvider')]

aProvider('connectionDataProvider')]
    public function testAllOnConnection(mixed $connection, ?string $expected): void
    {
        $job = new FakeJob();
        $job->allOnConnection($connection);

        $this->assertSame($job->connection, $expected)

  public function testOnConnection(mixed $connection, ?string $expected): void
    {
        $job = new FakeJob();
        $job->onConnection($connection);

        $this->assertSame($job->connection, $expected);
    }

    #[Dat


e Mockery as m;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Question\ChoiceQuestion;

class CommandTest extends TestCase
{
    public function testCallingClassCommandResolveCommandViaApplicationResolution()
    {
        $command = new class ext

[]);
        $output = new NullOutput;
        $outputStyle = m::mock(OutputStyle::class);
        $application->shouldReceive('make')->with(OutputStyle::class, ['input' => $input, 'output' => $output])->andReturn($outputStyle);
        $application->shoul

ends Command
        {
            public function handle()
            {
            }
        };

        $application = m::mock(Application::class);
        $command->setLaravel($application);

        $input = new ArrayInput(


vel\Prompts\Prompt;
use Mockery as m;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;

use function Laravel\Prompts\multiselect;
use function Laravel\Prompts\select;

class ConfiguresPromptsTest extends TestCase
{
    #[DataProvider('selectDataProvider')]
    public function testSelectFallback($prompt, $expectedOptions, $expectedDefault, $return, $expectedReturn)
    {
        Prom

            }

            public function handle()
            {
                $this->answer = ($this->prompt)();
            }
        };

        $this->runCommand($command, fn ($components) => $components
            ->expects('choice')

pt::fallbackWhen(true);

        $command = new class($prompt) extends Command
        {
            public $answer;

            public function __construct(protected $prompt)
            {
                parent::__construct();


lication;
use Illuminate\Foundation\Console\Kernel;
use Illuminate\Tests\Console\Fixtures\FakeCommandWithArrayInputPrompting;
use Illuminate\Tests\Console\Fixtures\FakeCommandWithInputPrompting;
use Mockery as m;
use Orchestra\Testbench\Concerns\InteractsWithMockery;
use Orchestra\Testbench\Foundation\Application as Testbench;
use PHPUnit\Framework\Attributes\RunInSeparateProcess;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command

nTest extends TestCase
{
    use InteractsWithMockery;

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

        parent::tearDown();
    }

    public function testAddSetsLaravelInstance()
    {

 as SymfonyCommand;
use Symfony\Component\Console\Exception\CommandNotFoundException;
use Throwable;

use function Illuminate\Filesystem\join_paths;
use function Orchestra\Testbench\default_skeleton_path;

class ConsoleApplicatio