Lumen Artisan command throws "Error: Call to a member function assertExitCode() on int" while testing - laravel

my code is as follows:
class DailyUsageCommandTest extends TestCase
{
public function testDailyUsageCommandTest()
{
$this->artisan('daily-usage')->assertExitCode(0);
}
}
But it throws:
1) DailyUsageCommandTest::testDailyUsageCommandTest
Error: Call to a member function assertExitCode() on int

The error is saying that $this->artisan('daily-usage') returns an int (Call to a member function assertExitCode() on int). So you have to store the result and do assertTrue with your value like this:
$result = $this->artisan('daily-usage');
$this->assertTrue($result === 0);

Related

What does the Object of class stdClass could not be converted to int indicate

I did some math operation trying to deduct one variable from another variable but fails to give me a results say 30 - 10 returns an error. If I change ->first('leave_entitlement'); to ->sum('leave_entitlement'); and able to do the deduction. However I am not summing leave_entitlement. How to I do it right? please
Leave Model function
public static function getSumOfLeaveTaken($leave_category_id){
$total_leave_taken = DB::table('leaves')
->where('created_by', \Auth::user()->id)
->where('leave_category_id', $leave_category_id)
->sum('num_days');
return $total_leave_taken ;
}
LeaveBalance Model function
public static function getNumOfLeaveEntitlment(){
$leaveEntitlement = DB::table('salary_level_user')
->where('user_id', \Auth::user()->id)->first('leave_entitlement');
return $leaveEntitlement;
}
Inside my Leave Controller
$total_leave_taken = Leave::getSumOfLeaveTaken($request->leave_category_id);
$leaveEntitlement = LeaveBalance::getNumOfLeaveEntitlment();
$total_leave_balance = (int)$leaveEntitlement - (int)$total_leave_taken ;
Solved:
Replace ->first with ->value to return a single value and there you can do the deductions
->first('leave_entitlement')
replace with
->value('leave_entitlement')

Using chained partial mocks on an interface used in an artisan command

I'm trying to unittest an artisan command in Laravel 5.3. The command calls on functions in a class that is provided to the command constructor as an interface. That interface calls on functions in another class. This is the general setup.
class MyCommand
{
public function __construct(MyRepositoryInterface $interface)
{
...
$this->interface = $interface;
...
}
public function fire()
{
$this->interface->useTheSecondClass();
}
}
class MyRepository implements MyRepositoryInterface
{
public function __construct(MySecondRepositoryInterface $second)
{
...
$this->second = $second;
...
}
public function useTheSecondClass()
{
$response = $this->second->getSomeValue();
}
}
class MySecondRepository implements MySecondRepositoryInterface
{
/**
* #return Some\External\Client
*/
public function getExternalClient()
{
....
return $external_client;
}
public function getSomeValue()
{
$client = $this->getExternalClient();
$something = $client->doSomething();
Event::fire('some event based on $something`);
return $something;
}
}
I'm attempting to mock the variable returned in MySecondRepository -> getExternalClient() so that I can fake an external API call and use that faked data to test both the MySecondRepository -> getSomeValue() and MyRepository -> useTheSecondClass() functionalities as called from the MyCommand class as such.
public function testMyCommand()
{
$external_client_mock = Mockery::mock("Some\External\Client");
$external_client_mock->shouldReceive("doSomething")
->andReturn("some values");
$second_repository_mock = Mockery::mock("MySecondRepositoryInterface")
->makePartial();
$second_repository_mock->shouldReceive("getExternalClient")
->andReturn($external_client_mock);
$resource = new MyRepository($second_repository_mock);
$this->app->instance("MyRepositoryInterface", $resource);
$class = App::make(MyCommand::class);
$class->fire();
...
}
I have used this exact same mock chain successfully to test the $resource variable directly (e.g., testing $resource->useTheSecondClass() directly, not through MyCommand), but in this situation, while $second_repository_mock->getExternalClient() is mocking correctly, the test is still expecting there to be a mocked expectation for $second_repository_mock->getSomeValue(). Since $second_repository_mock is set to a partial mock, I don't understand why it's still looking for all functions to be mocked.
If I remove the $external_client_mock part and fully mock $second_repository_mock my tests directly related to the artisan command work, however I'd like to test that the event triggered in getSomeValue() is dealt with properly from the artisan command, which I can't do if I can't use the partial mock.
Does anyone have any insight on why this isn't working?
You are trying to mock an interface which makes no sense. Interfaces have no concrete implementations to use. This results in the faulty code. Just mock your repositories and it will work.
EDIT
Just ran the tests with the following refactor and they went to green:
public function testMyCommand() // phpcs:ignore
{
$external_client_mock = \Mockery::mock("App\Client");
$external_client_mock->shouldReceive("doSomething")
->andReturn("some values");
$second_repository_mock = \Mockery::mock("App\MySecondRepository[getExternalClient]")
->shouldIgnoreMissing();
$second_repository_mock->shouldReceive("getExternalClient")
->andReturn($external_client_mock);
$resource = new MyRepository($second_repository_mock);
$this->app->instance("App\MyRepositoryInterface", $resource);
$class = \App::make(\App\MyClass::class);
$class->fire();
}
The only major difference is that you had App\MyCommand in the second to last line and not App\MyClass.

Fatal error: Call to a member function format() on a non-object in C:\xampp\htdocs\esupport\application\controllers\order.php on line 234

I am learning CodeIgniter with the following code:
private function getdbdate($date){
$myDateTime = DateTime::createFromFormat('d/m/Y', $date);
return $myDateTime->format('Y/m/d');
}
private function getviewdate($date){
$myDateTime = DateTime::createFromFormat('Y-m-d', $date);
return $myDateTime->format('d/m/Y');
}
This code gives me a fatal error:
fatal error:-call to a member function format() in C:\xampp\htdocs\esupport\application\controllers\order.php on line 234
Can you help me?
Check if $myDateTime is false, using var_dump:
var_dump($myDateTime);
DateTime::createFromFormat() returns false, in case an error occured.

PHPSpec missing matchers

When I try using PHPSpec matchers like shouldBeEqualTo, shouldBeString etc I get this error and I don't know why.
Call to undefined method Prophecy\Prophecy\MethodProphecy::shouldBeEqualTo()
I have imported ObjectBehavior and my spec is extending it.
My PHPSpec version is 2.2.1.
<?php
namespace Spec\Itmore\Core\Interactor;
use Itmore\Core\Entity\Task;
use Itmore\Core\Entity\TaskDTO;
use Itmore\Core\Entity\TaskList;
use Itmore\Core\Entity\TaskListDTO;
use Itmore\Core\Interactor\AddTask;
use Itmore\Core\Repository\TaskRepositoryInterface;
use Itmore\Core\Repository\TasklistRepositoryInterface;
use Itmore\Core\Repository\UserRepositoryInterface;
use PhpSpec\ObjectBehavior;
use Prophecy;
class SynchronizeTaskSpec extends ObjectBehavior
{
public function let(
TaskRepositoryInterface $taskRepository,
TaskListRepositoryInterface $taskListRepository,
UserRepositoryInterface $userRepository
) {
$this->beConstructedWith($taskRepository, $taskListRepository, $userRepository);
}
public function it_is_initializable()
{
$this->shouldHaveType('Itmore\Core\Interactor\SynchronizeTask');
}
public function it_should_throw_exception_when_task_does_not_gave_google_id(
TaskDTO $taskDTO,
TaskListDTO $taskListDTO
) {
$exception = new \ErrorException('not a google task');
$this->shouldThrow($exception)->duringFromGoogleToApp($taskDTO, $taskListDTO);
}
public function it_should_synchronize_existing_task_from_google_to_app(
TaskDTO $taskDTO,
TaskListDTO $taskListDTO,
Task $task,
TaskRepositoryInterface $taskRepository
) {
$taskDTO->getGoogleId()->willReturn('taskId');
$taskRepository->findOneByGoogleId('taskId')->willReturn($task);
$taskDTO->getTitle()->willReturn('GoogleTitle');
// $task->getTitle()->shouldBeEqualTo('GoogleTitle');
$taskDTO->getTitle()->willReturn('exampleTitle');
$taskRepository->update()->shouldBeCalled();
$this->fromGoogleToApp($taskDTO, $taskListDTO)->shouldReturnAnInstanceOf('Itmore\Core\Entity\TaskDTO');
}
}
You can only call shouldBeEqualTo on $this->someMethod(), for stubs you need to use willReturn as you are stubbing their behaviour, not asserting it.
$this is the SUS not $task.

NHibernate 3.3 Linq calling user defined function with bit parameter and bit result

I'm extending the NHibernate Linq provider and i wish to call a user defined that has both bit parameter[s] and return type.
Here's the SQL user defined function signature:
FUNCTION f_DocumentsFreeTextSearch
(
#docId int,
#searchString varchar(8000),
#searchTitle bit
)
RETURNS bit
Here's the "fake" extension method used for Linq usage:
public static class DialectExtensions
{
public static bool FreeText(this Document doc, string searchString, bool searchTitle)
{
return false;
}
}
Here's my LinqToHqlGeneratorsRegistry
public sealed class ExtendedLinqToHqlGeneratorsRegistry : DefaultLinqToHqlGeneratorsRegistry
{
public ExtendedLinqToHqlGeneratorsRegistry()
{
DialectExtensions.FreeText(null, null, true)),
new FreeTextGenerator());
}
}
And here's my generator:
public class FreeTextGenerator : BaseHqlGeneratorForMethod
{
public FreeTextGenerator()
{
SupportedMethods = new[]
{
ReflectionHelper.GetMethodDefinition(() => DialectExtensions.FreeText(null, null, true))
};
}
#region Overrides of BaseHqlGeneratorForMethod
public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
{
return treeBuilder.MethodCall("dbo.f_documentsfreetextsearch", arguments.Select(a => visitor.Visit(a).AsExpression()).ToArray());
}
#endregion
}
This is the desired usage:
[TestMethod]
public void CanFreeText()
{
var query = SessionHolder.Current.Query<Document>();
var list = query.Where(d => d.FreeText("giorno", true)).ToList();
}
First problem: the above code causes an InvalidCastException:
Test method App.Tests.NHMapping.CanFreeText threw exception:
System.InvalidCastException: Unable to cast object of type
'NHibernate.Hql.Ast.HqlMethodCall' to type
'NHibernate.Hql.Ast.HqlBooleanExpression'.
Solved this way (not elegant but it works):
[TestMethod]
public void CanFreeText()
{
var query = SessionHolder.Current.Query<Document>();
var list = query.Where(d => d.FreeText("giorno", true) == true).ToList();
}
Now NHibernate executes the query, but the generated SQL is wrong:
Test method App.Tests.NHMapping.CanFreeText threw exception:
NHibernate.Exceptions.GenericADOException: could not execute query [
select [...] from dbo.DOCUMENTS document0_ where case when
dbo.f_documentsfreetextsearch(document0_.IDDOCUMENT, #p0, #p1=1) then
1 else 0 end=#p2 ] Name:p1 - Value:giorno Name:p2 - Value:True
Name:p3 - Value:True [SQL: select [...] from dbo.DOCUMENTS document0_
where case when dbo.f_documentsfreetextsearch(document0_.IDDOCUMENT,
#p0, #p1=1) then 1 else 0 end=#p2] --->
System.Data.SqlClient.SqlException: Incorrect syntax near '='.
Please not that the function call in the generated SQL has #p1=1 as third parameter, and that the WHERE clause is an inline CASE instead of
dbo.f_documentsfreetextsearch(document0_.IDDOCUMENT, #p0, #p1) = 1
as i expected.
If i change in my C# code the bool parameter and return type into Int32, everything just work well (but still not very elegant).
Any idea of how to get desired syntax to work?
Thanks in advance
Claudio
PS: sorry for lots of code and errors' text :P
seems you hit the same bug NH-2839 as i did when using usertype for boolean property. not much you can do about it now until this is fixed.

Resources