Lumen testing environment with MongoDB - mongodb

In a service provider I set the Mongo database name I am using within the application like this:
$this->app->bind('MongoDB', function() {
$client = new MongoClient();
return $client->selectDB('myproductiondatabase');
});
When running phpunit to run my tests I want to use a different database that gets recreated on every test. What ive done so far is:
$db = $this->app->environment('production') ? 'myproductiondatabase' : 'mytestingdatabase';
$this->app->bind('MongoDB', function() {
$client = new MongoClient();
return $client->selectDB($db);
});
This doesn't seem quite right. I understand I can make multiple .env files for testing and such. Not sure how when running phpunit from the cmd line it will know which .env file to load.
Whats the best way?

Related

Mocking postgressql using python & pytest

def fetch_holidays_in_date_range(src):
query = "SELECT * from holiday_tab where id = src"
db = dbconnect.connect()
# defining the cursor for reading data
cursor = db.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
# query the database
cursor.execute(query.format(src));
rows = cursor.fetchall()
dbconnect.destroy(cursor, db)
return rows
Could someone help, how to mock this code in pytest or in unittest. I've googled for mock db and I hardly found anything.
Pytest doesn't support you to run the test on production/main DB if you are using pytest-django.
There is a better approach to solve this issue.
Pytest DB resolve method
This says that whenever you run the test with a marker #pytest.mark.django_db, tests are run on another newly created db with name test_your production_db_name.
So if your db name is hello, pytest will create a new db called test_hello and runs tests on it

MongoDB - A Script to Create Indexes

New to MongoDB - at the moment I'm creating indexes directly from my web app however I want to instead have some sort of bash script I run (and more easily maintain) that can create my various text indexes for me.
Wanted to check is this possible? I'm unsure about how I would actually execute it if so - namely I have a Docker image running Docker - so do I have to bash into that then run the .sh? Or would I just specify the DB and collection in the script itself and just run it from terminal as usual?
Any pointers would be appreciated.
Thanks.
You can do it using java script:
var createIndexes = function(fullObj) {
conn = new Mongo();
db = conn.getDB(databaseName);
getMapInd = null;
setMapInd1 = db.testMappings.createIndex( { 'testId': 1}, {unique: true} )
getMapInd = db.testMappings.getIndexes();
printjson("---------------------Below indexes created in Mappings collection-----------------------");
printjson(getMapInd);
};
createIndexes();

How do I run only certain tests in karma?

I have karma config set up correctly, config file, running in the background, just great. As soon as I change and save a file, it reruns the tests.... all 750 of the unit tests. I want to be able to run just a few. Short of manually hacking the config file or commenting out hundreds of tests across many files, is there any easy way to do it?
E.g. when running command line server tests using say mocha, I just use regexp: mocha -g 'only tests that I want'. Makes it much easier to debug and quickly check.
So now I feel foolish. mocha supports a very narrow version of regexp matching.
This runs all tests
describe('all tests',function(){
describe('first tests',function(){
});
describe('second tests',function(){
});
});
This runs just 'first tests'
describe('all tests',function(){
describe.only('first tests',function(){
});
describe('second tests',function(){
});
});
You can also do it.only()
I should have noticed that. Sigh.
You can do that at karma startup time unfortunately, not at runtime.
If you want to change it dynamically you have to put some more effort.
Say you want to focus on a specific set/suite of tests from the beginning, on the karma-mocha plugin page there's this snippet of code to do what you want:
module.exports = function(config) {
config.set({
// karma configuration here
...
// this is a mocha configuration object
client: {
// The pattern string will be passed to mocha
args: ['--grep', '<pattern>'],
...
}
});
};
In order to make the <pattern> parametric you have to wrap the configuration file in a Configurator that will listen CLI and customize the karma configuration for you.
Have a look to this SO answer to know how to setup a very simple Configurator.
I have same question and this is my workround by a little change on karma.conf.js.
In fact, take an argument from command line and modify the pattern in "files".
I use minimist to parse the argument list.
In config file:
/* Begin */
var minimist = require('minimist');
var argv = minimist(process.argv);
var testBase="test/unit";
var testExt=".spec.js";
var unitTestPattern = testBase+'/**/*'+testExt;
if ("test" in argv){
unitTestPattern = testBase+"/"+argv["test"]+testExt;
}
/* End */
module.exports = function(config){
config.set({
//....
files : [
//....
unitTestPattern, //place here
// 'test/unit/**/*.spec.js', //replace this
//....
],
//....
});
};
run in command prompt:
karma start test/karma.conf.js --single-run --test #TEST_CASE_FILE#
a nice extension that can help here is karma-jasmine-html-reporter-livereload
https://www.npmjs.com/package/karma-jasmine-html-reporter-livereload
or karma-jasmine-html-reporter https://www.npmjs.com/package/karma-jasmine-html-reporter?__hstc=72727564.86845f057bb4d741f59d578059e30644.1443860954685.1453095135802.1453138187458.37&__hssc=72727564.1.1453138187458&__hsfp=2285154675
It creates a debug page in which you can run each test individually. very useful for large projects!
1) In your karma.conf.js get the params from the terminal:
var files = (process.env.npm_config_single_file) ? process.env.npm_config_single_file : 'test/test_index.js';
2) In order to run a single test you will need to set an option object with all your configuration (Without files and preprocessors):
var option = {
webpack: {
// webpack configuration
},
// more configuration......
};
3) Set your files path and preprocessors:
option.files = [
{pattern: files, watch: false}
];
option.preprocessors = {};
option.preprocessors[files] = [ 'webpack', 'sourcemap' ];
// call config.set function
config.set(option);
4) Run in the terminal:
npm test --single_file=**/my-specific-file-spec.js
For more information check this PR:
https://github.com/webpack/karma-webpack/pull/178
There are different ways to do it.
Use --grep option. The disadvantage of this is that all the tests are preprocessed before running the specific test suite.
Use .only method. Disadvantage same as no. 1. Using both 1 and 2 method my node process used to crash often saying out of memory.
Limit the files options for processing. This is super fast.
Limit preprocessing to certain folder like Unit or Integration folder.
For this I have used custom cli option --only and in the karma config
const modules = config.only;
and in the the files pattern
files: typeof modules === 'string ? '[`tests/**/${module}/**/*.(test|spec).js`]: 'tests/**/*.(test|spec).js'
Advantage: Developers can run only certain tests when they make a small change way faster by limiting in the preprocessing phase.
You can also use combination of no.3 and no.1 or 2.

Trying to follow the tutorial for zf1: about the database connection

I'm following this tutorial.
When I run php scripts/load.mysql.php it says:
SQLSTATE[42000] [1102] Incorrect database name '/home/tirengarfio/workspace/ZendFW/gaziende/application/../data/db/guestbook-dev.db'
So I just tried to change the line
resources.db.params.dbname = APPLICATION_PATH "/../data/db/guestbook-dev.db"
to
resources.db.params.dbname = "guestbook-dev" and created a new database called guestbook.
but I get another error about the "guestbook" is not a file, exactly:
PHP Warning: file_get_contents(/home/tirengarfio/workspace/ZendFW/gaziende/scripts/data.mysql.sql): failed to open stream: No such file or directory in /home/tirengarfio/workspace/ZendFW/gaziende/scripts/load.mysql.php on line 81
This is the code around the line 81 error (checkout what var_dump() returns):
// Check to see if we have a database file already
$options = $bootstrap->getOption('resources');
$dbFile = $options['db']['params']['dbname'];
if (file_exists($dbFile)) {
unlink($dbFile);
}
// this block executes the actual statements that were loaded from
// the schema file.
try {
$schemaSql = file_get_contents(dirname(__FILE__) . '/schema.mysql.sql');
// use the connection directly to load sql in batches
$dbAdapter->getConnection()->exec($schemaSql);
var_dump($dbFile);die(); // this returns "guestbook-dev"
chmod($dbFile, 0666);
So.. how should I set the name for the database connection exactly?
Note: the example of the tutorial is for Sqlite and I'm trying to use MySQL. Is that point? I never used Sqlite.
Regards
here are the basic application.ini settings for a Mysql db,
resources.db.adapter = "pdo_Mysql"
resources.db.params.username = "username"
resources.db.params.password = "password"
resources.db.params.dbname = "database name"
resources.db.params.charset = "utf8"
resources.db.isDefaultTableAdapter = true //optional but very helpful if you only have one db
Mysql Needs a little more info then SqlLite.
As far as populating the DB for this Tutorial I just took the easy way and copied the SQL into phpmyadmin.
Note:
If you've never used SqlLite before, this might be great chance to learn something new. This tutorial really doesn't need Mysql. :)

memcached not working on codeigniter 2.1.0

I have been trying to make it work for sometime now, but I can't. I am working on a Windows 7 64bits, I have the Memcached Server running as Service, I have the php_memcached.dll extension in the PHP 5.3.8 and when I call it on the app in Codeigniter I do it the right way (I Think).
$this->load->driver('cache', array('adapter' => 'memcached', 'backup' => 'file'));
var_dump($this->cache->memcached->is_supported());
die();
but it throws a false so I don't know what I am doing wrong. When I call it like this:
$this->load->driver('cache', array('adapter' => 'memcached', 'backup' => 'file'));
$data = $this->cache->memcached->get('data_' . $idData);
I get this PHP error:
Fatal error: Call to a member function get() on a non-object in E:\workspace\example\system\libraries\Cache\drivers\Cache_memcached.php on line 50
Thanks for the help :-)
The CI driver is looking for the Apache Module, but in WIN we use mostly the PHP-Class Memcache.
Try to change Line 165 in /system/libraries/Cache/drivers/Cache_memcached.php
$this->_memcached = new Memcached();
For me it works after changing from Memcached to Memcache.
$this->_memcached = new Memcache();
I know this is old, but I just came across the same issue.
On Windows, you should be using "Memcache" rather than "Memcached". To do this, follow the instructions on this page:
http://www.leonardaustin.com/technical/how-to-install-memcached-on-xampp-on-windows-7
Then, to get it working in CI, you'll need to make two small changes to \system\libraries\Cache\drivers\Cache_memcached.php:
In function is_supported(), replace:
if ( !extension_loaded('memcached'))
With:
if ( !extension_loaded('memcached') && !extension_loaded('memcache'))
And in function _setup_memcached(), replace:
$this->memcached = new Memcached();
With:
if(class_exists("Memcached"))
$this->_memcached = new Memcached();
else
$this->_memcached = new Memcache();