Test class not found when extending abstract test class - php

I am currently using the lumen framework (v5.6) and writing unit tests for my code.
I have a base class TestCase:
namespace Tests;
$_SERVER["http_proxy"] = "";
abstract class TestCase extends \Laravel\Lumen\Testing\TestCase
{
/**
* Creates the application.
*
* #return \Laravel\Lumen\Application
*/
public function createApplication()
{
return require __DIR__.'/../bootstrap/app.php';
}
}
I use this base class to write my tests, however I have two tests with a lot of overlap (they both test implementations of an interface), so I put the common logic in an abstract class:
namespace Tests\App\IO;
use App\io\PageDataParser;
use App\Models\AdvancedArray;
use App\Services\PageService;
use Mockery;
use Tests\TestCase;
abstract class ParsePageDataTestCase extends TestCase
{
// Test logic here, but not relevant for the question
}
And finally I use this abstract class on my actual test:
namespace Tests\App\IO;
use App\io\JsonPageDataParser;
use App\Models\AdvancedArray;
class JsonParsePageDataTestCaseTest extends ParsePageDataTestCase
{
// Test are here, but not relevant for the question
}
However when I execute JsonParsePageDataTestCaseTest I get the following error:
PHP Fatal error: Class 'Tests\ParsePageDataTestCase' not found in \tests\app\io\JsonParsePageDataTest.php on line 15
I have verified that the structure of the folders is corrected, also tried using 'composer dump-autoloadand verified that mycomposer.jsonhas an entry which specifies a classmap to 'tests/.
I execute my tests using phpunit.xml which loads the bootstrap/app.php, but I still get this error.
The phpunit.xml:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="bootstrap/app.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Application test Suite">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<!-- ENV variables go here -->
</php>
</phpunit>
And finally my composer.json:
{
"name": "laravel/lumen",
"description": "The Laravel Lumen Framework.",
"keywords": ["framework", "laravel", "lumen"],
"license": "MIT",
"type": "project",
"require": {
"php": ">=7.1.3",
"laravel/lumen-framework": "5.6.*",
"vlucas/phpdotenv": "~2.2",
"willdurand/hateoas": "~2.1",
"guzzlehttp/guzzle": "~6.0",
"ext-json": "*",
"vinelab/neoeloquent": "^1.4.6",
"jenssegers/mongodb": "3.4.*",
"predis/predis": "~1.0"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
"phpunit/phpunit": "~7.0",
"mockery/mockery": "~1.0",
"barryvdh/laravel-ide-helper": "~2.5"
},
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
"autoload-dev": {
"classmap": [
"tests/"
]
},
"scripts": {
"post-root-package-install": [
"#php -r \"file_exists('.env') || copy('.env.example', '.env');\""
]
},
"config": {
"preferred-install": "dist",
"sort-packages": true,
"optimize-autoloader": true
},
"minimum-stability": "dev",
"prefer-stable": true
}
If you need any more information please let me know.
Thank you in advance!

This is a problem from the Lumen installation.
When you install laravel the tests folder comes configured as psr-4 on autoload-dev:
{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
...
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
...
"minimum-stability": "dev",
"prefer-stable": true
}
But on Lumen installation doesn't as we can see bellow:
{
"name": "laravel/lumen",
"description": "The Laravel Lumen Framework.",
"keywords": ["framework", "laravel", "lumen"],
"license": "MIT",
"type": "project",
"require": {
"php": ">=7.1.3",
"laravel/lumen-framework": "5.7.*",
"vlucas/phpdotenv": "~2.2"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
"phpunit/phpunit": "~7.0",
"mockery/mockery": "~1.0"
},
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
"autoload-dev": {
"classmap": [
"tests/"
]
},
"scripts": {
"post-root-package-install": [
"#php -r \"file_exists('.env') || copy('.env.example', '.env');\""
]
},
"config": {
"preferred-install": "dist",
"sort-packages": true,
"optimize-autoloader": true
},
"minimum-stability": "dev",
"prefer-stable": true
}
So in order for this to work you will need to change the autoload to:
"autoload-dev": {
"classmap": [
"tests/"
],
"psr-4": {
"Tests\\": "tests/"
}
}

Related

Laravel - Class 'Firebase\JWT\CachedKeySet' not found

I am trying to integrate firebase/php-jwt into my Laravel project.
I added the following code from the firebase/php-jwt to test it out.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use GuzzleHttp;
use Phpfastcache\CacheManager;
use Firebase\JWT\CachedKeySet;
use Firebase\JWT\JWT;
class MyUserController extends Controller
{
public function searchUser(Request $request)
{
$jwksUri = 'omitted';
// Create an HTTP client (can be any PSR-7 compatible HTTP client)
$httpClient = new Client();
// Create an HTTP request factory (can be any PSR-17 compatible HTTP request factory)
$httpFactory = new GuzzleHttp\Psr7\HttpFactory();
// Create a cache item pool (can be any PSR-6 compatible cache item pool)
$cacheItemPool = CacheManager::getInstance('files');
$keySet = new CachedKeySet(
$jwksUri,
$httpClient,
$httpFactory,
$cacheItemPool,
null, // $expiresAfter int seconds to set the JWKS to expire
true // $rateLimit true to enable rate limit of 10 RPS on lookup of invalid keys
);
$decoded = JWT::decode($jwt, $keySet);
$token = $request->bearerToken();
dd($token);
}
}
But I am getting the following error when I run the code
Class 'Firebase\JWT\CachedKeySet' not found
I found a similar question here and I have tried adding the require statement for vendor/autoload.php and it didn't work for me.
I am using PHP version 7.4.29.
Here is my composer.json
{
"name": "laravel/lumen",
"description": "The Laravel Lumen Framework.",
"keywords": ["framework", "laravel", "lumen"],
"license": "MIT",
"type": "project",
"require": {
"php": "^7.3|^8.0",
"firebase/php-jwt": "^6.1",
"flipbox/lumen-generator": "^8.2",
"guzzlehttp/guzzle": "^7.0",
"itsgoingd/clockwork": "^5.1",
"laravel/lumen-framework": "^8.3.1",
"phpfastcache/phpfastcache": "^8.1",
"symfony/psr-http-message-bridge": "^2.1"
},
"require-dev": {
"fakerphp/faker": "^1.9.1",
"mockery/mockery": "^1.3.1",
"phpunit/phpunit": "^9.5.10"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"classmap": [
"tests/"
]
},
"config": {
"preferred-install": "dist",
"sort-packages": true,
"optimize-autoloader": true
},
"minimum-stability": "dev",
"prefer-stable": true,
"scripts": {
"post-root-package-install": [
"#php -r \"file_exists('.env') || copy('.env.example', '.env');\""
]
},
"symfony/psr-http-message-bridge": "0.2"
}
So how do I fix this?

Laravel don't triger to ComposerServiceProvider Class

The "view()->share(...)" I placed in the boot method of the ComposerServiceProvider file does not work. But when I put it in AppServiceProvider it works. I also added ComposerServiceProvider to "providers" section in app.php file.
The error:
ErrorException
Undefined variable: test (View: /Users/devtools/Projects/sites/laravel/resources/views/components/backend/sidebar/menu-list.blade.php)
http://localhost/tr/admin/settings
What could be the problem? Thanks for help.
They are my codes:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
// ...
public function boot()
{
// This code works when I put it in AppServiceProvider.php
view()->composer('*', function ($view) {
view()->share('test', 'deneme');
});
}
}
config/app.php:
// ...
'providers' => [
/*
* Application Service Providers...
*/
App\Providers\ComposerServiceProvider::class,
],
routers/web.php:
Route::prefix(LaravelLocalization::setLocale() . "/admin")
->name('admin.')
->middleware(['localeSessionRedirect', 'localizationRedirect', 'localize', 'auth', 'verified'])
->group(function ()
{
Route::get('/', function () {
return view('backend.home');
})->name('home');
});
composer.json
{
"name": "laravel/laravel",
"type": "project",
"description": "The Laravel Framework.",
"keywords": [
"framework",
"laravel"
],
"license": "MIT",
"require": {
"php": "^7.2.5|^8.0",
"fideloper/proxy": "^4.4",
"fruitcake/laravel-cors": "^2.0",
"guzzlehttp/guzzle": "^6.3.1|^7.0.1",
"laravel/framework": "^7.29",
"laravel/tinker": "^2.5",
"laravel/ui": "^2.4",
"mcamara/laravel-localization": "^1.6"
},
"require-dev": {
"almasaeed2010/adminlte": "~3.0",
"facade/ignition": "^2.0",
"fakerphp/faker": "^1.9.1",
"mockery/mockery": "^1.3.1",
"nunomaduro/collision": "^4.3",
"phpunit/phpunit": "^8.5.8|^9.3.3"
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
]
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"minimum-stability": "dev",
"prefer-stable": true,
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"#php artisan package:discover --ansi"
],
"post-root-package-install": [
"#php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"#php artisan key:generate --ansi"
]
}
}
As you can see these are the file name and paths
SOLUTION:
The problem was that I deleted the "data" folder in
"storage/framework/cache/". When I ran the "php artisan cache:clear"
command, it gave an error. I added the folder and it's okay.
try this :
View::composer('*', function($view)
{
$view->share('test', 'deneme');
});
and do not forget to add this too:
use View;

Lumen using Graph API with socialite

I am trying to get my app to redirect to the Facebook login page so I can access thee Graph API endpoints.
In bootstrap/app.php have
$app->register(App\Providers\AuthServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);
class_alias(Laravel\Socialite\Facades\Socialite::class, 'Socialite');
$app->register(Laravel\Socialite\SocialiteServiceProvider::class);
My controller is:
<?php
namespace App\Http\Controllers\Facebook;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Facades\Socialite;
class FacebookController extends Controller
{
public function redirectToProvider(Request $request)
{
return Socialite::with('facebook')->redirect();
}
public function handleProviderCallback(Request $request)
{
//here you hadle input user data
$user = Socialite::with('facebook')->user();
}
}
My routes:
Route::get('facebook','App\Http\Controllers\AuthController#redirectToProvider');
Route::get('callback','App\Http\Controllers\AuthController#handleProviderCallback');
My composer.json
{
"name": "laravel/lumen",
"description": "The Laravel Lumen Framework.",
"keywords": ["framework", "laravel", "lumen"],
"license": "MIT",
"type": "project",
"require": {
"php": "^7.2.5",
"facebook/graph-sdk": "^5.6",
"laravel/lumen-framework": "^7.0",
"laravel/socialite": "^4.2",
"laravel/ui": "^2.0"
},
"require-dev": {
"fzaninotto/faker": "^1.9.1",
"mockery/mockery": "^1.3.1",
"phpunit/phpunit": "^8.5"
},
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
"autoload-dev": {
"classmap": [
"tests/"
]
},
"config": {
"preferred-install": "dist",
"sort-packages": true,
"optimize-autoloader": true
},
"minimum-stability": "dev",
"prefer-stable": true,
"scripts": {
"post-root-package-install": [
"#php -r \"file_exists('.env') || copy('.env.example', '.env');\""
]
}
}
All posts I have seen use the config/servcies.php or config/app.php files however I cannot and these files in lumen
Unsure if this is helpful but get these errors when go to the http://local/admin/facebook/login page
at /Applications/MAMP/htdocs/facebook/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php:230
at Laravel\Lumen\Application->handleDispatcherResponse(array(0))
(/Applications/MAMP/htdocs/facebook/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php:170)
at Laravel\Lumen\Application->Laravel\Lumen\Concerns\{closure}(object(Request))
(/Applications/MAMP/htdocs/facebook/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php:426)
at Laravel\Lumen\Application->sendThroughPipeline(array(), object(Closure))
(/Applications/MAMP/htdocs/facebook/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php:172)
at Laravel\Lumen\Application->dispatch(null)
(/Applications/MAMP/htdocs/facebook/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php:109)
at Laravel\Lumen\Application->run()
(/Applications/MAMP/htdocs/facebook/public/index.php:28)

Problem with composer package on production server - Laravel project

My problem is BadMethodCallException when trait method calls.
The package is kalnoy/nestedset for Laravel. On my local server all works perfect, but then I create my app on production server, I always have this exception:
Method Illuminate\Database\Query\Builder::descendants does not exist.
What I tried to do without result:
1. composer init
2. composer dump-autoload
3. delete and deployed project few times
4. composer require kalnoy/nestedset
5. Many hours of googling.
What thoughts about it? Has anyone had such a problem and sloved it?
My model:
namespace App;
use Illuminate\Database\Eloquent\Model,
Kalnoy\Nestedset\NodeTrait;
class Category extends Model
{
use NodeTrait;
protected $table = 'categories';
public function getOnMainItems($limit = 6)
{
return Category::where('main', 1)->limit($limit)->get();
}
}
Method what "doesn't exist":
namespace App\Services;
use App\Category;
use Kalnoy\Nestedset\Collection;
class CategoryService
{
/**
* #param string $slug
* #return array $categories
*/
public function getCatalogCategoriesForFilter(string $slug = '')
{
$categories = [];
if ($slug !== '') {
$currentCategory = Category::where([['category_slug', $slug], ['active', 1]])->limit(1)->get();
$categoriesByParent = Category::defaultOrder()->descendantsOf($currentCategory[0]->id);
foreach ($categoriesByParent as $category) {
$categories[] = $category->id;
}
}
return $categories;
}
}
My composer.json file
{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
"php": "^7.1.3",
"darryldecode/cart": "~4.0",
"doctrine/dbal": "^2.8",
"fideloper/proxy": "^4.0",
"kalnoy/nestedset": "^4.3",
"laravel/framework": "5.6.*",
"laravel/tinker": "^1.0",
"predis/predis": "^1.1"
},
"require-dev": {
"filp/whoops": "^2.0",
"fzaninotto/faker": "^1.4",
"mockery/mockery": "^1.0",
"nunomaduro/collision": "^2.0",
"phpunit/phpunit": "^7.0"
},
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"extra": {
"laravel": {
"dont-discover": [
]
}
},
"scripts": {
"post-root-package-install": [
"#php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"#php artisan key:generate"
],
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"#php artisan package:discover"
]
},
"config": {
"preferred-install": "dist",
"sort-packages": true,
"optimize-autoloader": true
},
"minimum-stability": "dev",
"prefer-stable": true
}
Thanks everyone.
UPDATE:
Error message:
(1/1) BadMethodCallException
Method Illuminate\Database\Query\Builder::descendants does not exist.
in Builder.php line 2816
at Builder->__call('descendants', array(2))
in Builder.php line 1286
at Builder->__call('descendants', array(2))
in CategoryService.php line 38
at CategoryService->getCatalogCategories('postelnoe-bele')
in GoodsController.php line 41
Thanks everyone who helps me.
I sloved this.
The problem was in
Category::where('active', 1)->descendants($categoryId);
The Category::where('active', 1) returns queryBuilder object, which has not descendants method, it availabe on Category (model object).
The right way is
Category::descendants($categoryId);
I was embarrassed cause wrong way works on my local server. If somebody can explain this thing I would very grateful.

class not found with composer autoloader

I have this in my composer.json
{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
"php": ">=7.0.0",
"alchemy/zippy": "^0.4.8",
"barryvdh/laravel-debugbar": "^3.1",
"fideloper/proxy": "~3.3",
"graham-campbell/exceptions": "^10.0",
"intervention/image": "^2.4",
"intervention/imagecache": "^2.3",
"laravel/framework": "5.5.*",
"laravel/tinker": "~1.0",
"laravelcollective/html": "^5.5",
"symfony/dom-crawler": "^3.3"
},
"files": [
"vendor/redbutton/text-image-alpha/vendor/autoload.php"
],
"require-dev": {
"filp/whoops": "^2.1",
"fzaninotto/faker": "~1.4",
"mockery/mockery": "0.9.*",
"phpunit/phpunit": "~6.0"
},
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"extra": {
"laravel": {
"dont-discover": [
]
}
},
"scripts": {
"post-root-package-install": [
"#php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"#php artisan key:generate"
],
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"#php artisan package:discover"
]
},
"config": {
"preferred-install": "dist",
"sort-packages": true,
"optimize-autoloader": true
}
}
The php files for my package are in a laravel installation:
/vendor/redbutton/text-image-alpha/src/
When I try to call a file I get the message:
Class 'Class 'RedButton\TextImageAlpha\TextImageAlpha' not found' not found
I use this to try and call the class:
$image = new \RedButton\TextImageAlpha\TextImageAlpha( 'some string' );
The file in /vendor/redbutton/text-image-alpha/src/TextImageAlpha.php looks like this:
<?php
namespace RedButton\TextImageAlpha;
use RedButton\TextImageAlpha\Exceptions;
use RedButton\Tools\Objects;
/**
* TextImageAlpha class convert a text to image.
*
* #author Tomas Rathouz <trathouz at gmail.com>
*/
class TextImageAlpha
{
// lots of code
}
This is my first composer package and I don't really have an idea of what is going wrong here. Could someone please explain to me what I'm doing wrong?
Good news. I've looked at your package at Bitbucket and you're doing it right in its composer.json:
Drop unnecessary code from composer.json
I've noticed in pasted composer.json there is manual adding of some vendor file.
"files": [
"vendor/redbutton/text-image-alpha/vendor/autoload.php"
],
/vendor nested in /vendor doesn't make sense as it might duplicate autoloading and break it.
Also I don't see redbutton/text-image-alpha in require section, where it should be.
How to add package the right way?
To install your package just call composer:
composer require redbutton/text-image-alpha
And that's it.
It should appear in require section in composer.json. Composer will autoload it by rules in composer.json of the package - here.
Test
I've tried following code and class is found correctly:
<?php
require __DIR__ . '/vendor/autoload.php';
$image = new \RedButton\TextImageAlpha\TextImageAlpha('some string');
var_dump($image);
Having composer.json:
{
"require": {
"redbutton/text-image-alpha": "^1.0"
}
}

Categories