prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
\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...
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
{ "filepath": "tests/Integration/Cache/RedisCacheLockTest.php", "language": "php", "file_size": 4692, "cut_index": 614, "middle_length": 229 }
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 { pa...
$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());
{ "filepath": "tests/Integration/Cache/FileCacheLockTest.php", "language": "php", "file_size": 4591, "cut_index": 614, "middle_length": 229 }
estbench\Attributes\WithConfig; use Orchestra\Testbench\TestCase; class FoundationHelpersTest extends TestCase { public function testRescue() { $this->assertSame( 'rescued!', rescue(function () { throw new Exception; }, '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 {
{ "filepath": "tests/Integration/Foundation/FoundationHelpersTest.php", "language": "php", "file_size": 5121, "cut_index": 716, "middle_length": 229 }
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 se...
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 () {
{ "filepath": "tests/Integration/Foundation/MaintenanceModeTest.php", "language": "php", "file_size": 9524, "cut_index": 921, "middle_length": 229 }
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 = re...
=> 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'
{ "filepath": "tests/Integration/Foundation/Console/AboutCommandTest.php", "language": "php", "file_size": 1801, "cut_index": 537, "middle_length": 229 }
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 ConfigPublishCommand...
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
{ "filepath": "tests/Integration/Foundation/Console/ConfigPublishCommandTest.php", "language": "php", "file_size": 2054, "cut_index": 563, "middle_length": 229 }
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 InteractsWithPubli...
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
{ "filepath": "tests/Integration/Foundation/Console/OptimizeCommandTest.php", "language": "php", "file_size": 1653, "cut_index": 537, "middle_length": 229 }
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 ThrowUnc...
ption', [ 'driver' => 'monolog', 'handler' => ThrowExceptionLogHandler::class, ]); } public function boot() { Application::starting(function ($artisan) { $artisan->add(new ThrowExceptionComma
; $config->set('logging.channels.throw_exce
{ "filepath": "tests/Integration/Foundation/Fixtures/Providers/ThrowUncaughtExceptionServiceProvider.php", "language": "php", "file_size": 862, "cut_index": 529, "middle_length": 52 }
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 e...
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
{ "filepath": "tests/Integration/Foundation/Testing/Concerns/MakeHttpRequestsTest.php", "language": "php", "file_size": 1116, "cut_index": 515, "middle_length": 229 }
\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, '...
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() {
{ "filepath": "tests/Integration/Foundation/Exceptions/RenderBladeFilesTest.php", "language": "php", "file_size": 3113, "cut_index": 614, "middle_length": 229 }
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...
->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
{ "filepath": "tests/Integration/Cookie/CookieTest.php", "language": "php", "file_size": 1997, "cut_index": 537, "middle_length": 229 }
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; ListenerTe...
}); 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;
{ "filepath": "tests/Integration/Events/ListenerTest.php", "language": "php", "file_size": 1889, "cut_index": 537, "middle_length": 229 }
mitTestEvent::$ran = false; AnotherShouldDispatchAfterCommitTestEvent::$ran = false; parent::tearDown(); } public function testEventIsDispatchedIfThereIsNoTransaction() { Event::listen(ShouldDispatchAfterCommitTestEvent::class, ShouldDispatchAfterCommitListener::class); Ev...
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
{ "filepath": "tests/Integration/Events/ShouldDispatchAfterCommitEventTest.php", "language": "php", "file_size": 11200, "cut_index": 921, "middle_length": 229 }
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\Te...
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
{ "filepath": "tests/Integration/Foundation/Support/Providers/RouteServiceProviderTest.php", "language": "php", "file_size": 2217, "cut_index": 563, "middle_length": 229 }
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::cre...
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
{ "filepath": "tests/Integration/Http/ThrottleRequestsTest.php", "language": "php", "file_size": 24765, "cut_index": 1331, "middle_length": 229 }
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 Illuminat...
\Integration\Foundation\Fixtures\EventDiscovery\UnionListeners\UnionListener; use Orchestra\Testbench\TestCase; use SplFileInfo; class DiscoverEventsTest extends TestCase { protected function tearDown(): void { DiscoverEvents::$guessClassN
\Integration\Foundation\Fixtures\EventDiscovery\ShouldBeDiscoveredListeners\RegisteredListener; use Illuminate\Tests\Integration\Foundation\Fixtures\EventDiscovery\ShouldBeDiscoveredListeners\SkippedListener; use Illuminate\Tests
{ "filepath": "tests/Integration/Foundation/DiscoverEventsTest.php", "language": "php", "file_size": 4872, "cut_index": 614, "middle_length": 229 }
der; use Orchestra\Testbench\TestCase; class FoundationServiceProvidersTest extends TestCase { protected function getPackageProviders($app) { return [HeadServiceProvider::class]; } public function testItCanBootServiceProviderRegisteredFromAnotherServiceProvider() { $this->assertTru...
$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() {
{ "filepath": "tests/Integration/Foundation/FoundationServiceProvidersTest.php", "language": "php", "file_size": 943, "cut_index": 606, "middle_length": 52 }
class RoutingServiceProviderTest extends TestCase { public function testItIncludesMergedDataInServerRequestInterfaceInstancesUsingGetRequests() { Route::get('test-route', function (ServerRequestInterface $request) { return $request->getParsedBody(); })->middleware(MergeDataMiddlewa...
() { 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
{ "filepath": "tests/Integration/Foundation/RoutingServiceProviderTest.php", "language": "php", "file_size": 5256, "cut_index": 716, "middle_length": 229 }
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() ...
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
{ "filepath": "tests/Integration/Foundation/Configuration/PrefersJsonDisabledTest.php", "language": "php", "file_size": 1114, "cut_index": 515, "middle_length": 229 }
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 functi...
) ); }); } #[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' )
{ "filepath": "tests/Integration/Foundation/Exceptions/RendererTest.php", "language": "php", "file_size": 6056, "cut_index": 716, "middle_length": 229 }
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 = Ev...
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
{ "filepath": "tests/Integration/Events/DeferEventsTest.php", "language": "php", "file_size": 3469, "cut_index": 614, "middle_length": 229 }
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)] ...
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',
{ "filepath": "tests/Integration/Foundation/Support/Providers/RouteServiceProviderHealthTest.php", "language": "php", "file_size": 2041, "cut_index": 563, "middle_length": 229 }
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 Illumina...
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
{ "filepath": "tests/Integration/Foundation/ExceptionHandlerTest.php", "language": "php", "file_size": 11948, "cut_index": 921, "middle_length": 229 }
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 { ...
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
{ "filepath": "tests/Integration/Foundation/Console/OptimizeClearCommandTest.php", "language": "php", "file_size": 1424, "cut_index": 524, "middle_length": 229 }
\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\StartSessio...
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
{ "filepath": "tests/Integration/Foundation/Configuration/PrefersJsonTest.php", "language": "php", "file_size": 4464, "cut_index": 614, "middle_length": 229 }
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 RedirectIfAuthentica...
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);
{ "filepath": "tests/Integration/Auth/Middleware/RedirectIfAuthenticatedTest.php", "language": "php", "file_size": 3022, "cut_index": 563, "middle_length": 229 }
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'...
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(); }
{ "filepath": "tests/Integration/Foundation/Console/ConfigCacheCommandTest.php", "language": "php", "file_size": 3650, "cut_index": 614, "middle_length": 229 }
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 functio...
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
{ "filepath": "tests/Integration/Events/QueuedClosureListenerTest.php", "language": "php", "file_size": 2204, "cut_index": 563, "middle_length": 229 }
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 EventFakeTes...
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
{ "filepath": "tests/Integration/Events/EventFakeTest.php", "language": "php", "file_size": 8482, "cut_index": 716, "middle_length": 229 }
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 TestC...
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
{ "filepath": "tests/Routing/RoutingControllerAttributeTest.php", "language": "php", "file_size": 2900, "cut_index": 563, "middle_length": 229 }
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 Prompts...
{ Prompt::interactive(true); Prompt::fallbackWhen(true); TextPrompt::fallbackUsing(function () { $this->prompted = true; return 'foo'; }); } public function handle(): int { ret
ce $input)
{ "filepath": "tests/Console/Fixtures/FakeCommandWithArrayInputPrompting.php", "language": "php", "file_size": 819, "cut_index": 522, "middle_length": 14 }
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...
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
{ "filepath": "tests/Routing/RoutingRouteTest.php", "language": "php", "file_size": 98380, "cut_index": 3790, "middle_length": 229 }
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\Resp...
* 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) { // } /**
{ "filepath": "tests/Routing/fixtures/controller.php", "language": "php", "file_size": 1334, "cut_index": 524, "middle_length": 229 }
{ /** * 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() { ...
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
{ "filepath": "tests/Routing/fixtures/except_controller.php", "language": "php", "file_size": 995, "cut_index": 582, "middle_length": 52 }
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() { ...
$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');
{ "filepath": "tests/Bus/BusBatchableTest.php", "language": "php", "file_size": 1965, "cut_index": 537, "middle_length": 229 }
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; /** * @va...
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
{ "filepath": "tests/Bus/BusPendingDispatchTest.php", "language": "php", "file_size": 3968, "cut_index": 614, "middle_length": 229 }
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...
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
{ "filepath": "tests/Bus/QueueableTest.php", "language": "php", "file_size": 2176, "cut_index": 563, "middle_length": 229 }
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\C...
[]); $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(
{ "filepath": "tests/Console/CommandTest.php", "language": "php", "file_size": 9618, "cut_index": 921, "middle_length": 229 }
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 ConfiguresPromptsTe...
} 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();
{ "filepath": "tests/Console/ConfiguresPromptsTest.php", "language": "php", "file_size": 6233, "cut_index": 716, "middle_length": 229 }
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 Te...
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
{ "filepath": "tests/Console/ConsoleApplicationTest.php", "language": "php", "file_size": 13205, "cut_index": 921, "middle_length": 229 }
Mockery as m; use PHPUnit\Framework\TestCase; class ConsoleScheduledEventTest extends TestCase { /** * The default configuration timezone. * * @var string */ protected $defaultTimezone; protected function setUp(): void { $this->defaultTimezone = date_default_timezone_get()...
lse); $app->shouldReceive('environment')->andReturn('production'); $event = new Event(m::mock(EventMutex::class), 'php foo'); $this->assertSame('* * * * *', $event->getExpression()); $this->assertTrue($event->isDue($app));
parent::tearDown(); } public function testBasicCronCompilation() { $app = m::mock(Application::class.'[isDownForMaintenance,environment]'); $app->shouldReceive('isDownForMaintenance')->andReturn(fa
{ "filepath": "tests/Console/ConsoleScheduledEventTest.php", "language": "php", "file_size": 6057, "cut_index": 716, "middle_length": 229 }
pace Illuminate\Tests\Console; use Illuminate\Console\Signals; use Illuminate\Tests\Console\Fixtures\FakeSignalsRegistry; use PHPUnit\Framework\TestCase; class SignalsTest extends TestCase { protected $registry; protected $signals; protected $state; protected function setUp(): void { $t...
n () { $this->state = 'taylor'; }); $this->registry->handle('my-signal'); $this->assertSame('taylorotwell', $this->state); } public function testUnregister() { $this->signals->register('my-signal',
ent::tearDown(); } public function testRegister() { $this->signals->register('my-signal', function () { $this->state .= 'otwell'; }); $this->signals->register('my-signal', functio
{ "filepath": "tests/Console/SignalsTest.php", "language": "php", "file_size": 1320, "cut_index": 524, "middle_length": 229 }
; use Illuminate\Support\Testing\Fakes\QueueFake; use Laravel\SerializableClosure\SerializableClosure; use Mockery as m; use PHPUnit\Framework\TestCase; use Symfony\Component\Mailer\Transport\TransportInterface; class MailableQueuedTest extends TestCase { public function testQueuedMailableSent(): void { ...
shedOn(null, SendQueuedMailable::class); } public function testQueuedMailableWithAttachmentSent(): void { $queueFake = new QueueFake(new Application); $mailer = $this->getMockBuilder(Mailer::class) ->setConstructorA
age', 'to']) ->getMock(); $mailer->setQueue($queueFake); $mailable = new MailableQueueableStub; $queueFake->assertNothingPushed(); $mailer->send($mailable); $queueFake->assertPu
{ "filepath": "tests/Mail/MailableQueuedTest.php", "language": "php", "file_size": 10067, "cut_index": 921, "middle_length": 229 }
eeResponse('all-users', Request::create('users', 'GET')); $this->assertEquals(['seven'], $this->getRoute()->middleware()); } public function testNullNamespaceIsRespected() { $this->router->middleware(['one'])->namespace(null)->get('users', function () { return 'all-users'; ...
}); $this->seeResponse('all-users', Request::create('users', 'GET')); $this->assertSame(['one'], $this->getRoute()->middleware()); } public function testMiddlewareAsStringableObjectOnRouteInstance() { $one = new cla
le { public function __toString() { return 'one'; } }; $this->router->middleware($one)->get('users', function () { return 'all-users';
{ "filepath": "tests/Routing/RouteRegistrarTest.php", "language": "php", "file_size": 62577, "cut_index": 2151, "middle_length": 229 }
te\Tests\Routing; use Illuminate\Routing\RouteUri; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; class RouteUriTest extends TestCase { #[DataProvider('uriProvider')] public function testRouteUrisAreProperlyParsed($uri, $expectedParsedUri, $expectedBindingFields) { ...
'/foo/{bar}', [], ], [ '/foo/{bar}/baz/{qux}', '/foo/{bar}/baz/{qux}', [], ], [ '/foo/{bar}/baz/{qux?}',
@return array */ public static function uriProvider() { return [ [ '/foo', '/foo', [], ], [ '/foo/{bar}',
{ "filepath": "tests/Routing/RouteUriTest.php", "language": "php", "file_size": 1873, "cut_index": 537, "middle_length": 229 }
hedulingMutex; use Illuminate\Console\Scheduling\EventMutex; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Console\Scheduling\SchedulingMutex; use Illuminate\Container\Container; use Mockery as m; use PHPUnit\Framework\TestCase; class ConsoleEventSchedulerTest extends TestCase { /** * @var \Illum...
= new Schedule(m::mock(EventMutex::class))); } public function testMutexCanReceiveCustomStore() { Container::getInstance()->make(EventMutex::class)->shouldReceive('useStore')->once()->with('test'); Container::getInstance()->mak
container->instance(EventMutex::class, m::mock(CacheEventMutex::class)); $container->instance(SchedulingMutex::class, m::mock(CacheSchedulingMutex::class)); $container->instance(Schedule::class, $this->schedule
{ "filepath": "tests/Console/ConsoleEventSchedulerTest.php", "language": "php", "file_size": 7091, "cut_index": 716, "middle_length": 229 }
me; use Illuminate\Support\Carbon; use Illuminate\Support\DateFactory; use Illuminate\Support\Facades\Date; use Illuminate\Tests\Support\Fixtures\CustomDateClass; use InvalidArgumentException; use PHPUnit\Framework\TestCase; class DateFacadeTest extends TestCase { protected function tearDown(): void { ...
{ $start = Carbon::now()->getTimestamp(); $this->assertSame(Carbon::class, get_class(Date::now())); self::assertBetweenStartAndNow($start, Date::now()->getTimestamp()); DateFactory::use(function (Carbon $date) {
, static::logicalAnd( static::greaterThanOrEqual($start), static::lessThanOrEqual(Carbon::now()->getTimestamp()) ) ); } public function testUseClosure()
{ "filepath": "tests/Support/DateFacadeTest.php", "language": "php", "file_size": 3301, "cut_index": 614, "middle_length": 229 }
MethodCallException; use Error; use Illuminate\Support\Traits\ForwardsCalls; use PHPUnit\Framework\TestCase; class ForwardsCallsTest extends TestCase { public function testForwardsCalls() { $results = (new ForwardsCallsOne)->forwardedTwo('foo', 'bar'); $this->assertEquals(['foo', 'bar'], $resu...
\ForwardsCallsOne::missingMethod()'); (new ForwardsCallsOne)->missingMethod('foo', 'bar'); } public function testMissingAlphanumericForwardedCallThrowsCorrectError() { $this->expectException(BadMethodCallException::class);
} public function testMissingForwardedCallThrowsCorrectError() { $this->expectException(BadMethodCallException::class); $this->expectExceptionMessage('Call to undefined method Illuminate\Tests\Support
{ "filepath": "tests/Support/ForwardsCallsTest.php", "language": "php", "file_size": 2665, "cut_index": 563, "middle_length": 229 }
te\Tests\Support; use Illuminate\Support\Collection; use Illuminate\Support\HigherOrderCollectionProxy; use Illuminate\Support\HigherOrderTapProxy; use PHPUnit\Framework\TestCase; class HigherOrderProxyTest extends TestCase { public function test_get_proxies_property_access_to_items() { $items = new C...
st_call_proxies_method_call_to_items() { $items = new Collection([ new class { public function shout($s) { return strtoupper($s); } },
xied method returns a Collection instance; assert type and values $this->assertInstanceOf(Collection::class, $proxy->name); $this->assertEquals(['Alice', 'Bob'], $proxy->name->all()); } public function te
{ "filepath": "tests/Support/HigherOrderProxyTest.php", "language": "php", "file_size": 1833, "cut_index": 537, "middle_length": 229 }
oid { Lottery::determineResultNormally(); parent::tearDown(); } public function testItCanWin() { $wins = false; Lottery::odds(1, 1) ->winner(function () use (&$wins) { $wins = true; })->choose(); $this->assertTrue($wins)...
turnValues() { $win = Lottery::odds(1, 1)->winner(fn () => 'win')->choose(); $this->assertSame('win', $win); $lose = Lottery::odds(0, 1)->loser(fn () => 'lose')->choose(); $this->assertSame('lose', $lose); } pu
wins = true; })->loser(function () use (&$loses) { $loses = true; })->choose(); $this->assertFalse($wins); $this->assertTrue($loses); } public function testItCanRe
{ "filepath": "tests/Support/LotteryTest.php", "language": "php", "file_size": 5461, "cut_index": 716, "middle_length": 229 }
return once(fn () => mt_rand(1, PHP_INT_MAX)); } }; $first = $instance->rand(); $second = $instance->rand(); $this->assertSame($first, $second); } public function testCallableIsCalledOnce() { $instance = new class { pu...
stance = new MyClass(); $first = $instance->rand(); Once::flush(); $second = $instance->rand(); $this->assertNotSame($first, $second); Once::disable(); Once::flush(); $first = $instance->rand();
t(); $second = $instance->increment(); $this->assertSame(1, $first); $this->assertSame(1, $second); $this->assertSame(1, $instance->count); } public function testFlush() { $in
{ "filepath": "tests/Support/OnceTest.php", "language": "php", "file_size": 9510, "cut_index": 921, "middle_length": 229 }
Sleep::for(1)->milliseconds()->then(fn () => 123)); } public function testSleepRespectsWhile() { $_SERVER['__sleep.while'] = 0; $result = Sleep::for(10)->milliseconds()->while(function () { static $results = [true, true, false]; $_SERVER['__sleep.while']++; ...
hDelta(1.5, round($end - $start, 1, PHP_ROUND_HALF_DOWN), 0.03); } public function testItCanFakeSleeping() { Sleep::fake(); $start = microtime(true); Sleep::for(1.5)->seconds(); $end = microtime(true);
ER['__sleep.while']); } public function testItSleepsForSecondsWithMilliseconds() { $start = microtime(true); Sleep::for(1.5)->seconds(); $end = microtime(true); $this->assertEqualsWit
{ "filepath": "tests/Support/SleepTest.php", "language": "php", "file_size": 18237, "cut_index": 1331, "middle_length": 229 }
uminate\Support\Facades\Config; use Illuminate\Support\Facades\Storage; use League\Flysystem\UnableToReadFile; use Orchestra\Testbench\TestCase; class StorageFacadeTest extends TestCase { public function testFake_whenDiskNotConfigured_doesNotThrowExceptionOnError() { $result = Storage::fake('test')->ge...
t('filesystems.disks.test', ['throw' => true]); $result = Storage::fake('test', ['throw' => false])->get('nonExistentFile'); $this->assertNull($result); } public function testPersistentFake_whenDiskNotConfigured_doesNotThrowExcept
'throw' => true]); $this->expectException(UnableToReadFile::class); Storage::fake('test')->get('nonExistentFile'); } public function testFake_whenThrowOverwritten_usesOverwrite() { Config::se
{ "filepath": "tests/Support/StorageFacadeTest.php", "language": "php", "file_size": 2090, "cut_index": 563, "middle_length": 229 }
ls(['Desk', 'Chair', 'Lamp'], $array['office']['furniture']); $array = []; Arr::push($array, null, 'Chris', 'Nuno'); $this->assertEquals(['Chris', 'Nuno'], $array); Arr::push($array, null, 'Taylor'); $this->assertEquals(['Chris', 'Nuno', 'Taylor'], $array); $this->exp...
>assertEquals(['foo', 'bar', 'baz'], Arr::collapse($data)); // Case including numeric and string elements $array = [[1], [2], [3], ['foo', 'bar']]; $this->assertEquals([1, 2, 3, 'foo', 'bar'], Arr::collapse($array)); // Ca
lse]]; Arr::push($array, 'foo.bar', 'baz'); } public function testCollapse() { // Normal case: a two-dimensional array with different elements $data = [['foo', 'bar'], ['baz']]; $this-
{ "filepath": "tests/Support/SupportArrTest.php", "language": "php", "file_size": 71957, "cut_index": 3790, "middle_length": 229 }
upport; use Illuminate\Support\Benchmark; use PHPUnit\Framework\TestCase; class SupportBenchmarkTest extends TestCase { public function testMeasure(): void { $this->assertIsNumeric(Benchmark::measure(fn () => 1 + 1)); $this->assertIsArray(Benchmark::measure([ 'first' => fn () => 1...
roName = __FUNCTION__; $this->assertFalse(Benchmark::hasMacro($macroName)); // Register a macro to test Benchmark::macro($macroName, fn () => true); $this->assertTrue(Benchmark::hasMacro($macroName)); $this->asser
ic function testMacroable(): void { $mac
{ "filepath": "tests/Support/SupportBenchmarkTest.php", "language": "php", "file_size": 895, "cut_index": 547, "middle_length": 52 }
\Uuid; use Symfony\Component\Uid\Ulid; class SupportBinaryCodecTest extends TestCase { protected function tearDown(): void { $reflection = new \ReflectionClass(BinaryCodec::class); $property = $reflection->getProperty('customCodecs'); $property->setValue(null, []); parent::tear...
aryCodec::formats()); } public function testRegisterOverridesDefaultFormat() { BinaryCodec::register('uuid', fn ($v) => 'custom-encode', fn ($v) => 'custom-decode'); $this->assertSame('custom-encode', BinaryCodec::encode('test
ntains('ulid', $formats); } public function testRegisterAddsCustomFormat() { BinaryCodec::register('hex', fn ($v) => bin2hex($v ?? ''), fn ($v) => hex2bin($v ?? '')); $this->assertContains('hex', Bin
{ "filepath": "tests/Support/SupportBinaryCodecTest.php", "language": "php", "file_size": 5462, "cut_index": 716, "middle_length": 229 }
sitory; use Illuminate\Container\Container; use Illuminate\Support\Fluent; use Illuminate\Support\Traits\CapsuleManagerTrait; use Mockery as m; use PHPUnit\Framework\TestCase; class SupportCapsuleManagerTraitTest extends TestCase { use CapsuleManagerTrait; public function testSetupContainerForCapsule() { ...
ction testSetupContainerForCapsuleWhenConfigIsBound() { $this->container = null; $app = new Container; $app['config'] = m::mock(Repository::class); $this->setupContainer($app); $this->assertEquals($app, $this->g
luent::class, $app['config']); } public fun
{ "filepath": "tests/Support/SupportCapsuleManagerTraitTest.php", "language": "php", "file_size": 982, "cut_index": 582, "middle_length": 52 }
rbon; use PHPUnit\Framework\TestCase; class SupportCarbonTest extends TestCase { /** * @var \Illuminate\Support\Carbon */ protected $now; protected function setUp(): void { parent::setUp(); Carbon::setTestNow($this->now = Carbon::create(2017, 6, 27, 13, 14, 15, 'UTC')); ...
Carbon::class, $this->now); } public function testCarbonIsMacroableWhenNotCalledStatically() { Carbon::macro('diffInDecades', function (?Carbon $dt = null, $abs = true) { return (int) ($this->diffInYears($dt, $abs) / 10);
{ $this->assertInstanceOf(Carbon::class, $this->now); $this->assertInstanceOf(DateTimeInterface::class, $this->now); $this->assertInstanceOf(BaseCarbon::class, $this->now); $this->assertInstanceOf(
{ "filepath": "tests/Support/SupportCarbonTest.php", "language": "php", "file_size": 5537, "cut_index": 716, "middle_length": 229 }
rue], ]); $this->assertTrue($data->hasMany->verified); } #[DataProvider('collectionClassProvider')] public function testFirstOrFailReturnsFirstItemInCollection($collection) { $collection = new $collection([ ['name' => 'foo'], ['name' => 'bar'], ]...
$this->expectException(ItemNotFoundException::class); $collection = new $collection([ ['name' => 'foo'], ['name' => 'bar'], ]); $collection->where('name', 'INVALID')->firstOrFail(); } #[DataPro
$this->assertSame(['name' => 'foo'], $collection->firstOrFail('name', 'foo')); } #[DataProvider('collectionClassProvider')] public function testFirstOrFailThrowsExceptionIfNoItemsExist($collection) {
{ "filepath": "tests/Support/SupportCollectionTest.php", "language": "php", "file_size": 228466, "cut_index": 7068, "middle_length": 229 }
uminate\Filesystem\Filesystem; use Illuminate\Support\Composer; use Mockery as m; use PHPUnit\Framework\TestCase; use Symfony\Component\Process\Process; use function Illuminate\Support\php_binary; class SupportComposerTest extends TestCase { public function testDumpAutoloadRunsTheCorrectCommand() { $c...
$composer->dumpAutoloads(); } public function testDumpAutoloadRunsTheCorrectCommandWithExtraArguments() { $composer = $this->mockComposer(['composer', 'dump-autoload', '--no-scripts']); $composer->dumpAutoloads('--no-scrip
nt() { $expectedProcessArguments = [php_binary(), 'composer.phar', 'dump-autoload']; $customComposerPhar = true; $composer = $this->mockComposer($expectedProcessArguments, $customComposerPhar);
{ "filepath": "tests/Support/SupportComposerTest.php", "language": "php", "file_size": 2615, "cut_index": 563, "middle_length": 229 }
itionCallback() { // With static condition $logger = (new ConditionableLogger()) ->when(2, function ($logger, $condition) { $logger->log('when', $condition); }, function ($logger, $condition) { $logger->log('default', $condition); }...
ult', $condition); }); $this->assertSame(['init', 'when', true], $logger->values); } public function testWhenDefaultCallback() { // With static condition $logger = (new ConditionableLogger()) ->
) { return $logger->has('init'); }, function ($logger, $condition) { $logger->log('when', $condition); }, function ($logger, $condition) { $logger->log('defa
{ "filepath": "tests/Support/SupportConditionableTest.php", "language": "php", "file_size": 5942, "cut_index": 716, "middle_length": 229 }
use Generator; use Illuminate\Console\Command; use Illuminate\Console\Concerns\InteractsWithIO; use Illuminate\Console\OutputStyle; use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Helper\ProgressBar; use Symfony\Component\Console\Input\Arg...
mand->setOutput($output); $output->shouldReceive('createProgressBar') ->once() ->with(count($iterable)) ->andReturnUsing(function ($steps) use ($bufferedOutput) { // we can't mock ProgressBar bec
erable($iterable) { $command = new CommandInteractsWithIO; $bufferedOutput = new BufferedOutput(); $output = m::mock(OutputStyle::class, [new ArgvInput(), $bufferedOutput])->makePartial(); $com
{ "filepath": "tests/Console/Concerns/InteractsWithIOTest.php", "language": "php", "file_size": 2834, "cut_index": 563, "middle_length": 229 }
\Console\Scheduling\CacheEventMutex; use Illuminate\Console\Scheduling\CacheSchedulingMutex; use Illuminate\Console\Scheduling\Event; use Illuminate\Contracts\Cache\Factory; use Illuminate\Contracts\Cache\Repository; use Illuminate\Support\Carbon; use Mockery as m; use PHPUnit\Framework\TestCase; class CacheScheduling...
minate\Contracts\Cache\Repository */ protected $cacheRepository; protected function setUp(): void { parent::setUp(); $this->cacheFactory = m::mock(Factory::class); $this->cacheRepository = m::mock(Repository::clas
t */ protected $event; /** * @var \Illuminate\Support\Carbon */ protected $time; /** * @var \Illuminate\Contracts\Cache\Factory */ protected $cacheFactory; /** * @var \Illu
{ "filepath": "tests/Console/Scheduling/CacheSchedulingMutexTest.php", "language": "php", "file_size": 4615, "cut_index": 614, "middle_length": 229 }
t extends TestCase { #[RequiresOperatingSystem('Linux|Darwin')] public function testBuildCommandUsingUnix() { $event = new Event(m::mock(EventMutex::class), 'php -i'); $this->assertSame("php -i > '/dev/null' 2>&1", $event->buildCommand()); } #[RequiresOperatingSystem('Windows')] ...
$scheduleId = '"framework'.DIRECTORY_SEPARATOR.'schedule-eeb46c93d45e928d62aaf684d727e213b7094822"'; $this->assertSame("(php -i > '/dev/null' 2>&1 ; '".php_binary()."' 'artisan' schedule:finish {$scheduleId} \"$?\") > '/dev/null' 2>&1 &", $ev
)); } #[RequiresOperatingSystem('Linux|Darwin')] public function testBuildCommandInBackgroundUsingUnix() { $event = new Event(m::mock(EventMutex::class), 'php -i'); $event->runInBackground();
{ "filepath": "tests/Console/Scheduling/EventTest.php", "language": "php", "file_size": 9635, "cut_index": 921, "middle_length": 229 }
nsole\View\Components; use Illuminate\Database\Migrations\MigrationResult; use Mockery as m; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Console\Question\ChoiceQuestion; class ComponentsTest extends TestCase { public function testAlert() { ...
)->render([ 'ls -la', 'php artisan inspire', ]); $output = $output->fetch(); $this->assertStringContainsString('⇂ ls -la', $output); $this->assertStringContainsString('⇂ php artisan inspire', $outpu
'THE APPLICATION IS IN THE [PRODUCTION] ENVIRONMENT.', $output->fetch() ); } public function testBulletList() { $output = new BufferedOutput(); (new Components\BulletList($output)
{ "filepath": "tests/Console/View/ComponentsTest.php", "language": "php", "file_size": 4833, "cut_index": 614, "middle_length": 229 }
\Container\Container; use Illuminate\Hashing\Argon2IdHasher; use Illuminate\Hashing\ArgonHasher; use Illuminate\Hashing\BcryptHasher; use Illuminate\Hashing\HashManager; use PHPUnit\Framework\Attributes\Depends; use PHPUnit\Framework\TestCase; use RuntimeException; class HasherTest extends TestCase { public $hashM...
'')); $hasher = new ArgonHasher(); $this->assertFalse($hasher->check('password', '')); $hasher = new Argon2IdHasher(); $this->assertFalse($hasher->check('password', '')); } public function testNullHashedValueReturns
onfig()); $this->hashManager = new HashManager($container); } public function testEmptyHashedValueReturnsFalse() { $hasher = new BcryptHasher(); $this->assertFalse($hasher->check('password',
{ "filepath": "tests/Hashing/HasherTest.php", "language": "php", "file_size": 5089, "cut_index": 614, "middle_length": 229 }
ce; use RuntimeException; use Throwable; final class JsonFormatterTest extends TestCase { #[\Override] protected function setUp(): void { parent::setUp(); config(['logging.default' => 'testing']); config(['logging.channels' => [ 'testing' => [ 'driver' =...
'exception']; $this->assertSame('bar', $exceptionData['foo']); $this->assertSame(ContextProvidingException::class, $exceptionData['class']); } public function testExceptionContextIsNotDuplicatedWhenGoingThroughReport() {
EnrichedOnDirectLogging() { Log::error('fail', ['exception' => new ContextProvidingException('Something went wrong')]); $formatted = $this->getFormattedJson(); $exceptionData = $formatted['context'][
{ "filepath": "tests/Log/JsonFormatterTest.php", "language": "php", "file_size": 12065, "cut_index": 921, "middle_length": 229 }
gerCachesLoggerInstances() { $manager = new LogManager($this->app); $logger1 = $manager->channel('single')->getLogger(); $logger2 = $manager->channel('single')->getLogger(); $this->assertSame($logger1, $logger2); } public function testLogManagerGetDefaultDriver() { ...
kChannel() { $config = $this->app['config']; $config->set('logging.channels.stack', [ 'driver' => 'stack', 'channels' => ['stderr', 'stdout'], ]); $config->set('logging.channels.stderr', [
//we don't specify any channel name $manager->channel(); $this->assertCount(1, $manager->getChannels()); $this->assertSame('single', $manager->getDefaultDriver()); } public function testStac
{ "filepath": "tests/Log/LogManagerTest.php", "language": "php", "file_size": 28289, "cut_index": 1331, "middle_length": 229 }
namespace Illuminate\Tests\Support; use ArrayIterator; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Contracts\Support\Jsonable; use IteratorAggregate; use JsonSerializable; use Traversable; class TestArrayableObject implements Arrayable { public function toArray() { return ['foo' => 'ba...
{ return 'foo'; } } class TestTraversableAndJsonSerializableObject implements IteratorAggregate, JsonSerializable { public $items; public function __construct($items = []) { $this->items = $items; } public funct
onSerializable { public function jsonSerialize(): array { return ['foo' => 'bar']; } } class TestJsonSerializeWithScalarValueObject implements JsonSerializable { public function jsonSerialize(): string
{ "filepath": "tests/Support/Common.php", "language": "php", "file_size": 1213, "cut_index": 518, "middle_length": 229 }
tBasicParameterParsing() { $results = Parser::parse('command:name'); $this->assertSame('command:name', $results[0]); $results = Parser::parse('command:name {argument} {--option}'); $this->assertSame('command:name', $results[0]); $this->assertSame('argument', $results[1][0]...
ts[1][0]->isRequired()); $this->assertSame('option', $results[2][0]->getName()); $this->assertTrue($results[2][0]->acceptValue()); $results = Parser::parse('command:name {argument?*} {--option=*}'); $this->assertSame('comm
nt*} {--option=}'); $this->assertSame('command:name', $results[0]); $this->assertSame('argument', $results[1][0]->getName()); $this->assertTrue($results[1][0]->isArray()); $this->assertTrue($resul
{ "filepath": "tests/Console/ConsoleParserTest.php", "language": "php", "file_size": 7233, "cut_index": 716, "middle_length": 229 }
e\Eloquent\Model; use Illuminate\Routing\Exceptions\BackedEnumCaseNotFoundException; use Illuminate\Routing\ImplicitRouteBinding; use Illuminate\Routing\Route; use PHPUnit\Framework\TestCase; include_once 'Enums.php'; class ImplicitRouteBindingTest extends TestCase { public function test_it_can_resolve_the_implic...
oute($container, $route); $this->assertSame('fruits', $route->parameter('category')->value); } public function test_it_can_resolve_the_implicit_backed_enum_route_bindings_for_the_given_route_with_optional_parameter() { $action
e = new Route('GET', '/test', $action); $route->parameters = ['category' => 'fruits']; $route->prepareForSerialization(); $container = Container::getInstance(); ImplicitRouteBinding::resolveForR
{ "filepath": "tests/Routing/ImplicitRouteBindingTest.php", "language": "php", "file_size": 4115, "cut_index": 614, "middle_length": 229 }
* @var \Illuminate\Routing\RouteCollection */ protected $routeCollection; protected function setUp(): void { parent::setUp(); $this->routeCollection = new RouteCollection; } public function testRouteCollectionCanAddRoute() { $this->routeCollection->add(new Rou...
$this->assertInstanceOf(Route::class, $outputRoute); $this->assertEquals($inputRoute, $outputRoute); } public function testRouteCollectionCanRetrieveByName() { $this->routeCollection->add($routeIndex = new Route('GET', '
testRouteCollectionAddReturnsTheRoute() { $outputRoute = $this->routeCollection->add($inputRoute = new Route('GET', 'foo', [ 'uses' => 'FooController@index', 'as' => 'foo_index', ]));
{ "filepath": "tests/Routing/RouteCollectionTest.php", "language": "php", "file_size": 16032, "cut_index": 921, "middle_length": 229 }
n\Store; use Mockery as m; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\HeaderBag; class RoutingRedirectorTest extends TestCase { protected $headers; protected $request; protected $url; protected $session; protected $redirect; protected function setUp(): void { ...
$this->request->shouldReceive('expectsJson')->andReturn(false)->byDefault(); $this->request->headers = $this->headers; $this->url = m::mock(UrlGenerator::class); $this->url->shouldReceive('getRequest')->andReturn($this->request)
s->request->shouldReceive('method')->andReturn('GET')->byDefault(); $this->request->shouldReceive('route')->andReturn(true)->byDefault(); $this->request->shouldReceive('ajax')->andReturn(false)->byDefault();
{ "filepath": "tests/Routing/RoutingRedirectorTest.php", "language": "php", "file_size": 7458, "cut_index": 716, "middle_length": 229 }
, $url->asset('foo/bar')); $this->assertSame('/foo/bar', $url->asset('foo/bar', true)); } public function testBasicGenerationWithHostFormatting() { $url = new UrlGenerator( $routes = new RouteCollection, Request::create('http://www.foo.com/') ); $rou...
uestBaseUrlWithSubfolder() { $request = Request::create('http://www.foo.com/subfolder/foo/bar/subfolder/'); $request->server->set('SCRIPT_FILENAME', '/var/www/laravel-project/public/subfolder/index.php'); $request->server->set(
$host); }); $this->assertSame('http://www.foo.org/foo/bar', $url->to('foo/bar')); $this->assertSame('/named-route', $url->route('plain', [], false)); } public function testBasicGenerationWithReq
{ "filepath": "tests/Routing/RoutingUrlGeneratorTest.php", "language": "php", "file_size": 91871, "cut_index": 3790, "middle_length": 229 }
s\Queue\Queue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; use Mockery as m; use PHPUnit\Framework\TestCase; use RuntimeException; class BusDispatcherTest extends TestCase { public function testCommandsThatShouldQueueIsQueued() { $container = new Container; ...
urn $mock; }); $dispatcher->dispatch(m::mock(ShouldQueue::class)); Container::setInstance(null); } public function testCommandsThatShouldQueueIsQueuedUsingCustomHandler() { $container = new Container;
eturn(null); Container::setInstance($container); $dispatcher = new Dispatcher($container, function () { $mock = m::mock(Queue::class); $mock->shouldReceive('push')->once(); ret
{ "filepath": "tests/Bus/BusDispatcherTest.php", "language": "php", "file_size": 6131, "cut_index": 716, "middle_length": 229 }
se Illuminate\Contracts\Cache\Repository; use Mockery as m; use Mockery\MockInterface; use PHPUnit\Framework\TestCase; class CacheCommandMutexTest extends TestCase { /** * @var \Illuminate\Console\CacheCommandMutex */ protected $mutex; /** * @var \Illuminate\Console\Command */ prot...
>cacheFactory); $this->command = new class extends Command { protected $name = 'command-name'; }; } public function testCanCreateMutex() { $this->mockUsingCacheStore(); $this->cacheRepository
$cacheRepository; protected function setUp(): void { $this->cacheFactory = m::mock(Factory::class); $this->cacheRepository = m::mock(Repository::class); $this->mutex = new CacheCommandMutex($this-
{ "filepath": "tests/Console/CacheCommandMutexTest.php", "language": "php", "file_size": 5920, "cut_index": 716, "middle_length": 229 }
uminate\Console\Command; use Illuminate\Console\Signals; use Illuminate\Tests\Console\Fixtures\FakeSignalsRegistry; use PHPUnit\Framework\TestCase; class CommandTrapTest extends TestCase { protected $registry; protected $signals; protected $state; protected function setUp(): void { Signa...
', $this->state); } public function testTrapWhenNotAvailable() { Signals::resolveAvailabilityUsing(fn () => false); $command = $this->createCommand(); $command->trap('my-signal', function () { $this->state
$command = $this->createCommand(); $command->trap('my-signal', function () { $this->state = 'taylorotwell'; }); $this->registry->handle('my-signal'); $this->assertSame('taylorotwell
{ "filepath": "tests/Console/CommandTrapTest.php", "language": "php", "file_size": 2972, "cut_index": 563, "middle_length": 229 }
\Console\Scheduling\CacheEventMutex; use Illuminate\Console\Scheduling\Event; use Illuminate\Contracts\Cache\Factory; use Illuminate\Contracts\Cache\Repository; use Mockery as m; use PHPUnit\Framework\TestCase; class CacheEventMutexTest extends TestCase { /** * @var \Illuminate\Console\Scheduling\CacheEventMu...
m::mock(Factory::class); $this->cacheRepository = m::mock(Repository::class); $this->cacheFactory->shouldReceive('store')->andReturn($this->cacheRepository); $this->cacheMutex = new CacheEventMutex($this->cacheFactory); $thi
protected $cacheFactory; /** * @var \Illuminate\Contracts\Cache\Repository */ protected $cacheRepository; protected function setUp(): void { parent::setUp(); $this->cacheFactory =
{ "filepath": "tests/Console/Scheduling/CacheEventMutexTest.php", "language": "php", "file_size": 4376, "cut_index": 614, "middle_length": 229 }
e\Scheduling\EventMutex; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Console\Scheduling\SchedulingMutex; use Illuminate\Container\Container; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Tests\Console\Fixtures\JobToTestWithSchedule; use Mockery as m; use PHPUnit\Framework\Attributes\CoversCl...
>container->instance(EventMutex::class, $eventMutex); $schedulingMutex = m::mock(SchedulingMutex::class); $this->container->instance(SchedulingMutex::class, $schedulingMutex); } #[DataProvider('jobHonoursDisplayNameIfMethodExistsPr
r; protected function setUp(): void { parent::setUp(); $this->container = new Container; Container::setInstance($this->container); $eventMutex = m::mock(EventMutex::class); $this-
{ "filepath": "tests/Console/Scheduling/ScheduleTest.php", "language": "php", "file_size": 4362, "cut_index": 614, "middle_length": 229 }
ted = false; parent::tearDown(); } public function test_it_can_set_values() { $values = [ 'string' => 'string', 'bool' => false, 'int' => 5, 'float' => 5.5, 'null' => null, 'array' => [1, 2, 3], 'hash' => [...
an_add_values_when_not_already_present() { Context::addIf('foo', 1); $this->assertSame(1, Context::get('foo')); Context::addIf('foo', 2); $this->assertSame(1, Context::get('foo')); } public function test_it_can
s as $type => $value) { Context::add($type, $value); } foreach ($values as $type => $value) { $this->assertSame($value, Context::get($type)); } } public function test_it_c
{ "filepath": "tests/Log/ContextTest.php", "language": "php", "file_size": 23552, "cut_index": 1331, "middle_length": 229 }
)->parseConfiguration($config)); } public function testDriversAliases() { $this->assertEquals([ 'mssql' => 'sqlsrv', 'mysql2' => 'mysql', 'postgres' => 'pgsql', 'postgresql' => 'pgsql', 'sqlite3' => 'sqlite', 'redis' => 'tcp', ...
ss' => 'tls', 'some-particular-alias' => 'mysql', ], ConfigurationUrlParser::getDriverAliases()); $this->assertEquals([ 'driver' => 'mysql', ], (new ConfigurationUrlParser)->parseConfiguration('some-particul
Equals([ 'mssql' => 'sqlsrv', 'mysql2' => 'mysql', 'postgres' => 'pgsql', 'postgresql' => 'pgsql', 'sqlite3' => 'sqlite', 'redis' => 'tcp', 'redi
{ "filepath": "tests/Support/ConfigurationUrlParserTest.php", "language": "php", "file_size": 16196, "cut_index": 921, "middle_length": 229 }
uminate\Console\OutputStyle; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; class OutputStyleTest extends TestCase { public function testDetectsNewLine() { $bufferedOutput = new BufferedOutput(); $style = new...
(new ArrayInput([]), $underlyingStyle); $underlyingStyle->newLine(); $this->assertTrue($style->newLineWritten()); } public function testDetectsNewLineOnWrite() { $bufferedOutput = new BufferedOutput(); $style
public function testDetectsNewLineOnUnderlyingOutput() { $bufferedOutput = new BufferedOutput(); $underlyingStyle = new OutputStyle(new ArrayInput([]), $bufferedOutput); $style = new OutputStyle
{ "filepath": "tests/Console/OutputStyleTest.php", "language": "php", "file_size": 2104, "cut_index": 563, "middle_length": 229 }
Illuminate\Database\Eloquent\Model; use Illuminate\Routing\RouteSignatureParameters; use Laravel\SerializableClosure\SerializableClosure; use PHPUnit\Framework\TestCase; use ReflectionParameter; class RouteSignatureParametersTest extends TestCase { public function test_it_can_extract_the_route_action_signature_pa...
eSignatureParameters::fromAction($action); $this->assertContainsOnlyInstancesOf(ReflectionParameter::class, $parameters); $this->assertSame('user', $parameters[0]->getName()); } } class SignatureParametersUser extends Model { // }
e($callable) )]; $parameters = Rout
{ "filepath": "tests/Routing/RouteSignatureParametersTest.php", "language": "php", "file_size": 868, "cut_index": 559, "middle_length": 52 }
Builder; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Foundation\Bus\PendingChain; use Illuminate\Queue\CallQueuedClosure; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Facade; use Illuminate\Support\Facades\Queue; use Mockery as m; use PHPUnit\Framework...
$container = new Container; Facade::setFacadeApplication($container); $queue = m::mock(Factory::class); $container->instance(Factory::class, $queue); $container->alias(Factory::class, 'queue');
w DB; $db->addConnection([ 'driver' => 'sqlite', 'database' => ':memory:', ]); $db->bootEloquent(); $db->setAsGlobal(); if (! Facade::getFacadeApplication()) {
{ "filepath": "tests/Bus/BusBatchTest.php", "language": "php", "file_size": 26979, "cut_index": 1331, "middle_length": 229 }
uminate\Console\Command; use Illuminate\Console\CommandMutex; use Illuminate\Contracts\Console\Isolatable; use Illuminate\Foundation\Application; use Mockery as m; use Orchestra\Testbench\Concerns\InteractsWithMockery; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component...
$ran = 0; public function __invoke() { $this->ran++; } }; $this->commandMutex = m::mock(CommandMutex::class); $app = new Application; $app->instance(CommandMutex::class,
tex */ protected $commandMutex; /** {@inheritdoc} */ #[\Override] protected function setUp(): void { $this->command = new class extends Command implements Isolatable { public
{ "filepath": "tests/Console/CommandMutexTest.php", "language": "php", "file_size": 2741, "cut_index": 563, "middle_length": 229 }
ramework\TestCase; class FrequencyTest extends TestCase { /** @var \Illuminate\Console\Scheduling\Event */ protected $event; protected function setUp(): void { $this->event = new Event( m::mock(EventMutex::class), 'php foo' ); } public function testEver...
this->assertSame('*/4 * * * *', $this->event->everyFourMinutes()->getExpression()); $this->assertSame('*/5 * * * *', $this->event->everyFiveMinutes()->getExpression()); $this->assertSame('*/10 * * * *', $this->event->everyTenMinutes()->getE
unction testEveryXMinutes() { $this->assertSame('*/2 * * * *', $this->event->everyTwoMinutes()->getExpression()); $this->assertSame('*/3 * * * *', $this->event->everyThreeMinutes()->getExpression()); $
{ "filepath": "tests/Console/Scheduling/FrequencyTest.php", "language": "php", "file_size": 8368, "cut_index": 716, "middle_length": 229 }
te\Tests\Conditionable; use Illuminate\Database\Capsule\Manager as DB; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\HigherOrderWhenProxy; use PHPUnit\Framework\TestCase; class ConditionableTest extends TestCase { protected function setUp(): void { ...
onableModel::query()->when(false)); $this->assertInstanceOf(HigherOrderWhenProxy::class, TestConditionableModel::query()->when()); $this->assertInstanceOf(Builder::class, TestConditionableModel::query()->when(false, null)); $this->a
} public function testWhen(): void { $this->assertInstanceOf(HigherOrderWhenProxy::class, TestConditionableModel::query()->when(true)); $this->assertInstanceOf(HigherOrderWhenProxy::class, TestConditi
{ "filepath": "tests/Conditionable/ConditionableTest.php", "language": "php", "file_size": 1781, "cut_index": 537, "middle_length": 229 }
work\TestCase; class RoutingSortedMiddlewareTest extends TestCase { public function testMiddlewareCanBeSortedByPriority() { $priority = [ 'First', 'Second', 'Third', ]; $middleware = [ 'Something', 'Something', 'So...
; $this->assertEquals($expected, (new SortedMiddleware($priority, $middleware))->all()); $this->assertSame([], (new SortedMiddleware(['First'], []))->all()); $this->assertEquals(['First'], (new SortedMiddleware(['First'], ['First'
'Second', ]; $expected = [ 'Something', 'First:api', 'First:foo,bar', 'Second', 'Otherthing', 'Third:foo', 'Third', ]
{ "filepath": "tests/Routing/RoutingSortedMiddlewareTest.php", "language": "php", "file_size": 3449, "cut_index": 614, "middle_length": 229 }
{ public function test_pending_batch_may_be_configured_and_dispatched() { $container = new Container; $eventDispatcher = m::mock(Dispatcher::class); $eventDispatcher->shouldReceive('dispatch')->once(); $container->instance(Dispatcher::class, $eventDispatcher); $job = ...
ueue('test-queue')->withOption('extra-option', 123); $this->assertSame('test-connection', $pendingBatch->connection()); $this->assertSame('test-queue', $pendingBatch->queue()); $this->assertCount(1, $pendingBatch->beforeCallbacks()
() { // })->progress(function () { // })->then(function () { // })->catch(function () { // })->allowFailures()->onConnection('test-connection')->onQ
{ "filepath": "tests/Bus/BusPendingBatchTest.php", "language": "php", "file_size": 13109, "cut_index": 921, "middle_length": 229 }
uminate\Container\Container; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Routing\Route; use Illuminate\Routing\RouteBinding; use PHPUnit\Framework\TestCase; class RouteBindingTest extends TestCase { pu...
nnot_resolve_the_explicit_soft_deleted_model_for_the_given_route() { $container = Container::getInstance(); $route = new Route('GET', '/users/{user}', function () { }); $callback = RouteBinding::forModel($container, Ex
{ }); $callback = RouteBinding::forModel($container, ExplicitRouteBindingUser::class); $this->assertInstanceOf(ExplicitRouteBindingUser::class, $callback(1, $route)); } public function test_it_ca
{ "filepath": "tests/Routing/RouteBindingTest.php", "language": "php", "file_size": 2110, "cut_index": 563, "middle_length": 229 }
_basename('/Foo/Bar/Baz/')); $this->assertSame('Baz', class_basename('/Foo///Bar/Baz//')); // accepts objects $this->assertSame('stdClass', class_basename(new stdClass())); // edge-cases $this->assertSame('1', class_basename(1)); $this->assertSame('1', class_basename('1')...
n(true, 'Hello')); $this->assertNull(when(false, 'Hello')); $this->assertSame('There', when(1 === 1, 'There')); // strict types $this->assertSame('There', when(1 == '1', 'There')); // loose types $this->assertNull(when(1 ==
class_basename('/')); $this->assertSame('', class_basename('///')); $this->assertSame('..', class_basename('\Foo\Bar\Baz\\..\\')); } public function testWhen() { $this->assertSame('Hello', whe
{ "filepath": "tests/Support/SupportHelpersTest.php", "language": "php", "file_size": 77031, "cut_index": 3790, "middle_length": 229 }
eption; use Illuminate\Support\Timebox; use Mockery as m; use PHPUnit\Framework\TestCase; class SupportTimeboxTest extends TestCase { public function testMakeExecutesCallback() { $callback = function () { $this->assertTrue(true); }; (new Timebox)->call($callback, 0); } ...
box::class)->shouldAllowMockingProtectedMethods()->makePartial(); $mock->call(function ($timebox) { $timebox->returnEarly(); }, 10000); $mock->shouldNotHaveReceived('usleep'); } public function testMakeShouldSl
nce(); $mock->call(function () { }, 10000); $mock->shouldHaveReceived('usleep')->once(); } public function testMakeShouldNotSleepWhenEarlyReturnHasBeenFlagged() { $mock = m::spy(Time
{ "filepath": "tests/Support/SupportTimeboxTest.php", "language": "php", "file_size": 2546, "cut_index": 563, "middle_length": 229 }
$this->assertSame('https://laravel.com/route', Uri::route('')->value()); $this->assertSame('https://laravel.com/signed-route', Uri::signedRoute('')->value()); $this->assertSame('https://laravel.com/signed-route', Uri::temporarySignedRoute('', '')->value()); $this->assertSame('https://laravel.c...
$this->assertSame('docs/installation', $uri->path()); $this->assertSame([], $uri->query()->toArray()); $this->assertSame('', (string) $uri->query()); $this->assertSame('', $uri->query()->decode()); $this->assertNull($ur
this->assertSame('https', $uri->scheme()); $this->assertNull($uri->user()); $this->assertNull($uri->password()); $this->assertSame('laravel.com', $uri->host()); $this->assertNull($uri->port());
{ "filepath": "tests/Support/SupportUriTest.php", "language": "php", "file_size": 11980, "cut_index": 921, "middle_length": 229 }
ViewErrorBag; use PHPUnit\Framework\TestCase; class SupportViewErrorBagTest extends TestCase { public function testHasBagTrue() { $viewErrorBag = new ViewErrorBag; $viewErrorBag->put('default', new MessageBag(['msg1', 'msg2'])); $this->assertTrue($viewErrorBag->hasBag()); } pub...
tion testGetBagWithNew() { $viewErrorBag = new ViewErrorBag; $this->assertInstanceOf(MessageBag::class, $viewErrorBag->getBag('default')); } public function testGetBags() { $messageBag1 = new MessageBag; $me
ag = new MessageBag; $viewErrorBag = new ViewErrorBag; $viewErrorBag = $viewErrorBag->put('default', $messageBag); $this->assertEquals($messageBag, $viewErrorBag->getBag('default')); } public func
{ "filepath": "tests/Support/SupportViewErrorBagTest.php", "language": "php", "file_size": 3906, "cut_index": 614, "middle_length": 229 }
is->assertEquals(['name' => 'Taylor', 'votes' => 100], $input->all()); } public function test_can_merge_items() { $input = new ValidatedInput(['name' => 'Taylor']); $input = $input->merge(['votes' => 100]); $this->assertSame('Taylor', $input->name); $this->assertSame('Tayl...
; $this->assertTrue($inputA->missing('votes')); $this->assertTrue($inputA->missing(['votes'])); $this->assertFalse($inputA->missing('name')); $inputB = new ValidatedInput(['name' => 'Taylor', 'votes' => 100]); $thi
sertEquals(['name' => 'Taylor', 'votes' => 100], $input->all()); } public function test_input_existence() { $inputA = new ValidatedInput(['name' => 'Taylor']); $this->assertTrue($inputA->has('name'))
{ "filepath": "tests/Support/ValidatedInputTest.php", "language": "php", "file_size": 22019, "cut_index": 1331, "middle_length": 229 }
use Illuminate\Support\Collection; use Illuminate\Support\LazyCollection; trait CountsEnumerations { protected function makeGeneratorFunctionWithRecorder($numbers = 10) { $recorder = new Collection(); $generatorFunction = function () use ($numbers, $recorder) { for ($i = 1; $i <=...
$this->assertEnumeratesCollection($collection, 0, $executor); } protected function assertEnumerates($count, callable $executor) { $this->assertEnumeratesCollection( LazyCollection::times(100), $count,
tDoesNotEnumerate(callable $executor) { $this->assertEnumerates(0, $executor); } protected function assertDoesNotEnumerateCollection( LazyCollection $collection, callable $executor ) {
{ "filepath": "tests/Support/Concerns/CountsEnumerations.php", "language": "php", "file_size": 2507, "cut_index": 563, "middle_length": 229 }
e; class FilesystemAdapterTest extends TestCase { private $tempDir; private $filesystem; private $adapter; protected function setUp(): void { $this->tempDir = __DIR__.'/tmp'; $this->filesystem = new Filesystem( $this->adapter = new LocalFilesystemAdapter($this->tempDir)...
esystem->write('file.txt', 'Hello World'); $files = new FilesystemAdapter($this->filesystem, $this->adapter); $response = $files->response('file.txt'); ob_start(); $response->sendContent(); $content = ob_get_clean()
); $filesystem->deleteDirectory(basename($this->tempDir)); unset($this->tempDir, $this->filesystem, $this->adapter); parent::tearDown(); } public function testResponse() { $this->fil
{ "filepath": "tests/Filesystem/FilesystemAdapterTest.php", "language": "php", "file_size": 30056, "cut_index": 1331, "middle_length": 229 }
class FilesystemManagerTest extends TestCase { public function testExceptionThrownOnUnsupportedDriver() { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Disk [local] does not have a configured driver.'); $filesystem = new FilesystemManager(tap(ne...
stem->build([ 'driver' => 'local', 'root' => 'my-custom-path', 'url' => 'my-custom-url', 'visibility' => 'public', ])); rmdir(__DIR__.'/../../my-custom-path'); } public function test
mandDisk() { $filesystem = new FilesystemManager(new Application); $this->assertInstanceOf(Filesystem::class, $filesystem->build('my-custom-path')); $this->assertInstanceOf(Filesystem::class, $filesy
{ "filepath": "tests/Filesystem/FilesystemManagerTest.php", "language": "php", "file_size": 10278, "cut_index": 921, "middle_length": 229 }
) { $files = new Filesystem; $files->deleteDirectory(self::$tempDir); self::$tempDir = null; } protected function tearDown(): void { $files = new Filesystem; $files->deleteDirectory(self::$tempDir, $preserve = true); parent::tearDown(); } public...
$tempDir.'/file.txt', 'Hello World'); } public function testLines() { $path = self::$tempDir.'/file.txt'; $contents = ' '.PHP_EOL.' spaces around '.PHP_EOL.PHP_EOL.'Line 2'.PHP_EOL.'1 trailing empty line ->'.PHP_EOL.PHP_EOL;
get(self::$tempDir.'/file.txt')); } public function testPutStoresFiles() { $files = new Filesystem; $files->put(self::$tempDir.'/file.txt', 'Hello World'); $this->assertStringEqualsFile(self::
{ "filepath": "tests/Filesystem/FilesystemTest.php", "language": "php", "file_size": 27940, "cut_index": 1331, "middle_length": 229 }
PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RequiresOperatingSystem; use PHPUnit\Framework\TestCase; use function Illuminate\Filesystem\join_paths; class JoinPathsHelperTest extends TestCase { #[RequiresOperatingSystem('Linux|Darwin')] #[DataProvider('unixDataProvider')] pu...
yield ['only/\\os_separator\\/\\get_ltrimmed.php', join_paths('only', '\\os_separator\\', '\\get_ltrimmed.php')]; yield ['/base_path//does_not/get_trimmed.php', join_paths('/base_path/', '/does_not', '/get_trimmed.php')]; yield ['Em
yield ['very/Basic/Functionality.php', join_paths('very', 'Basic', 'Functionality.php')]; yield ['segments/get/ltrimed/by_directory/separator.php', join_paths('segments', '/get/ltrimed', '/by_directory/separator.php')];
{ "filepath": "tests/Filesystem/JoinPathsHelperTest.php", "language": "php", "file_size": 3010, "cut_index": 563, "middle_length": 229 }