I am new in PHPUnit and i am required to run the test using browser and save the result in xml format.
But every time when i run this code, i got following error:
FatalErrorException: Error: Interface 'PHPUnit_Framework_Test' not found in /usr/share/php/PHPUnit/Framework/TestSuite.php line 83
My code looks like this:
require_once '/var/www/Drillsight/app/autoload.php';
require_once "PHPUnit/Framework/TestSuite.php";
require_once "PHPUnit/TextUI/TestRunner.php";
$run_command = new PHPUnit_TextUI_Command;
$run_command ->run(array('phpunit', '--log-junit', 'results.xml', 'MyPHPUnitTest.php'),true);
Can anybody help in this matter?
Any other recommendation options will be highly appreciated !
Thanks in advance !
Do it really need to be runned in a browser?
I personally use a .bat file containing all my unit test like this
REM GEM_MECHANIC_TESTS
ECHO.
ECHO FILE : GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
CALL PHPUNIT %~DP0/../../../GENERAL_CONTROLER/TEST/GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
ECHO.
REM GEM_MECHANIC_INTERFACE_BUILDER_TESTS
ECHO.
ECHO FILE : HTML_GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
CALL PHPUNIT %~DP0/../../../GENERAL_CONTROLER/TEST/TEST_INTERFACE_BUILDER/HTML_GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
ECHO.
And run a command like this in my Xampp console:
C:\xampp\htdocs\PC_administration_interface\Controler/script/temp_unit_test.bat >C:\xampp\htdocs\PC_administration_interface\Controler/test_result.txt
Or if you want to do it automatically each night with a windows task:
Launch_xampp.bat
#echo off
tasklist | find /i "xampp-control.exe" && goto :eof
start /b "xampp-control.exe" "C:\xampp\xampp-control.exe"
launch_automatic_test.bat
#echo off
call %~DP0\launch_xampp.bat
call %~DP0\..\..\..\..\xampp_shell.bat
cls
call %~DP0\run_unit_test.bat > "%~DP0\..\test_result.txt"
The method don't matter as much as I export the result in a textfile and than use PHP to parse the output (you can just change the code a bit to produce XML).
public static function fetchTestResult(&$errorMessage){
$echoString = '';
$failure = false;
$fileContent = '';
$errorMessage = '';
$dbManager = GeneralDbManager::getInstance();
if (file_exists(realpath(dirname(__FILE__)) . '/test_result.txt')) {
#$fileContent = file(realpath(dirname(__FILE__)) . '/test_result.txt');
if ($fileContent === false){
$errorMessage = $dbManager->getErrorMessage('UNIT_TEST_RESULT_LOG_ERR', "An error happened while reading the unit tests results log.");
}
else{
unlink(realpath(dirname(__FILE__)) . '/test_result.txt');
if (file_exists(realpath(dirname(__FILE__)) . '/script/temp_unit_test.bat')) {
unlink(realpath(dirname(__FILE__)) . '/script/temp_unit_test.bat');
}
$echoString = HtmlTagBuilder::createCustomTextArea("TA_UNIT_TEST_RESULT", TextAlign::ALIGN_LEFT, false, 1100, 500);
foreach ($fileContent as $line){
if (StringManager::stringStartWith($line, "FILE :")){
$failure = false;
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::TITLE_LINE);
}
elseif (StringManager::stringStartWith($line, "time:")){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::WARNING_LINE);
}
elseif (StringManager::stringStartWith($line, "OK (")){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::SUCCESS_LINE);
}
elseif ((StringManager::stringStartWith($line, "There ") and strpos($line, "failure") !== false)
or $failure === true){
$failure = true;
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::ERROR_LINE);
}
elseif (strpos(strtolower($line), "failure") !== false){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::ERROR_LINE);
}
else{
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::REGULAR_LINE);
}
}
$echoString .= '</DIV><br><br>';
}
}
else{
$errorMessage = $dbManager->getErrorMessage('UNIT_TEST_NO_RESULT_LOG_ERR', "You must run the unit test and generate the test log before displaying it.");
}
return $echoString;
}
Related
I am trying to upload an image to a WordPress website using my custom code but it is not working. The directory is writable and there is no other error. The subdirectory 'contracts' was created manually.
$uploads = wp_get_upload_dir();
$fileTmpPath = $_FILES['upload_img']['tmp_name'];
$fileName = $_FILES['upload_img']['name'];
$fileSize = $_FILES['upload_img']['size'];
$fileType = $_FILES[$filename]['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
$newFileName = md5(time() . $fileName) . '.' . $fileExtension;
$allowedfileExtensions = array('jpg', 'gif', 'png');
if (in_array($fileExtension, $allowedfileExtensions)) {
$dest_path = $uploads['basedir'].'/contracts/'. $newFileName;
if ( !is_writeable( $upload_path ) ) {
echo 'Unable to write to directory.';
}
if(move_uploaded_file($fileTmpPath, $dest_path)){
echo $uploads['baseurl'].'/contracts/'.$newFileName;
}
}
There is a small typo in the code, not sure if this would stop execution but non the less try with this code
$uploads = wp_get_upload_dir();
$fileTmpPath = $_FILES['upload_img']['tmp_name'];
$fileName = $_FILES['upload_img']['name'];
$fileSize = $_FILES['upload_img']['size'];
$fileType = $_FILES['upload_img']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
$newFileName = md5(time() . $fileName) . '.' . $fileExtension;
$allowedfileExtensions = array('jpg', 'gif', 'png');
if (in_array($fileExtension, $allowedfileExtensions)) {
$dest_path = $uploads['basedir'].'/contracts/'. $newFileName;
if ( !is_writeable( $upload_path ) ) {
echo 'Unable to write to directory.';
}
if(move_uploaded_file($fileTmpPath, $dest_path)){
echo $uploads['baseurl'].'/contracts/'.$newFileName;
}
}
I'm new to PHPUnit. I'm developing on an existing system, adding new features. I want to use PHPUnit to test codes I made. However, the system runs only on server (CGI) environment (access from a browser), and everything breaks while running from command-line.
Is it possible to setting PHPUnit to make a test suite which can be invoked from web browser?
Personally, I'm using windows task manager (cron can do the same thing on linux) to generate my unit test and send it to a text file every night.
Instead of display it directly in the web browser like I do, you could parse the result file directly on your server and then send the html output by email. So you could simply examine the result page on your local machine every morning like I do. Here's some code to start up your solution (on windows/PHP).
In task manager:
Action 1: C:\xampp\htdocs\PC_administration_interface\Controler\Script\launch_automatic_test.bat
Action 2: "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Argument action 2: http://localhost/PC_administration_interface/view/unit_test.php?DISPLAY_RESULT=TRUE
Launch_automatic_test.bat
#echo off
call %~DP0\launch_xampp.bat
call %~DP0\..\..\..\..\xampp_shell.bat
cls
call %~DP0\run_unit_test.bat > "%~DP0\..\test_result.txt"
launch_xampp_bat
#echo off
tasklist | find /i "xampp-control.exe" && goto :eof
start /b "xampp-control.exe" "C:\xampp\xampp-control.exe"
And here's a sample of run_unit_tets.bat
#ECHO OFF
CLS
REM GEM_MECHANIC_TESTS
ECHO.
ECHO FILE : GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
CALL PHPUNIT %~DP0/../../../GEM_MECHANIC/CONTROLER/TEST/GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
ECHO.
REM GEM_MECHANIC_INTERFACE_BUILDER_TESTS
ECHO.
ECHO FILE : HTML_GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
CALL PHPUNIT %~DP0/../../../GEM_MECHANIC/CONTROLER/TEST/TEST_INTERFACE_BUILDER/HTML_GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
ECHO.
Then I'm launching a web page that parse my result and display it in the web browser:
public static function fetchTestResult(&$errorMessage){
$echoString = '';
$failure = false;
$fileContent = '';
$errorMessage = '';
$dbManager = GeneralDbManager::getInstance();
if (file_exists(realpath(dirname(__FILE__)) . '/test_result.txt')) {
#$fileContent = file(realpath(dirname(__FILE__)) . '/test_result.txt');
if ($fileContent === false){
$errorMessage = $dbManager->getErrorMessage('UNIT_TEST_RESULT_LOG_ERR', "An error happened while reading the unit tests results log.");
}
else{
unlink(realpath(dirname(__FILE__)) . '/test_result.txt');
if (file_exists(realpath(dirname(__FILE__)) . '/script/temp_unit_test.bat')) {
unlink(realpath(dirname(__FILE__)) . '/script/temp_unit_test.bat');
}
$echoString = HtmlTagBuilder::createCustomTextArea("TA_UNIT_TEST_RESULT", TextAlign::ALIGN_LEFT, false, 1100, 500);
foreach ($fileContent as $line){
if (StringManager::stringStartWith($line, "FILE :")){
$failure = false;
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::TITLE_LINE);
}
elseif (StringManager::stringStartWith($line, "time:")){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::WARNING_LINE);
}
elseif (StringManager::stringStartWith($line, "OK (")){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::SUCCESS_LINE);
}
elseif ((StringManager::stringStartWith($line, "There ") and strpos($line, "failure") !== false)
or $failure === true){
$failure = true;
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::ERROR_LINE);
}
elseif (strpos(strtolower($line), "failure") !== false){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::ERROR_LINE);
}
else{
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::REGULAR_LINE);
}
}
$echoString .= '</DIV><br><br>';
}
}
else{
$errorMessage = $dbManager->getErrorMessage('UNIT_TEST_NO_RESULT_LOG_ERR', "You must run the unit test and generate the test log before displaying it.");
}
return $echoString;
}
Additional note: I'm currently getting some information about CGI and it seem that it is pretty inefficient. You might also consider take a look at this post (question and answers):
What is Common Gateway Interface (CGI)?
I have been working on a powershell script that uses a .txt file to download multiple files from tinyurls. I have been successful in using Jobs to make this happen simultaneously, thanks to those on this forum.
The project requires some pretty large files to be downloaded, and using the current method has no progress indicator. I figured some users might think the program died. Looking for a way give a status of where it is in the download. Here is what I came up with, but I'm lost in how to pipe this information back out to the console. Any suggestions?
#Checks to see if NT-Download folder is on the Desktop, if not found, creates it
$DOCDIR = [Environment]::GetFolderPath("Desktop")
$TARGETDIR = "$DOCDIR\NT-Download"
if(!(Test-Path -Path $TARGETDIR )){
New-Item -ItemType directory -Path $TARGETDIR
}
$filepaths = Resolve-Path "files.txt"
Get-Content "$filepaths" | Foreach {
Start-Job {
function Save-TinyUrlFile
{
PARAM (
$TinyUrl,
$DestinationFolder
)
$response = Invoke-WebRequest -Uri $TinyUrl
$filename = [System.IO.Path]::GetFileName($response.BaseResponse.ResponseUri.OriginalString)
$filepath = [System.IO.Path]::Combine($DestinationFolder, $filename)
$totalLength = [System.Math]::Floor($response.get_ContentLength()/1024)
$responseStream = $response.GetResponseStream()
$buffer = new-object byte[] 10KB
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $count
try
{
$filestream = [System.IO.File]::Create($filepath)
$response.RawContentStream.WriteTo($filestream)
$filestream.Close()
while ($count -gt 0)
{
[System.Console]::CursorLeft = 0
[System.Console]::Write("Downloaded {0}K of {1}K", [System.Math]::Floor($downloadedBytes/1024), $totalLength)
$targetStream.Write($buffer, 0, $count)
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $downloadedBytes + $count
}
"`nFinished Download"
$targetStream.Flush()
$targetStream.Close()
$targetStream.Dispose()
$responseStream.Dispose()
}
finally
{
if ($filestream)
{
$filestream.Dispose();
}
}
}
Save-TinyUrlFile -TinyUrl $args[0] -DestinationFolder $args[1]
} -ArgumentList $_, "$TARGETDIR"
}
Have a look at Write-Progress
PS C:> for ($i = 1; $i -le 100; $i++ )
{write-progress -activity "Search in Progress" -status "$i% Complete:" -percentcomplete $i;}
Far more simple way : rely on Bits:
Start-BitsTransfer -Source $tinyUrl
I am having a problem in sending Arduino data into my database. I am currently using WAMPSERVER. I have an arduino mini w/ ATMEGA 328 and I am using ENC28J60. The problem is I have tried different libraries and examples to send data into the server but I failed. I just notice that some libraries are not compatible with my enc28J60. I have tried UIPEthernet.h, Ethernet.h, etherShield.h and EtherCard.h. The etherShield.h and EtherCard.h seemed to work just fine. But I prefer to use EtherCard.h because I heard etherShield is the older lib. I know a little php.
I think the things that might guide me is to see a working example of using the EtherCard.h library demonstrating the sending of sensor data from arduino into my database. The network setup I am currently working on is that, the ENC28J60 is connected in my home network with an ip address of 192.168.10.10. The server to which I placed the database is my laptop with an IP address of 192.168.10.2. I am placing the php files in this directory C:\wamp\www. I hope I have explained it well. I'm sorry for my English.
I am currently working of a port of my homewatch server from Arduino Uno w Ethernet lib to AVR-NETIO with Ethercard lib (or UIPEthernet).
On the server side there is a Apache/PHP/MySQL server.
To update data on a webserver connected database, you can use POST or GET requests to a php web page. These data can then be added easily to a database and the same or another web page can also display the data of the database.
<?php
require 'dbhelp.php';
//header('Content-type: text/plain');
echo "<html>";
echo "<head>";
echo "<meta name='viewport' content='width=device-width, user-scalable=false, initial-scale=1;'>";
echo "</head>";
echo "<body>" . "<h2>Temperatur und Luftfeuchte</h2>";
// GET requests are sent as a query string on the URL:
// GET index.html?name1=value&name2=value HTTP/1.1
// Host: about.com
// http://192.168.0.40/homewatch/index.php?channel=1&temp=165&humidity=80&datetime=010120131234
if($DEBUG){
print("<pre>");
print_r($_GET);
print("</pre>");
}
openDB();
if( isset($_GET['channel']) && isset($_GET['temp']) && isset($_GET['humidity']) )
{
if($DEBUG)
echo "<p>addData()";
$c=$_GET['channel'];
$t=$_GET['temp'];
$h=$_GET['humidity'];
addData($c, $t, $h);
if($DEBUG)
echo "<p>all done";
//listData();
echo "<p>OK updated data for channel:" . $c . "</p>";
}
else
{
if($DEBUG)
echo "listData()";
//listData();
//echo "<p>missing arg";
}
echo "<p><a href='linechart_hour.php'>Stunden-Übersicht</a></p>";
echo "<p><a href='barchart_days.php'>Tages-Übersicht</a></p>";
echo "<p><a href='http://www.unwetterzentrale.de/uwz/getwarning_de.php?plz=41363&uwz=UWZ-DE&lang=de'>Unwetterwarnungen Jüchen</a></p>";
echo showAllCharts();
//#################################################################################
// see http://code.google.com/p/googlechartphplib/wiki/GettingStarted
//#################################################################################
// don't forget to update the path here
require './lib/GoogleChart.php';
$chart = new GoogleChart('lc', 500, 200);
// manually forcing the scale to [0,100]
$chart->setScale(0,100);
// add one line
$data = new GoogleChartData(array(49,74,78,71,40,39,35,20,50,61,45));
$chart->addData($data);
// customize y axis
$y_axis = new GoogleChartAxis('y');
$y_axis->setDrawTickMarks(false)->setLabels(array(0,50,100));
$chart->addAxis($y_axis);
// customize x axis
$x_axis = new GoogleChartAxis('x');
$x_axis->setTickMarks(5);
$chart->addAxis($x_axis);
echo $chart->toHtml();
//#################################################################################
// END
//#################################################################################
echo "<p>v0.9" . "</body>" . "</html>";
?>
the dbhelp.php file creates the DB automatically if not already exists:
<?php
//global dbhelp.php file
$server="localhost";
$user="root";
$passwd="password";
$names=array(
1 => "Aussen",
2 => "Schlaf",
3 => "Andreas");
$DEBUG=false;
function openDB(){
global $DEBUG;
global $user;
global $passwd;
$link = mysql_connect("localhost", $user, $passwd);
if(!$link){
echo "SqlConnect failed";
echo mysql_error();
}
else
if($DEBUG)
echo "SqlConnect OK";
$query="CREATE database IF NOT EXISTS avrdb;";
$result = mysql_query($query, $link);
if(!$result){
echo "CreateDB failed";
echo mysql_error();
}
else
if($DEBUG)
echo "CreateDB OK";
$result = mysql_select_db("avrdb", $link);
if(!$result){
echo "SelectDB failed";
echo mysql_error();
}
else
if($DEBUG)
echo "SelectDB OK";
$query="CREATE TABLE IF NOT EXISTS `avrtemp` (" .
"`id` int(11) NOT NULL AUTO_INCREMENT, " .
"`channel` int(11), " .
"`temp` int(11), " .
"`humidity` int(11), " .
"`date_time` TIMESTAMP, " .
"PRIMARY KEY (`id`) );";
$result = mysql_query($query, $link);
if(!$result){
echo "CreateTable failed";
echo mysql_error();
}
else
if($DEBUG)
echo "CreateTable OK";
return true;
}
...
function addData($c,$t,$h){
global $DEBUG;
$lastStoredDateTime=getLastStoredDateTime();
if($DEBUG){
echo "<p>" . $c . "</p>\n";
echo "<p>LastDateTime=".$lastStoredDateTime."</p>\n";
}
// add data but do not save seconds (use 00)
$query="INSERT INTO avrtemp (`channel`,`temp`,`humidity`,`date_time`)".
" VALUES ( $c,$t,$h,".
// " DATE_FORMAT(NOW()),".
" DATE_FORMAT('".$lastStoredDateTime."', ".
" '%Y-%c-%d %H:%i') )";
if($DEBUG)
echo "<p>" . $query;
$result = mysql_query($query);
if(!$result){
echo "addData failed";
echo mysql_error();
}
else
if($DEBUG)
echo "addData OK";
}
The Arduino posts (using GET) updated data every 5 minutes. The data arrives at the Arduino via 433MHz wireless sensors every minute or so.
Using the Ethernet Lib the data update is done via
char cBuf[maxBuf+1];
const char getHttpString[] =
"GET /homewatch/index.php?channel=%i&temp=%i&humidity=%i&time=%i\0";
...
// and send data: /index.php?channel=1&temp=165&humidity=80&datetime=010120131234
if (client.connect(server, 80)) {
Serial.println("connected. Send GET...");
snprintf(cBuf, maxBuf,
getHttpString,
sensorData[idxChannel].channel,
sensorData[idxChannel].temp,
sensorData[idxChannel].humidity,
sensorData[idxChannel].time_long
);
Serial.println(F("####"));
Serial.println(cBuf);
Serial.println(F("####"));
client.println(cBuf);
...
https://github.com/hjgode/homewatch/blob/master/arduino/SketchBook/WebClientTemperature/WebClientTemperature.ino:
The string "GET /homewatch/index.php?channel=%i&temp=%i&humidity=%i&time=%i\0" is simply filled with actual sensor data and the server saves that to its database.
The Ethercard lib comes with similar examples: see the examples noipClient, pachube and webclient. Unfortunately I was not yet able to adopt these for my AVR-NETIO.
The code to post (GET) some data to the server I am currently working is
void sendData(int idxChannel){
Serial.print(F("in sendData for idx=")); Serial.println(idxChannel);
byte sd;
int channel=sensorData[idxChannel].channel;
int temp=sensorData[idxChannel].temp;
int humidity=sensorData[idxChannel].humidity;
char* stime="201301011122";
stime=printDateTime((char*)&stime, 13, sensorData[idxChannel].time_long);
if(sensorData[idxChannel].bUpdated==0){
//nothing new
if (MYDEBUG==0){
Serial.println(F("leaving for not updated channel data"));
goto exit_sendData;
}
else
{
sensorData[idxChannel].channel=idxChannel;
sensorData[idxChannel].temp=222;
sensorData[idxChannel].humidity=55;
sensorData[idxChannel].time_long=now();
}
}
// generate two fake values as payload - by using a separate stash,
// we can determine the size of the generated message ahead of time
sd = stash.create();
stash.print("0,");
stash.println((word) millis() / 123);
stash.print("1,");
stash.println((word) micros() / 456);
stash.save();
// generate the header with payload - note that the stash size is used,
// and that a "stash descriptor" is passed in as argument using "$H"
Stash::prepare(PSTR("GET http://$F/homewatch/index.php?channel=$D&temp=$D&humidity=$D&time=$S" "\r\n"
"Host: $F" "\r\n"
"Content-Length: $D" "\r\n"
"\r\n"
"$H"),
website,
channel,
temp,
humidity,
stime,
website, stash.size(), sd);
// send the packet - this also releases all stash buffers once done
ether.tcpSend();
exit_sendData:
lastConnectionTime = now();//millis();
Serial.println(F("...end of sendData()"));
}
As you see, there is a formatted string
PSTR("GET http://$F/homewatch/index.php?channel=$D&temp=$D&humidity=$D&time=$S"
which is filled with variables. $F fills from Flash Memory, $D a number var, $S from a RAM memory string. Using this without my SensorCode (which uses Interrupts) is working.
it shows"-- Debug: Undefined variable: wordscut on line 168 of /wp-content/theme"
function cutstr($string, $length) {
$string =strip_tags($string);
preg_match_all("/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|
[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/", $string, $info);
for($i=0; $i<count($info[0]); $i++) {
$wordscut.= $info[0][$i];
$j= ord($info[0][$i]) > 127 ? $j + 2 : $j + 1;
if ($j > $length - 3) {
return $wordscut." ...";
}
}
return join('', $info[0]);
}
the above is my function. i know in php, it's right if a variable doesn't be declared before it is used.why it shows"Undefined variable: wordscut, j..... thank you.
2,* REQUIRED: Non-printable characters were found in the '''functions.php''' file. You may want to check this file for errors.
what is Non-printable characters .how to correct it? thank you.
This is one one classic bug.
When PHP started your script, $wordscut is not defined. When you run
$wordscut .= "sometext";
The code actually do
$wordscut = $wordscut . "sometext";
At this point, $wordscut is not available, thus Undefined Variable error occurred.
To fix it, add
$wordscut = '';
before
for($i=0; $i<count($info[0]); $i++) {