Php artisan test filter

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

volodec/laravel-check-your-skill-test

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Тест на знание основ laravel

Для начала необходимо развернуть проект на котором будут выполняться тесты.

  • composer install
  • php artisan key:generate Либо используйте docker-compose:
  • docker-compose up -d —build
  • docker-compose exec laravel.test php artisan key:generate
  • .env с реквизитами mysql базы данных
  • КРАЙНЕ ВАЖНО ЧТОБЫ БАЗА ДАННЫХ НАЗЫВАЛАСЬ laravel_skill_test
  • php artisan test —filter MigrationsTest
  • php artisan test —filter RouteTest
  • php artisan test —filter BladeTest
  • php artisan test —filter ModelTest
  • php artisan test —filter ValidationTest
  • php artisan test —filter AuthTest
  • php artisan test

Искать задачи можно по фильтру TODO в IDE (игнорируя директорию /storage), либо по списку заданий

Подтверждение выполнения теста

PR в ветку master (автоматически запустит тест проверки)

Все задания находятся здесь database/migrations/tasks

Создать в базе данных таблицу categories с 2 полями id и title (не забыть про timestamps)

Для title указать что значение по умолчанию NULL

Задание 3: Значение по умолчанию

Для active указать что значение по умолчанию TRUE

Добавить функционал soft delete

Добавить поля с timestamps (created_at, updated_at) через 1 метод

Читайте также:  All tag list in html

Задание 6: Новое поле с указанием порядка

Добавить поле description типа text (DEFAULT NULL) ПОСЛЕ поля title

Задание 7: Проверка наличия поля

Сделать провеку на наличие поля active и в случаи успеха добавить поле main (boolean default false)

Задание 8: Переименовать поле

Переименовать поле title в name

Задание 9: Переименовать таблицу

Переименовать таблицу posts в articles

Добавить таблицу для связи articles и categories (belongsToMany) c foreign ключами

Все задания находятся здесь routes/web.php и routes/api.php

По GET урлу /hello отобразить view — /resources/views/hello.blade (без контроллера)

По GET урлу / обратиться к IndexController, метод index

Задание 3: View с наименованием роута

По GET урлу /page/contact отобразить view — /resources/views/pages/contact.blade с наименованием роута — contact

По GET урлу /users/[id] обратиться к UserController -> метод show без Route Model Binding. Только параметр id

По GET урлу /users/bind/[user] обратиться к UserController -> метод showBind но в данном случае используем Route Model Binding. Параметр user

Выполнить редирект с урла /bad на урл /good

Задание 7: Resource controller

Добавить роут на ресурс контроллер — UserCrudController с урлом — /users_crud

Организовать группу роутов (Route::group()) объединенных префиксом — dashboard

Задание 9: Группировка подзадачи

Добавить роут GET /admin -> Admin/IndexController -> index

Задание 10: Группировка подзадачи

Добавить роут POST /admin/post -> Admin/IndexController -> post

Организовать группу роутов (Route::group()) объединенных префиксом — security и мидлваром auth

Задание 12: Middleware подзадачи

Добавить роут GET /admin/auth -> Admin/IndexController -> auth

Задание 13: ApiResource (routes/api.php)

Добавить apiResource контроллер — Api/V1/UserController

Задание 1: Передать данные во view

Http/Controllers/IndexController.php Передайте users во view (название ключа users)

resources/views/table.blade.php Изменить реализацию этой view, расширить ее с использованием layout

resources/views/layouts/app.blade.php Подключите view с меню shared/menu.blade.php

resources/views/auth.blade.php Сделать проверку авторизован пользователь или нет. Если да то вывести ID пользователя. ID пользователя вывести внутри конструкции с проверкой

resources/views/welcome.blade.php Сделать blade component с названием HelloWorld с содержимым во view — Текущая дата в формате Y-m-d.

  • Обязательное условие добавить регистрацию компонента в AppServiceProvider и изменить его alias на hello
  • В итоге alias — hello а класс компонента App\View\Components\HelloWorld
  • Вывести его в указаном месте

resources/views/table.blade.php В эту view с контроллера передается collection c users в переменной data.

  • Выполнить foreach loop в одну строку (специальная директива)
  • Используйте view shared/user.blade.php для item (переменная user во item view)
  • Используйте view shared/empty.blade.php для состояния когда нет элементов

resources/views/table.blade.php Здесь сделайте классический foreach loop

  • Выведите div с $user->name
  • Воспользуйтесь переменной $loop и у нечетных div выведите класс — bg-red-500

Models/Item.php Указать что таблица у модели — products

Http/Controllers/EloquentController.php С помощью модели Item реализовать запрос

Http/Controllers/EloquentController.php Добавить в модель Item scope для фильтрации активных продуктов (scopeActive())

Http/Controllers/EloquentController.php Найти пользователя по id и передать во view либо отдать 404 страницу

Http/Controllers/EloquentController.php Выполнить простое добавление новой записи

Http/Controllers/EloquentController.php Выполнить простое обновление записи

Читайте также:  Css rotate не работает

Http/Controllers/EloquentController.php Выполнить массовое удаление записей

Http/Requests/ItemStoreRequest.php Добавить правила валидации для поля title

Policies/ItemPolicy.php Разрешить добавление продуктов только пользователю с >

Есть предложения? Возникли какие-либо проблемы? Не стестняйтесь и пишите GitHub Issues.

Источник

Run Tests With PHP Artisan Test

Run Tests With PHP Artisan Test cover image

Run Tests With PHP Artisan Test cover image

as an alternative to running your tests with the phpunit command.

This command will run all your tests, until the first test that fails.

Differences

The major differences from running your tests with phpunit can be seen in the output of your terminal.

When we run the tests in this example project about fluent string operations with phpunit , you will see this output:

alt text

When you run the tests with php artisan test , you will receive this:

alt text

Or, if we let one of the tests fail when running phpnunit you will see this:

alt text

Whereas when you run a test that fails with php artisan test it returns this output:

alt text

To summarize, php artisan test will:

1). Show the actual names of the tests that are running.

2). Stop at the first test that fails, subsequent tests are marked as pending.

3). Show the assertion that fails and the method of the test wherein it is executed.

Arguments

As stated in the Laravel docs, you can pass all the arguments to the test command that may be passed to the phpunit command as well, e.g.:

php artisan test —testsuite=»Api»

php artisan test —filter=»StringOperationsTest»

Источник

how to test specific test class using phpunit in laravel

I want to test specific testClass in my project since there are a lot of test class that’s failure and I just want to test one Class at a time. I’ve created the test Class in following folder \test\repositories\ApplicationVersionFormat.php :

assertEquals(true,$appVersion->isValidVersion($version)); > public function testInvalidFormat() < $version = '11.2.3'; $appVersion = new ApplicationVersionFormat(); $this->assertEquals(false,$appVersion->isValidVersion($version)); > public function testInvalidFormat2() < $version = '1.22.3'; $appVersion = new ApplicationVersionFormat(); $this->assertEquals(false,$appVersion->isValidVersion($version)); > public function testInvalidFormat3() < $version = '1.2.33'; $appVersion = new ApplicationVersionFormat(); $this->assertEquals(false,$appVersion->isValidVersion($version)); > public function testInvalidFormat4() < $version = '11.22.33'; $appVersion = new ApplicationVersionFormat(); $this->assertEquals(false,$appVersion->isValidVersion($version)); > > 
  • phpunit «repositories\AppVersionTest» . =>Cannot open file «test/repositories/AppVersionTest.php»
  • phpunit «test\repositories\AppVersionTest» . =>Cannot open file «test/repositories/AppVersionTest.php»
  • phpunit —filter «repositories\AppVersionTest» . =>No tests executed!
  • phpunit —testsuite «repositories\AppVersionTest» . =>No tests executed!

Try checking to some inclusion/exclusion configuration in your phpunit.xml(.dist) files. Can you post this files?

Источник

how to test specific test class using phpunit in laravel

I want to test specific testClass in my project since there are a lot of test class that’s failure and I just want to test one Class at a time.

I’ve created the test Class in following folder \test\repositories\ApplicationVersionFormat.php :

 use App\Repositories\ApplicationVersionFormat; class ApplicationVersionFormatTest extends \TestCase < public function testValidFormat( ) < $version = '1.2.3'; $appVersion = new ApplicationVersionFormat(); $this->assertEquals(true,$appVersion->isValidVersion($version)); > public function testInvalidFormat( ) < $version = '11.2.3'; $appVersion = new ApplicationVersionFormat(); $this->assertEquals(false,$appVersion->isValidVersion($version)); > public function testInvalidFormat2( ) < $version = '1.22.3'; $appVersion = new ApplicationVersionFormat(); $this->assertEquals(false,$appVersion->isValidVersion($version)); > public function testInvalidFormat3( ) < $version = '1.2.33'; $appVersion = new ApplicationVersionFormat(); $this->assertEquals(false,$appVersion->isValidVersion($version)); > public function testInvalidFormat4( ) < $version = '11.22.33'; $appVersion = new ApplicationVersionFormat(); $this->assertEquals(false,$appVersion->isValidVersion($version)); > > 

so I’ve tried this follwing command but none of this works :

  • phpunit «repositories\AppVersionTest» . =>Cannot open file «test/repositories/AppVersionTest.php»
  • phpunit «test\repositories\AppVersionTest» . =>Cannot open file «test/repositories/AppVersionTest.php»
  • phpunit —filter «repositories\AppVersionTest» . =>No tests executed!
  • phpunit —testsuite «repositories\AppVersionTest» . =>No tests executed!

Php Solutions

Solution 1 — Php

After trying several ways, I found out that I don’t need to include the folder to test the specific test class. This works for me it runs all the test on the class:

phpunit —filter ApplicationVersionFormatTest

I think it’s because my ApplicationVersionFormatTest extend The TestCase and return application instance which serves as the «glue» for all the components of Laravel.

Solution 2 — Php

for run phpunit test in laravel by many ways ..

vendor/bin/phpunit --filter methodName className pathTofile.php vendor/bin/phpunit --filter 'namespace\\directoryName\\className::methodName' 
vendor/bin/phpunit tests/Feature/UserTest.php vendor/bin/phpunit --filter tests/Feature/UserTest.php vendor/bin/phpunit --filter 'Tests\\Feature\\UserTest' vendor/bin/phpunit --filter 'UserTest' 
 vendor/bin/phpunit --filter testExample vendor/bin/phpunit --filter 'Tests\\Feature\\UserTest::testExample' vendor/bin/phpunit --filter testExample UserTest tests/Feature/UserTest.php 

for run tests from all class within namespace:

vendor/bin/phpunit --filter 'Tests\\Feature' 

Solution 3 — Php

To do the same thing using artisan run:

php artisan test --filter ApplicationVersionFormatTest 

Solution 4 — Php

For newer version this might work

php artisan test --filter // for instance php artisan test --filter test_example 
php artisan test --filter :: //for instance php artisan test --filter ExampleTest::test_example 

Solution 5 — Php

You can probably manage that with this answer to a related question.

Just mark the class with @group annotation and run PHPUnit with —group

Your command with —filter is not complete. Try this: phpunit —filter AppVersionTest «repositories\ApplicationVersionFormat.php»

Solution 6 — Php

phpunit —filter for example , files to test are, test/repos/EloquentPushTest.php , test/repos/EloquentWebTest.php for testing EloquentWebTest.php

use phpunit —filter ./repos/ElqouentWebpush

Solution 7 — Php

php phpunit-5.7.27.phar -c app/ "src/package/TestBundle/Tests/Controller/ExampleControllerTest.php" 

Solution 8 — Php

Using phpunit.xml

the @group option can be used on classes and methods.

/** * @group active * */ class ArrayShiftRightTest extends TestCase  
/** * @group inactive * */ class BinaryGapTest extends TestCase  
groups> include> group>active group> include> exclude> group>inactive group> exclude> groups> 

the classes that belongs to group active will be executed.

Solution 9 — Php

php artisan test --filter ExampleTest 

Источник

Оцените статью