Test Database and Codeception - laravel

I'm working With Laravel 5 / Codeception.
I'm working with a test database.
Here is my config:
acceptance.suite.yml:
class_name: AcceptanceTester
modules:
enabled:
- WebDriver
- \Helper\Acceptance
- Db
- Asserts
config:
WebDriver:
url: 'http://laravel.dev'
browser: 'phantomjs'
window_size: 1024x768
Db:
dsn: 'mysql:host=laravel.dev;dbname=kendo_test'
user: 'homestead'
password: 'secret'
So, here I define my db being my Test db.
Then, in my bootstrap.php I have:
$app->loadEnvironmentFrom('.env.testing');
And .env.testing:
DB_HOST=127.0.0.1
DB_DATABASE=kendo_test
DB_USERNAME=homestead
DB_PASSWORD=secret
As a test, I changed kendo_test to kendo_test2, and it failed, it is using this db.
Now, When I execute an acceptance test, my test fails because row is inserted in main db, not test, And I don't know why....
Here is my test:
public function it_create_user(\AcceptanceTester $I, $scenario)
{
App::setLocale('en');
$user = factory(User::class)->make();
$I = new SimpleUser($scenario);
$I->logAsUser();
$I->dontSee(trans_choice('core.user', 2) . ' </a></li>');
$I->logout();
$I = new SuperAdmin($scenario);
$I->logAsSuperAdmin();
$I->click('#dropdown-user');
$I->click(trans_choice('core.user', 2));
$I->click(trans('core.addModel', ['currentModelName' => trans_choice('core.user', 1)]));
$I->fillField('name',$user->name );
$I->fillField('email',$user->email);
$I->fillField('firstname',$user->firstname);
$I->fillField('lastname',$user->lastname);
$I->fillField('password','111111');
$I->fillField('password_confirmation','111111');
$I->click(trans('core.save')); // <-- Here is should save it
$I->seeInCurrentUrl('/users');
$I->seeInSource(trans('msg.user_create_successful'));
$I->seeInDatabase('ken_users', ['name' => $user->name]);
}
Any Idea why???

When you click $I->click(trans('core.save')); it will be used the .env from your app and not the one from $app->loadEnvironmentFrom.
This is because when running acceptance tests you are interacting with your app via a browser.
The test being run has its own instance, as well as the app accessed by the test.
The only reason here you would use $app->loadEnvironmentFrom is to leverage Eloquent, and even then it must be on a separate connection.

Related

Suddenly, Heroku credentials to a PostgreSQL server gives FATAL password for user error

Without changing anything in my settings, I can't connect to my PostgreSQL database hosted on Heroku. I can't access it in my application, and is given error
OperationalError: (psycopg2.OperationalError) FATAL: password authentication failed for user "<heroku user>" FATAL: no pg_hba.conf entry for host "<address>", user "<user>", database "<database>", SSL off
It says SSL off, but this is enabled as I have confirmed in PgAdmin. When attempting to access the database through PgAdmin 4 I get the same problem, saying that there is a fatal password authentication for user '' error.
I have checked the credentials for the database on Heroku, but nothing has changed. Am I doing something wrong? Do I have to change something in pg_hba.conf?
Edit: I can see in the notifications on Heroku that the database was updated right around the time the database stopped working for me. I am not sure if I triggered the update, however.
Here's the notification center:
In general, it isn't a good idea to hard-code credentials when connecting to Heroku Postgres:
Do not copy and paste database credentials to a separate environment or into your application’s code. The database URL is managed by Heroku and will change under some circumstances such as:
User-initiated database credential rotations using heroku pg:credentials:rotate.
Catastrophic hardware failures that require Heroku Postgres staff to recover your database on new hardware.
Security issues or threats that require Heroku Postgres staff to rotate database credentials.
Automated failover events on HA-enabled plans.
It is best practice to always fetch the database URL config var from the corresponding Heroku app when your application starts. For example, you may follow 12Factor application configuration principles by using the Heroku CLI and invoke your process like so:
DATABASE_URL=$(heroku config:get DATABASE_URL -a your-app) your_process
This way, you ensure your process or application always has correct database credentials.
Based on the messages in your screenshot, I suspect you were affected by the second bullet. Whatever the cause, one of those messages explicitly says
Once it has completed, your database URL will have changed
I had the same issue. Thx to #Chris I solved it this way.
This file is in config/database.js (Strapi 3.1.3)
var parseDbUrl = require("parse-database-url");
if (process.env.NODE_ENV === 'production') {
module.exports = ({ env }) => {
var dbConfig = parseDbUrl(env('DATABASE_URL', ''));
return {
defaultConnection: 'default',
connections: {
default: {
connector: 'bookshelf',
settings: {
client: dbConfig.driver,
host: dbConfig.host,
port: dbConfig.port,
database: dbConfig.database,
username: dbConfig.user,
password: dbConfig.password,
},
options: {
ssl: false,
},
},
},
}
};
} else {
// to use the default local provider you can return an empty configuration
module.exports = ({ env }) => ({
defaultConnection: 'default',
connections: {
default: {
connector: 'bookshelf',
settings: {
client: 'sqlite',
filename: env('DATABASE_FILENAME', '.tmp/data.db'),
},
options: {
useNullAsDefault: true,
},
},
},
});
}

Issue with connecting my express server on heroku to the remote mySQL

I'm trying to deploy my express server on Heroku which needs to connect to the remote MySQL database.
I used 'heroku config:add DATABASE_URL=mysql://dbusername:dbpassword#databasehostIP:databaseserverport/databasename with the correct information but still it tries to connect through wrong address.
I also used 'heroku config:add EXTERNAL_DATABASE_URL=mysql://dbusername:dbpassword#databasehostIP:databaseserverport/databasename with the correct information but still it tries to connect through wrong address.
In my Heroku app panel under 'setting' in 'Config Vars' section I see that DATABASE_URL and EXTERNAL_DATABASE_URL appeared with correct information. but in heroku log I still see the wrong information
This is my sequelize variable on the express server:
const sequelize = new Sequelize('dbName', 'USER', 'Password', {
host:"hostAddress",
dialect: 'mysql'
}
But I see the following on Heroku log:
2019-02-16T18:31:42.231390+00:00 app[web.1]: Unhandled rejection
SequelizeAccessDeniedError: Access denied for user
'USER'#'ec2-54-162-8-141.compute-1.amazonaws.com' (using
password: YES)
How can I change 'ec2-54-162-8-141.compute-1.amazonaws.com' to the remote MySQL host address?
Try setting your variable with something like this:
if (process.env.DATABASE_URL) {
const sequelize = new Sequelize(process.env.DATABASE_URL, {
define: {
freezeTableName: true, // don't make plural table names
underscored: true // don't use camel case
},
dialect: 'mysql',
dialectOptions: {
ssl: true
},
logging: true,
protocol: 'mysql',
quoteIdentifiers: false // set case-insensitive
});
} else {
console.log('Fatal error: DATABASE_URL not set');
process.exit(1);
}

Issues running BrowserStackLocal for website behind firewall

I'm trying to run browserstack behind the firewall.
I tried to run this command on terminal:
RK$ ./BrowserStackLocal --key <key> --force-local
BrowserStackLocal v7.0
You can now access your local server(s) in our remote browser.
Press Ctrl-C to exit
I opened another terminal and I ran the command
npm run test:functional:cr:mobile
I get the following error:
1) Run sample test flow page:
Uncaught WebDriverError: [browserstack.local] is set to true but local testing through BrowserStack is not connected.
This is my config.js
'use strict'
import webdriver from 'selenium-webdriver'
let driver
module.exports = {
getDriverConfiguration: function (testTitle, browserName) {
var capabilities = {
'browserName': process.env.BROWSER || 'Chrome',
'realMobile': 'true',
'os': 'android',
'deviceName': process.env.DEVICE || 'Samsung Galaxy S8',
'browserstack.user': 'USER',
'browserstack.key': 'KEY',
'browserstack.debug': 'true',
'build': 'Build for mobile testing',
'browserstack.local' : 'true',
'browserstack.localIdentifier' : 'Test123'
}
driver = new webdriver.Builder().withCapabilities(capabilities).usingServer('http://hub-cloud.browserstack.com/wd/hub').build()
driver.manage().deleteAllCookies()
return driver
}
}
I enabled browserstack.local to true but I still get this error.
Not sure where I'm going wrong.
Please kindly help.
The error [browserstack.local] is set to true but local testing through BrowserStack is not connected. is returned if your BrowserStackLocal connection (the one you established using ./BrowserStackLocal --key --force-local) is disconnected.
I would suggest you use the following approach instead, to avoid the additional step and easily manage your local testing connection:
npm install browserstack-local
Once you have installed the browserstack-local module, use the following code snippet as reference to modify your code and start browserstack-local from your code itself(before the line driver = new webdriver.Builder().withCapabilities(capabilities).usingServer('http://hub-cloud.browserstack.com/wd/hub').build()), instead of starting it from a separate terminal window:
var browserstack = require('browserstack-local');
//creates an instance of Local
var bs_local = new browserstack.Local();
// replace <browserstack-accesskey> with your key. You can also set an environment variable - "BROWSERSTACK_ACCESS_KEY".
var bs_local_args = { 'key': '<browserstack-accesskey>', 'forceLocal': 'true' };
// starts the Local instance with the required arguments
bs_local.start(bs_local_args, function() {
console.log("Started BrowserStackLocal");
});
// check if BrowserStack local instance is running
console.log(bs_local.isRunning());
// stop the Local instance
bs_local.stop(function() {
console.log("Stopped BrowserStackLocal");
});

In codeception functional test seeInDatabase not works from laravel

I am using codeception for testing in laravel 5.2.
Here is my codeception.yml file:
actor: Tester
paths:
tests: tests_codecept
log: tests_codecept/_output
data: tests_codecept/_data
support: tests_codecept/_support
envs: tests_codecept/_envs
settings:
bootstrap: _bootstrap.php
colors: false
memory_limit: 1024M
extensions:
enabled:
- Codeception\Extension\RunFailed
modules:
config:
Db:
dsn: 'mysql:host=localhost;dbname=kartice_test'
user: '*******'
password: '*******'
dump: tests_codecept/_data/dump.sql
populate: true
cleanup: true
reconnect: true
and here is functional.suite.yml file:
class_name: FunctionalTester
modules:
enabled:
# add framework module here
- \Helper\Functional
- Asserts
- Laravel5:
environment_file: .env.testing
- Db
here is my test method:
public function provera_dodavanja_novog_klijenta(FunctionalTester $I)
{
$this->authenticate($I);
$I->amOnPage('/kancelarija/komitenti/create');
$I->see('Kreiranje novog komitenta');
$I->fillField('input[name=komitent_code]', 'kom1');
$I->fillField('input[name=komitent_name]', 'Komitent 1');
$I->click('btnSave');
$I->seeInDatabase('komitenti', ['code' => 'kom1', 'name' => 'Komitent 1']);
$I->see('Komitent Komitent 1 je uspešno kreiran.');
}
Running functional test fails with message:
Step I see in database "komitenti",{"code":"kom1","name":"Komitent 1"}
Fail No matching records found for criteria {"code":"kom1","name":"Komitent 1"} in table komitenti
Failed asserting that 0 is greater than 0.
What I am doing wrong?
I have seen question Codeception seeInDatabase() doesn't work for me but this didn't helpe me.
You should probably useseeRecord method instead of seeInDatabase. I don't know why but for me first one was working and second one - not.
I use gulp tdd and when testing forms come across this error.
Please check:
You added this to Requests
<YourFormRequest>use App\Http\Requests\<YourFormRequest>;
Ensure the Model for your table is mass assignable
protected $fillable = ['tableField1', 'tableField2']

Sailsjs 0.10.3 - Heroku - RedisToGo - req.session undefined

When using sailsjs v0.10.3 with Redis To Go for session storage, req.session is always undefined.
It is undefined when I deploy both locally and to Heroku. req.session is correctly defined when I use the default memory adapter.
I created a sailsjs app:
sails new testapp
sails generate api test testSet testGet
Installed connect-redis v1.4.7:
npm install connect-redis#~1.4.7
Set the configuration in config/session.js:
adapter: 'redis',
host: 'hoki.redistogo.com',
port: 10015,
db: 'redistogo',
pass: '88819aa089d3dd86235f9fad4cb92e48'
Set the configuration in config/socket.js:
adapter: 'redis',
host: 'hoki.redistogo.com',
port: 10015,
db: 'redistogo',
pass: '88819aa089d3dd86235f9fad4cb92e48'
Created some controller actions which get and set a session value:
UserController.js
testSet: function (req, res) {
req.session.testVar = "I am the test var!";
return res.ok();
},
testGet: function (req, res) {
return res.json({
testVar: req.session.testVar
});
}
And finally deployed to Heroku:
git init
git add .
git commit -m "Initial commit"
heroku create
heroku addons:add redistogo
git push heroku master
git
This is the error:
error: Sending 500 ("Server Error") response:
TypeError: Cannot set property 'testVar' of undefined
at module.exports.testSet (/app/api/controllers/TestController.js:46:25)
It seems like this simple example should work.
Here is a repo of the example above:
https://github.com/derekbasch/sailsjs-redistogo-testapp
Does anyone know what I am doing wrong?
UPDATE:
I tried using the MemoryStore adapter on Heroku to get/set a session variable. That failed with undefined also. It works locally. Now I am even more confused.
We are using rediscloud (sails app on heroku) and the db property is set to 0. Could this be the problem?
Also, you should parse the URL provided by heroku via en env variables. This is what we use (coffeescript):
parseRedisUrl = ( url ) ->
parsed = require( 'url' ).parse( url )
password = (parsed.auth || '').split( ':' )[1]
hostname: parsed.hostname
port: parsed.port
password: password
redis = parseRedisUrl( process.env.REDISCLOUD_URL || "redis://localhost:6379" )
module.exports.session =
secret: '...'
adapter: 'redis'
host: redis.hostname
port: redis.port
pass: redis.password
db: 0
ttl: 60 * 60 * 24

Resources