php-mock / php-mock-mockery Goto Github PK
View Code? Open in Web Editor NEWMock non deterministic built-in PHP functions (e.g. time() or rand()) with Mockery.
License: Do What The F*ck You Want To Public License
Mock non deterministic built-in PHP functions (e.g. time() or rand()) with Mockery.
License: Do What The F*ck You Want To Public License
I have the below class to connect to ldap server to check whether the user belongs to a group or not. i want to write unit test for this class. how do i achieve this. how to mock the ldap php native functions. can some one please help me with a bit of sample code.
<?php
namespace ABC\Admin\Login;
use Doctrine\ORM\EntityManagerInterface;
/**
* Class Authenticate AD Login
* @package Adp\Admin\Login
*/
class LdapAuthentication
{
/**
* @var string host
*/
private $ldapHost;
/**
* @var string Admin
*/
private $ldapDomain;
/**
* @var string DN
*/
private $baseDn;
/**
* @var EntityManagerInterface
*/
private $entityManager;
public function validateUser($user, $password)
{
$ad = ldap_connect("$this->ldapHost") or die('Could not connect to LDAP server.');
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ad, LDAP_OPT_REFERRALS, 0);
if (!ldap_bind($ad, "{$user}@{$this->ldapDomain}", $password)) {
return false;
}
$userDn = $this->getDN($ad, $user, $this->baseDn);
return $this->checkGroupEx($ad, $userDn, $groups);
ldap_unbind($ad);
}
/**
* @param $ad
* @param $samAccountName
* @param $baseDn
* @return string
*/
private function getDN($ad, $samAccountName, $baseDn)
{
$attributes = array('dn');
$result = ldap_search(
$ad,
$baseDn,
"(samaccountname={$samAccountName})",
$attributes
);
if ($result === false) {
return '';
}
$entries = ldap_get_entries($ad, $result);
if ($entries['count'] > 0) {
return $entries[0]['dn'];
}
return '';
}
/**
* @param $ad
* @param $userDn
* @param $groups
* @param $roles
* @return bool
*/
private function checkGroupEx($ad, $userDn, $groups)
{
$attributes = array('cn','memberof', 'mail');
$result = ldap_read($ad, $userDn, '(objectclass=*)', $attributes);
if ($result === false) {
return false;
};
$entries = ldap_get_entries($ad, $result);
$response = array();
$name = explode(',', $entries[0]['cn'][0]);
$response['firstName'] = $name[0];
$response['lastName'] = $name[1];
$response['email'] = $entries[0]['mail'][0];
if ($entries['count'] <= 0) {
return false;
};
if (empty($entries[0]['memberof'])) {
return false;
}
for ($i = 0; $i < $entries[0]['memberof']['count']; $i++) {
$groupName = explode(',', $entries[0]['memberof'][$i]);
$pos = array_search(strtolower(substr($groupName[0], 3)), $groups);
if (!empty($pos)) {
return $response;
}
}
return false;
}
/**
* @return string
*/
public function getBaseDn()
{
return $this->baseDn;
}
/**
* @param string $baseDn
*/
public function setBaseDn($baseDn)
{
$this->baseDn = $baseDn;
}
/**
* @return string
*/
public function getLdapDomain()
{
return $this->ldapDomain;
}
/**
* @param string $ldapDomain
*/
public function setLdapDomain($ldapDomain)
{
$this->ldapDomain = $ldapDomain;
}
/**
* @return string
*/
public function getLdapHost()
{
return $this->ldapHost;
}
/**
* @param string $ldapHost
*/
public function setLdapHost($ldapHost)
{
$this->ldapHost = $ldapHost;
}
Mockery 1.0 was released a week ago. It would be nice to get support for it.
php-mock-mockery only supports php-mock 1.x, so after installing php-mock 2.0 the following errors occur in composer:
Problem 1
- php-mock/php-mock-integration 1.0.0 requires php-mock/php-mock ^1 -> satisfiable by php-mock/php-mock[1.0.0, 1.0.1] but these conflict with your requirements or minimum-stability.
- php-mock/php-mock-mockery 1.2.0 requires php-mock/php-mock-integration ^1 -> satisfiable by php-mock/php-mock-integration[1.0.0].
- Installation request for php-mock/php-mock-mockery ^1.2 -> satisfiable by php-mock/php-mock-mockery[1.2.0].
I suspect this is probably just an oversight in composer.json, or is there a specific reason why php-mock-mockery would not work with php-mock 2.0? I posted the issue here although the problematic package is actually php-mock-integration, but I suspect nobody installs that package specifically.
This package has a requirement of mockery/mockery
with version ^0.8
. Can this be updated to use the latest version of mockery?
Some code has been omitted. Please let me know if you need clarification.
namespace edu\wisc\doit\lists\wisclist;
class WiscList_DB
{
public function execute($sth, $select = true)
{
$r = oci_execute($sth);
if ($r === false) {
$e = oci_error($sth);
throw new DbQueryException($e[static::MESSAGE]);
}
$output = array();
if ($select === true) {
oci_fetch_all($sth, $output);
}
return $output;
}
}
class WiscList_DBTest extends \PHPUnit_Framework_TestCase
{
public function testExecuteReturnsDataWhenSelectTrue()
{
PHPMockery::mock(__NAMESPACE__, 'oci_execute')->with(anything())->andReturn(true)->once();
PHPMockery::mock(__NAMESPACE__, 'oci_fetch_all')->with(
anything(),
\Mockery::on(function (array &$output) {
$output = array('ID' => array(1));
return true;
})
)->once();
$data = static::getWiscListDbWithMockConfig()->execute(null, true);
$this->assertEquals(array('ID' => array(1)), $data);
}
private static function getWiscListDbWithMockConfig()
{
return new WiscList_DB(static::getMockConfig());
}
}
PHPUnit 4.8.13 by Sebastian Bergmann and contributors.
Runtime: PHP 5.6.15 with Xdebug 2.3.3
Configuration: /Users/ahoffmann/IdeaProjects/wisclist-admin/phpunit.xml
F
Time: 119 ms, Memory: 7.75Mb
There was 1 failure:
1) edu\wisc\doit\lists\wisclist\WiscList_DBTest::testExecuteReturnsDataWhenSelectTrue
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
- 'ID' => Array (...)
)
/Users/ahoffmann/IdeaProjects/wisclist-admin/tests/WiscList_DBTest.php:168
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
The goal is to mock the oci_fetch_all method, which takes an array by reference and fills it with the data that was fetched. I am using Mockery::on()
to preserve pass-by-reference behavior. I have successfully done this in the past with vanilla Mockery. However, when using php-mock's integration with Mockery, the behavior is not preserved.
$output
variable is modified in Mockery::on(), but is reset back to the original argument sometime after the Mockery::on() method returns.This library is not compatible with a latest php-mock/php-mock.
There doesn't seem to be able simple way to set up expectations for multiple function calls.
I've ended up doing this as a workaround, but its ugly:
$mockFetchBody = PHPMockery::mock("Namespace", "imap_fetchbody");
$mockFetchBody
->with('someparams')
->andReturn('response');
$mockFetchBody
->getMock()
->shouldReceive(\phpmock\integration\MockDelegateFunctionBuilder::METHOD)
->with('nextparams')
->andReturn('response2');
Is it possible to use the mocked json_decode for unit testing SomeClass::someMethod?
Where in someMethod() contains json_decode?
test Method:
PHPMockery::mock(NAMESPACE, "json_decode")
->andReturn("test");
$classMock = new SomeClass();
$actual = $classMock->someMethod();
$this->assertEquals("test", $actual);
SomeClass::someMethod:
// codes here
$var = json_decode($str);
// codes here
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.