Several troubles with PHPUnit - phpunit

I have two controllers. First path of them is controller/news.php, second is controller/admin/news.php. I have routes for each controller.
For the controller/admin/news.php I have
Route::set('news-admin', 'admin/news(/)', array('start' => '\d+'))
->defaults(array(
'directory' => 'admin',
'controller' => 'news',
'action' => 'index',
'start' => 0,
));
For the controller/news.php:
Route::set('news', 'news(/)', array('start' => '\d+'))
->defaults(array(
'controller' => 'news',
'action' => 'index',
'start' => 0,
));
When I use a browser all work OK. When I call the
$response = Request::factory('/news')->execute()
route in an unittest , test runs. But when I call the
$response = Request::factory('admin/news')->execute()
I get only the next message
PHPUnit 3.7.8 by Sebastian Bergmann.
Configuration read from /home/mydir/Projects/www/kohsite/application/tests/phpunit.xml
After several experiments I understood that I can't test route contains a "directory" for controllers placed into subfolders.
Below I've shown my phpunit.xml
<phpunit bootstrap="bootstrap.php" colors="true">
<testsuite name="ApplicationTestSuite">
<directory>./classes</directory>
</testsuite>
<filter>
<whitelist>
<directory suffix=".php">../tests</directory>
<exclude>
<directory suffix="*">../cache</directory>
<directory suffix="*">../config</directory>
<directory suffix="*">../logs</directory>
<directory suffix=".php">../views</directory>
<file>../bootstrap.php</file>
</exclude>
</whitelist>
</filter>
</phpunit>

I assume you are using Kohana 3.x? Im not sure how you have your application setup but when I design a site that has admin controllers I usually create an admin controller that is not in a sub-folder. The default route can handle any requests to the http://domain.com/<controller>/<action>/<id > such as http://domain.com/admin/index.
If I wanted to have a controller specifically for the admin news I would create a folder named "admin", and setup the controller definition like this:
class Controller_Admin_News extends Controller_Admin {
I would then write a route in my bootstrap.php that looks like this:
Route::set('admin_news', 'admin/news(/<action>(/<id>))')
->defaults(array(
'controller' => 'admin_news',
'action' => 'index'
));
Try setting up your app like that and see if it helps.

Sure, I'm using Kohana 3.2. I have controller
class Controller_Admin_News extends Controller_Admin_Common

Related

Symfony 3.0 load config from php file

I try to set up a symfony project with the microcontroller trait. But instead of use a config.yml I want to use a config.php file.
return [
'framework' => [
'secret' => 'secret_'
]
];
What is the best practice to achieve this?
when using microkernel trait, you can use the configureContainer method in your front controller (app.php) to load configuration directly from an array, like this:
protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader)
{
// PHP equivalent of config.yml
$c->loadFromExtension('framework', array(
'secret' => 'S0ME_SECRET'
));
}
docs here
You should use the container to set the parameters like
$container->setParameter('framework.secret', 'secret_');
as explained in the Symfony Docs

Create custom router service

am creating own framework based on Sf2 commponents and i try to create router service.
I i need that service for generateUrl() method
protected function generateUrl($route, $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
{
return $this->get('router')->generate($route, $parameters, $referenceType);
}
I try this
$container = new ContainerBuilder();
$container->setDefinition('router_loader', new Definition('Symfony\Component\Config\Loader\LoaderInterface'));
$container->setDefinition('router', new Definition('Symfony\Component\Routing\Router', array()));
And when i execute in my methodAction
$this->generateUrl('home');
he return me:
Catchable fatal error: Argument 1 passed to
Symfony\Component\Routing\Router::__construct() must be an instance of
Symfony\Component\Config\Loader\LoaderInterface, none given in
D:\xampp\htdocs\my_fw\vendor\symfony\routing\Router.php on line 95
looking on router constructor i see. I need that interface
public function __construct(LoaderInterface $loader, $resource, array $options = array(), RequestContext $context = null, LoggerInterface $logger = null)
how to avoid that implementation in service?
**New update:** routing.php
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
// Routing
$routes = new RouteCollection();
// Home
$routes->add('home', new Route('/', array(
'_controller' => 'MyCompany\\Controller\\HomeController::indexAction',
)));
You are having this error because you are configuring the router service with no service definition the service definition should have your service arguments which is the source of your error because the container try to create the router with no arguments check this
For better use you can configure the router service in the service.yml/.xml file
Edit: The documentation page for the Routing component has detailed setup instructions
Try injecting the router_loader service as an argument into the router service. For this case you have to use the Symfony\Component\DependencyInjection\Reference class.
Routes have to be configured with a config file when using the all in one Router class. You have to use a FileLocator and a real Loader class, like the YamlFileLoader, you can't just use the interface (services generally can't be interfaces in Symfony).
The service container setup for the router service should look like this:
use Symfony\Component\DependencyInjection\Reference;
// Loads config files from the current directory, change this to
// your liking, or add more than one path
$container->setDefinition('router_config_locator', new Definition(
'Symfony\Component\Config\FileLocator', [[__DIR__]]
));
$container->setDefinition('router_loader', new Definition(
'Symfony\Component\DependencyInjection\Loader\YamlFileLoader', [
new Reference('router_config_locator'),
]
));
$container->setDefinition('router',
new Definition('Symfony\Component\Routing\Router', array(
'loader' => new Reference('router_loader'),
// Definition of routes in Yaml form
'resource' => 'routes.yml',
))
);
The routes.yml file contains your route definitions:
home:
path: /home
defaults: {_controller: "MyController:index"}
Also have a look at this documentation page about setting up the routing component, which also talks about setting up the routing without the all in one class and config file.

symfony 1.4 not picking up subdirectory in routing?

I have one symfony 1.4 project where I can happily access the symfony app in a subdirectory www.olddomain.com/clients/
I have tried to achieve the same with another seperate project.
www.newdomain.com/clients/ but the routing won't work fully.
I can access www.newdomain.com/clients/ and it picks up the app and displays the login or content as it should BUT the login form submits to /login, NOT /clients/login as happens with the www.olddomain.com/clients/ project
, I have compared the two and cannot see any difference in the setup.
I have set the WebDir:
$this->setWebDir($this->getRootDir().'/content/clients/');
no_script_name is set to true
I have everything that would be in the web root (index.php, .htaccess, css js etc in /clients/.)
.htaccess in both cases contains
RewriteBase /clients/
If I access www.newdomain.com/clients/login it picks up the need to show the login form fine so that indicates my setup is OK BUT the login form which points to route #login is submitting the form to "/login" not "/clients/login".
I've tried dumping the route on both projects when I directly access /clients/login (see below) and have noticed that on the one that works there are a lot more variables in the 'context' including [ prefix: '/clients'] which would seem to be the key. All of this extra context information except the host variable is missing for www.newdomain.com/clients/login.
Can anyone help me understand what this means and how I might address it? How can I get this 'prefix' paramater set.
DOES WORK (www.olddomain.com/clients/login)
object(sfRoute)[31]
protected 'isBound' => boolean true
protected 'context' =>
array
'path_info' => string '/login' (length=6)
'prefix' => string '/clients' (length=8)
'method' => string 'GET' (length=3)
'format' => null
'host' => string 'www.olddomain.com'
'is_secure' => boolean false
'request_uri' => string 'http:/www.olddomain.com/clients/login'
protected 'parameters' =>
array
'module' => string 'sfGuardAuth' (length=11)
........
DOESN'T WORK (www.newdomain.com/clients/login)
object(sfRoute)[47]
protected 'isBound' => boolean true
protected 'context' =>
array
'host' => string 'www.newdomain.com'
protected 'parameters' =>
array
'module' => string 'sfGuardAuth' (length=11)
.....

Silverstripe 3 Extending Error Mail with HTTP_X_FORWARDED_FOR

By default the error mail only takes these server variables from log.php:
protected static $log_globals = array(
'_SERVER' => array(
'HTTP_ACCEPT',
'HTTP_ACCEPT_CHARSET',
'HTTP_ACCEPT_ENCODING',
'HTTP_ACCEPT_LANGUAGE',
'HTTP_REFERRER',
'HTTP_USER_AGENT',
'HTTPS',
'REMOTE_ADDR',
),
);
How do I add 'HTTP_X_FORWARDED_FOR' to my error e-mails without modifying the core files?
This is actually possible via the new configuration system in Silverstripe. Have a YAML config file with the following:
SS_Log:
log_globals:
'_SERVER':
- 'HTTP_X_FORWARDED_FOR'
This adds HTTP_X_FORWARDED_FOR to the _SERVER array on the log_globals static variable.

laravel development environment sqlite database does not exist

Trying to use sqlite in development environment. It seems to detect the environment correctly but when I try to migrate to development.sqlite I get exception thrown "database does not exist"
artisan command
php artisan migrate --env=development
bootstrap/start.php
$env = $app->detectEnvironment(array(
'development' => array('localhost'),
));
app/config/development/database.php
<?php
return array(
'default' => 'sqlite',
'connections' => array(
'sqlite' => array(
'driver' => 'sqlite',
'database' => __DIR__.'/../database/development.sqlite',
'prefix' => '',
)
)
);
As far as I know laravel is supposed to create the file if it does not exist but since it didn't I tried manually creating the file and still get the exception thrown.
UPDATE: Maybe something not right with the env because the same thing happens if I try ':memory' for the database.
UPDATE 2: I tried running the sample unit test but add to TestCase.php
/**
* Default preparation for each test
*
*/
public function setUp()
{
parent::setUp(); // Don't forget this!
$this->prepareForTests();
}
/**
* Creates the application.
*
* #return Symfony\Component\HttpKernel\HttpKernelInterface
*/
public function createApplication()
{
$unitTesting = true;
$testEnvironment = 'testing';
return require __DIR__.'/../../bootstrap/start.php';
}
/**
* Migrates the database and set the mailer to 'pretend'.
* This will cause the tests to run quickly.
*
*/
private function prepareForTests()
{
Artisan::call('migrate');
Mail::pretend(true);
}
And this too gives the same exception though the testing env is already shipped with laravel. So I'll see if I can find any new issues on that.
Wow, typos and wrong paths.
Copying the sqlite array from config/database.php into config/development/database.php I forgot to change the path to the development.sqlite file from
__DIR__.'/../database/development.sqlite'
to
__DIR__.'/../../database/development.sqlite'
And for the in memory test it should have been
':memory:'
instead of
':memory'
I noticed that my database.php file had the following
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
],
I changed it to read the following, and it worked just fine.
'sqlite' => [
'driver' => 'sqlite',
'database' => database_path('database.sqlite'),
'prefix' => '',
],
One of the problem which I faced was I use "touch storage/database.sqlite" in terminal, so database is created in Storage folder instead of database folder.
in my config/database.php path is database_path('database.sqlite')
'sqlite' => [
'driver' => 'sqlite',
'database' => database_path('database.sqlite'),
'prefix' => '',
],
than I use command "php artisan migrate" which gave me error "Database (/Applications/MAMP/htdocs/FOLDER_NAME/database/database.sqlite) does
not exist."
so it's obvious database file is not in database folder as It was generated in Storage folder, so copy "database.sqlite" from storage folder or run command "touch database/database.sqlite"
Hope that helps.!!
Well, my answer is kinda outdated, but anyway. I faced the same problem, but with Laravel 5, I am using Windows 7 x64. First I manually created SQLite database called 'db' and placed it into storage directory, then fixed my .env file like this:
APP_ENV=local
APP_DEBUG=true
APP_KEY=oBxQMkpqbENPb07bLccw6Xv7opAiG3Jp
DB_HOST=localhost
DB_DATABASE='db'
DB_USERNAME=''
DB_PASSWORD=''
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null`
I thought it would fix my problems, but the command line keeps telling me that database doesn't exist. And then I just checked the path to db in my database.php file and this is why I put database file into storage directory. But nothing changed. And finally I checked db's extension and it was .db, not .sqlite as default extension you see in your sqlite block in database.php. So this is how I reconfigured sqlite piece:
'sqlite' => [
'driver' => 'sqlite',
'database' => storage_path().'/db.db',
'prefix' => '',
],
And of course don't forget to set sqlite as default database in your database.php file. Good luck!
For me it was that path to database had to be '/var/www/html' + location to the database in your project. In my case database was stored in database/db.sqlite so DB_DATABASE='/var/www/html/database/db.sqlite'
I had the same error while running a GitHub action test workflow.
For me the solution was to define the relative path to the database archive into the workflow file:
on:
...
env:
DB_CONNECTION: sqlite
DB_DATABASE: database/database.sqlite
jobs:
laravel-tests:
...
I think that the previous answers reduce the importance of the config and most likely the developers wanted to get the database file like this:
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => database_path(env('DB_DATABASE', 'database').'.sqlite'), // <- like this
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
Tested on Laravel 9.x

Resources