write phpunit test function for a service class - phpunit

Hi guys i am trying to create a phpunit test for below function.
/**
* Get file size
*
* #param string $filePath
* #return int
*/
public function getFileSize(string $filePath): int
{
if (!file_exists($filePath)) {
return 0;
}
return filesize($filePath);
}
So far i have tried like this
/**
* Test get file size with invalid data
*/
public function testGetFileSizeWithValidData()
{
$filePath = 'rgreherher';
$service = new Tickets_Service_ContactMomentVehicle();
$result = $service->getFileSize($filePath);
$this->assertSame($result, $filePath);
}
So when i run in my terminal i am getting error as
<string:rgreherher> does not match expected type "integer".
Can anyone help me what mistake i have done.
Thanks in advance.

The error is telling you exactly what is going on, you are comparing an integer ($result) to a string ($filePath).
If I understand your test case correctly, you should replace $filePath with $filePath's size instead.
public function testGetFileSizeWithValidData()
{
$filePath = 'rgreherher';
$filePathSize = 55; // actual file size of $filePath
$service = new Tickets_Service_ContactMomentVehicle();
$result = $service->getFileSize($filePath);
$this->assertSame($result, $filePathSize);
}

In your test you assume that the file exists, but if not you must remember that php function filesize (which is in your function getFileSize) returns false and generates an E_WARNING if there is no file.

Related

Slim log writer with sqlite

I have configured slim to write logs to log files as the standard way. But this is not effective when we want to search large and all the logs at a given time. So I want to write those logs to a separate sqlite DB.
My question is how can I set the log writer to write the messages (as done in the Zend framework) ?
P S: I know that I can create a PDO object and use the queries. But I don't want to change the existing code. Just prefer to set the writer and let the framework do the job for me.
I managed to do this as follows,
Create the sqlite connection
$sqlite = new PDO('sqlite:./logs/log.db');
Create my own LogWritter similar to the framework
<?php
/**
* Description of LogWritter
*
* #author Ruwantha.Lankathilaka
*/
class LogWritter {
protected $sqliteConnection;
public function __construct($connection) {
$this->sqliteConnection = $connection;
}
/**
* Write function will bypass the slim default LogWriter and will return
* last inserted log id which could be used as a reference
*
* #param type $object will get the error message
* #param type $level will get the error levels of \Slim\Log
* #return mix if successfully logged will return the last insert id, else
* will return false
*/
public function write($object,$level) {
//Determine label
$label = 'DEBUG';
$message = (string) $object;
switch ($level) {
case \Slim\Log::FATAL:
$label = 'FATAL';
break;
case \Slim\Log::ERROR:
$label = 'ERROR';
break;
case \Slim\Log::WARN:
$label = 'WARN';
break;
case \Slim\Log::INFO:
$label = 'INFO';
break;
}
$sqliteQuery = "INSERT INTO logs (lable,message) VALUES (:lable,:message)";
$statement = $this->sqliteConnection->prepare($sqliteQuery);
$result = $statement->execute(array(':lable'=>$label,':message'=>$message));
if(!empty($result)){
return $this->sqliteConnection->lastInsertId();
}else{
return false;
}
}
}
Add the LogWritter to the index
Add the LogWritter to the Slim app
$app = new \Slim\Slim(array(
'log.writer' => $logWriter,
'log.enabled' => true,
'log.level' => \Slim\Log::DEBUG,
'debug' => true
));
now you can get the log from app
$retult = $app->log->error('test error');
$result will have the inserted log id false if the log failed
Hope this will help someone in future.

Drupal Object of class stdClass could not be converted to int

Hi I have the following drupal module
/**
* Implementation of hook_menu_alter().
*
* #param array $items
* Menu items keyed by path.
*/
function ajax_privacy_menu_alter(&$items) {
$items['node/%']['access callback'] = 'check_access';
$items['node/%']['access arguments'] = array(1);
}
function check_access($node_id)
{
if($node_id!=29)
return TRUE;
else
return FALSE;
}
If i type node/29 it returns access denied message as expected
but for other nodes ( eg: node/24 ) I get the following error
Notice: Object of class stdClass could not be converted to int in
check_access() (line 19 of
/home/pagergbr/public_html/pagerail/sites/all/modules/ajax_privacy/ajax_privacy.module).
and all the nodes in my site show up along with node/24. Please help
Your access callback gets $node object as an argument, try this:
function check_access($node) {
if ($node->nid != 29) {
...
}
}

Get new value of entity field after Doctrine flush

I'm trying to resize an image after persisting an entity with Doctrine. In my Entity code, I'm setting a field to a specific value before the flush and the update :
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->getFile()) {
// do whatever you want to generate a unique name
$filename = sha1(uniqid(mt_rand(), true));
$this->image = $filename.'.png';
}
}
So the image field is supposed to be updated.
Then in my controller, I'd like to do my resize job:
if ($form->isValid())
{
$em->persist($activite);
$em->flush();
//resize the image
$img_path = $activite->getImage();
resizeImage($img_path);
}
However, at this point in the code, the value of $activite->image is still null. How can I get the new value?
(Everything is saved well in the database.)
The EntityManager has a refresh() method to update your entity with the latest values from database.
$em->refresh($entity);
I found my error.
Actually, I was following this tutorial: http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html
and at some point they give this code to set the file:
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
// check if we have an old image path
if (isset($this->path)) {
// store the old name to delete after the update
$this->temp = $this->path;
$this->path = null;
} else {
$this->path = 'initial';
}
}
And then after the upload, in the first version (with the random filename), they do :
$this->file = null;
But then in the second version, this code is replace by:
$this->setFile(null);
My problem is that I've tried the two versions to finally come back to the first. However, I forgot to change the line to set the file to null and so everytime my path field was reset to null.
Sorry for this absurdity and thanks for your help.

Symfony PunkAveFileUploaderBundle > imagename before handleFileUpload

The Symfony2 PunkAve FileUpload Bundle works, but because of the returns inside the UploadHandler of BlueImp, it is not possible to get the filename.
<?php
/**
*
* #Route("/upload")
* #Template()
*/
public function uploadAction(Request $request)
{
$editId = $this->getRequest()->get('editId');
if (!preg_match('/^\d+$/', $editId))
{
throw new Exception("Bad edit id");
}
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('Foobar:Foobar')->find($editId);
$destinationFolder = 'test';
$fileUploader = $this->get('punk_ave.file_uploader');
$imageName = $fileUploader->handleFileUpload(array('folder' => $destinationFolder ));
$imageEntity = new \Foobar\Entity\Image();
$imageEntity->setImage($imageName);
$imageEntity->setFolder($destinationFolder);
$em->persist($media);
$em->flush();
return true;
}
The example above uploads the image.
The variable $imageName triggers the fileUploadHandler. There is somewhere a return, why it doesn't go the the next lines where it should save the imagename.
How can I still get it working in Symfony? To save the filename in the Entity after he handled the upload?
As they said in documentation: handleFileUpload DOES NOT RETURN as the response is generated in native PHP by BlueImp's UploadHandler class. handleFileUpload has exit(0); at the end so when you call it then entire process stops there. If you want to save files to database you should do it in action which handles request (from documentation's example it will be editAction) and there, again as documentation said, use getFiles to get the list of filenames and mirror that in your database as you see fit.

Help me write a PHPUnit Test for the following method

public function getAvailableVideosByRfid($rfid, $count=200) {
$query="SELECT id FROM sometable WHERE rfid='$rfid'";
$result = mysql_query($query);
$count2 = mysql_num_rows($result);
if ($count2){ //this rfid has been claimed
return 0;
}
My assertions are :
1). $rfid is a string 5 characters long
2). I am getting a valid result set
Thank You
Please assume that I have the following Unit Test code:
class videoSharingTest extends PHPUnit_Framework_TestCase {
/**
* #var videoSharing
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp() {
$this->object = new videoSharing;
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown() {
}
public function testGetAllVideosByRfid() {
******What should I put here*****
}
You need to decentralize your database, typically with a Database abstraction layer which you would mock out. Thus adding a ->setDatabase(), etc. on the object that has the method you are using. Then inside your setUp() { ... } you would set the Database object to a mock:
$this->object->setDatabase($mockDb);
Then you would change
$result = mysql_query($query);
$count2 = mysql_num_rows($result);
to use some form of PDO - so that you could call setDatabase() with a PDO Sql Lite. For example:
setUp() { $this->object->setDatabase($mockDb); }
testFunction() {
$rfid = 'the rfid to use in the test';
//make sure no videos exist yet
$this->assertEquals(0, count($this->object->getAvailableVideosByRfid($rfid, ..);
//you may want to assert that it returns a null/false/empty array/etc.
$db = $this->object->getDatabase();
$records = array(... some data ...);
$db->insert($records); //psuedo code
$vids = $this->object->getAvailableVideosByRfid($rfid, ..); //however you map
$this->assertEquals(count($records), count(vids));
foreach($vids as $video) {
//here you would map the $video to the corresponidng $record to make sure all
vital data was stored and retrieved from the method.
}
}
Typically this would all be done in PDO Sqlite so that no true database would be made/created just for the unit test & that it would live and die with the test, and any developer anywhere could use it with no configuration needed.

Resources