Upgrade 1-11.38

This commit is contained in:
xesmyd
2026-03-30 14:10:30 +02:00
parent f2a7e6d1fc
commit ac648ef29d
24665 changed files with 69682 additions and 2205004 deletions
@@ -13,39 +13,36 @@ namespace Symfony\Component\Security\Core\Tests\Authentication;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\Security\Core\Event\AuthenticationEvent;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
use Symfony\Component\Security\Core\Exception\ProviderNotFoundException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\ProviderNotFoundException;
class AuthenticationProviderManagerTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testAuthenticateWithoutProviders()
{
new AuthenticationProviderManager(array());
$this->expectException('InvalidArgumentException');
new AuthenticationProviderManager([]);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testAuthenticateWithProvidersWithIncorrectInterface()
{
new AuthenticationProviderManager(array(
$this->expectException('InvalidArgumentException');
(new AuthenticationProviderManager([
new \stdClass(),
));
]))->authenticate($this->getMockBuilder(TokenInterface::class)->getMock());
}
public function testAuthenticateWhenNoProviderSupportsToken()
{
$manager = new AuthenticationProviderManager(array(
$manager = new AuthenticationProviderManager([
$this->getAuthenticationProvider(false),
));
]);
try {
$manager->authenticate($token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
@@ -57,9 +54,15 @@ class AuthenticationProviderManagerTest extends TestCase
public function testAuthenticateWhenProviderReturnsAccountStatusException()
{
$manager = new AuthenticationProviderManager(array(
$secondAuthenticationProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface')->getMock();
$manager = new AuthenticationProviderManager([
$this->getAuthenticationProvider(true, null, 'Symfony\Component\Security\Core\Exception\AccountStatusException'),
));
$secondAuthenticationProvider,
]);
// AccountStatusException stops authentication
$secondAuthenticationProvider->expects($this->never())->method('supports');
try {
$manager->authenticate($token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
@@ -71,9 +74,9 @@ class AuthenticationProviderManagerTest extends TestCase
public function testAuthenticateWhenProviderReturnsAuthenticationException()
{
$manager = new AuthenticationProviderManager(array(
$manager = new AuthenticationProviderManager([
$this->getAuthenticationProvider(true, null, 'Symfony\Component\Security\Core\Exception\AuthenticationException'),
));
]);
try {
$manager->authenticate($token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
@@ -85,10 +88,10 @@ class AuthenticationProviderManagerTest extends TestCase
public function testAuthenticateWhenOneReturnsAuthenticationExceptionButNotAll()
{
$manager = new AuthenticationProviderManager(array(
$manager = new AuthenticationProviderManager([
$this->getAuthenticationProvider(true, null, 'Symfony\Component\Security\Core\Exception\AuthenticationException'),
$this->getAuthenticationProvider(true, $expected = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()),
));
]);
$token = $manager->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertSame($expected, $token);
@@ -101,10 +104,10 @@ class AuthenticationProviderManagerTest extends TestCase
->expects($this->never())
->method('supports')
;
$manager = new AuthenticationProviderManager(array(
$manager = new AuthenticationProviderManager([
$this->getAuthenticationProvider(true, $expected = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()),
$second,
));
]);
$token = $manager->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertSame($expected, $token);
@@ -112,16 +115,16 @@ class AuthenticationProviderManagerTest extends TestCase
public function testEraseCredentialFlag()
{
$manager = new AuthenticationProviderManager(array(
$manager = new AuthenticationProviderManager([
$this->getAuthenticationProvider(true, $token = new UsernamePasswordToken('foo', 'bar', 'key')),
));
]);
$token = $manager->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertEquals('', $token->getCredentials());
$manager = new AuthenticationProviderManager(array(
$manager = new AuthenticationProviderManager([
$this->getAuthenticationProvider(true, $token = new UsernamePasswordToken('foo', 'bar', 'key')),
), false);
], false);
$token = $manager->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertEquals('bar', $token->getCredentials());
@@ -140,7 +143,7 @@ class AuthenticationProviderManagerTest extends TestCase
->method('dispatch')
->with(AuthenticationEvents::AUTHENTICATION_FAILURE, $this->equalTo(new AuthenticationFailureEvent($token, $exception)));
$manager = new AuthenticationProviderManager(array($provider));
$manager = new AuthenticationProviderManager([$provider]);
$manager->setEventDispatcher($dispatcher);
try {
@@ -165,7 +168,7 @@ class AuthenticationProviderManagerTest extends TestCase
->method('dispatch')
->with(AuthenticationEvents::AUTHENTICATION_SUCCESS, $this->equalTo(new AuthenticationEvent($token)));
$manager = new AuthenticationProviderManager(array($provider));
$manager = new AuthenticationProviderManager([$provider]);
$manager->setEventDispatcher($dispatcher);
$this->assertSame($token, $manager->authenticate($token));
@@ -176,18 +179,18 @@ class AuthenticationProviderManagerTest extends TestCase
$provider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface')->getMock();
$provider->expects($this->once())
->method('supports')
->will($this->returnValue($supports))
->willReturn($supports)
;
if (null !== $token) {
$provider->expects($this->once())
->method('authenticate')
->will($this->returnValue($token))
->willReturn($token)
;
} elseif (null !== $exception) {
$provider->expects($this->once())
->method('authenticate')
->will($this->throwException($this->getMockBuilder($exception)->setMethods(null)->getMock()))
->willThrowException($this->getMockBuilder($exception)->setMethods(null)->getMock())
;
}
@@ -53,12 +53,12 @@ class AuthenticationTrustResolverTest extends TestCase
protected function getAnonymousToken()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')->setConstructorArgs(array('', ''))->getMock();
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')->setConstructorArgs(['', ''])->getMock();
}
protected function getRememberMeToken()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken')->setMethods(array('setPersistent'))->disableOriginalConstructor()->getMock();
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken')->setMethods(['setPersistent'])->disableOriginalConstructor()->getMock();
}
protected function getResolver()
@@ -26,16 +26,16 @@ class AnonymousAuthenticationProviderTest extends TestCase
public function testAuthenticateWhenTokenIsNotSupported()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationException');
$this->expectExceptionMessage('The token is not supported by this authentication provider.');
$provider = $this->getProvider('foo');
$this->assertNull($provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
$provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testAuthenticateWhenSecretIsNotValid()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$provider = $this->getProvider('foo');
$provider->authenticate($this->getSupportedToken('bar'));
@@ -51,10 +51,10 @@ class AnonymousAuthenticationProviderTest extends TestCase
protected function getSupportedToken($secret)
{
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')->setMethods(array('getSecret'))->disableOriginalConstructor()->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')->setMethods(['getSecret'])->disableOriginalConstructor()->getMock();
$token->expects($this->any())
->method('getSecret')
->will($this->returnValue($secret))
->willReturn($secret)
;
return $token;
@@ -12,17 +12,19 @@
namespace Symfony\Component\Security\Core\Tests\Authentication\Provider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder;
use Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider;
use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\User;
class DaoAuthenticationProviderTest extends TestCase
{
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationServiceException
* @group legacy
*/
public function testRetrieveUserWhenProviderDoesNotReturnAnUserInterface()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationServiceException');
$provider = $this->getProvider('fabien');
$method = new \ReflectionMethod($provider, 'retrieveUser');
$method->setAccessible(true);
@@ -30,15 +32,13 @@ class DaoAuthenticationProviderTest extends TestCase
$method->invoke($provider, 'fabien', $this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testRetrieveUserWhenUsernameIsNotFound()
{
$this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException');
$userProvider = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface')->getMock();
$userProvider->expects($this->once())
->method('loadUserByUsername')
->will($this->throwException(new UsernameNotFoundException()))
->willThrowException(new UsernameNotFoundException())
;
$provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface')->getMock(), 'key', $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface')->getMock());
@@ -48,15 +48,13 @@ class DaoAuthenticationProviderTest extends TestCase
$method->invoke($provider, 'fabien', $this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationServiceException
*/
public function testRetrieveUserWhenAnExceptionOccurs()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationServiceException');
$userProvider = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface')->getMock();
$userProvider->expects($this->once())
->method('loadUserByUsername')
->will($this->throwException(new \RuntimeException()))
->willThrowException(new \RuntimeException())
;
$provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface')->getMock(), 'key', $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface')->getMock());
@@ -77,7 +75,7 @@ class DaoAuthenticationProviderTest extends TestCase
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getUser')
->will($this->returnValue($user))
->willReturn($user)
;
$provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface')->getMock(), 'key', $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface')->getMock());
@@ -95,7 +93,7 @@ class DaoAuthenticationProviderTest extends TestCase
$userProvider = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface')->getMock();
$userProvider->expects($this->once())
->method('loadUserByUsername')
->will($this->returnValue($user))
->willReturn($user)
;
$provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface')->getMock(), 'key', $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface')->getMock());
@@ -105,11 +103,9 @@ class DaoAuthenticationProviderTest extends TestCase
$this->assertSame($user, $method->invoke($provider, 'fabien', $this->getSupportedToken()));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testCheckAuthenticationWhenCredentialsAreEmpty()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$encoder = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface')->getMock();
$encoder
->expects($this->never())
@@ -124,7 +120,7 @@ class DaoAuthenticationProviderTest extends TestCase
$token
->expects($this->once())
->method('getCredentials')
->will($this->returnValue(''))
->willReturn('')
;
$method->invoke(
@@ -140,7 +136,7 @@ class DaoAuthenticationProviderTest extends TestCase
$encoder
->expects($this->once())
->method('isPasswordValid')
->will($this->returnValue(true))
->willReturn(true)
;
$provider = $this->getProvider(null, null, $encoder);
@@ -151,25 +147,23 @@ class DaoAuthenticationProviderTest extends TestCase
$token
->expects($this->once())
->method('getCredentials')
->will($this->returnValue('0'))
->willReturn('0')
;
$method->invoke(
$provider,
$this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock(),
new User('username', 'password'),
$token
);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testCheckAuthenticationWhenCredentialsAreNotValid()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$encoder = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface')->getMock();
$encoder->expects($this->once())
->method('isPasswordValid')
->will($this->returnValue(false))
->willReturn(false)
;
$provider = $this->getProvider(null, null, $encoder);
@@ -179,32 +173,30 @@ class DaoAuthenticationProviderTest extends TestCase
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getCredentials')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$method->invoke($provider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock(), $token);
$method->invoke($provider, new User('username', 'password'), $token);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testCheckAuthenticationDoesNotReauthenticateWhenPasswordHasChanged()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$user = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock();
$user->expects($this->once())
->method('getPassword')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getUser')
->will($this->returnValue($user));
->willReturn($user);
$dbUser = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock();
$dbUser->expects($this->once())
->method('getPassword')
->will($this->returnValue('newFoo'))
->willReturn('newFoo')
;
$provider = $this->getProvider();
@@ -218,18 +210,18 @@ class DaoAuthenticationProviderTest extends TestCase
$user = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock();
$user->expects($this->once())
->method('getPassword')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getUser')
->will($this->returnValue($user));
->willReturn($user);
$dbUser = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock();
$dbUser->expects($this->once())
->method('getPassword')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$provider = $this->getProvider();
@@ -243,7 +235,7 @@ class DaoAuthenticationProviderTest extends TestCase
$encoder = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface')->getMock();
$encoder->expects($this->once())
->method('isPasswordValid')
->will($this->returnValue(true))
->willReturn(true)
;
$provider = $this->getProvider(null, null, $encoder);
@@ -253,19 +245,19 @@ class DaoAuthenticationProviderTest extends TestCase
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getCredentials')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$method->invoke($provider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock(), $token);
$method->invoke($provider, new User('username', 'password'), $token);
}
protected function getSupportedToken()
{
$mock = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Authentication\\Token\\UsernamePasswordToken')->setMethods(array('getCredentials', 'getUser', 'getProviderKey'))->disableOriginalConstructor()->getMock();
$mock = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Authentication\\Token\\UsernamePasswordToken')->setMethods(['getCredentials', 'getUser', 'getProviderKey'])->disableOriginalConstructor()->getMock();
$mock
->expects($this->any())
->method('getProviderKey')
->will($this->returnValue('key'))
->willReturn('key')
;
return $mock;
@@ -277,7 +269,7 @@ class DaoAuthenticationProviderTest extends TestCase
if (null !== $user) {
$userProvider->expects($this->once())
->method('loadUserByUsername')
->will($this->returnValue($user))
->willReturn($user)
;
}
@@ -293,7 +285,7 @@ class DaoAuthenticationProviderTest extends TestCase
$encoderFactory
->expects($this->any())
->method('getEncoder')
->will($this->returnValue($passwordEncoder))
->willReturn($passwordEncoder)
;
return new DaoAuthenticationProvider($userProvider, $userChecker, 'key', $encoderFactory);
@@ -12,11 +12,14 @@
namespace Symfony\Component\Security\Core\Tests\Authentication\Provider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Ldap\Adapter\CollectionInterface;
use Symfony\Component\Ldap\Adapter\QueryInterface;
use Symfony\Component\Ldap\Entry;
use Symfony\Component\Ldap\Exception\ConnectionException;
use Symfony\Component\Ldap\LdapInterface;
use Symfony\Component\Security\Core\Authentication\Provider\LdapBindAuthenticationProvider;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Ldap\Exception\ConnectionException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
@@ -25,12 +28,10 @@ use Symfony\Component\Security\Core\User\UserProviderInterface;
*/
class LdapBindAuthenticationProviderTest extends TestCase
{
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
* @expectedExceptionMessage The presented password must not be empty.
*/
public function testEmptyPasswordShouldThrowAnException()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$this->expectExceptionMessage('The presented password must not be empty.');
$userProvider = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock();
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
@@ -42,18 +43,31 @@ class LdapBindAuthenticationProviderTest extends TestCase
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', '', 'key'));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
* @expectedExceptionMessage The presented password is invalid.
*/
public function testNullPasswordShouldThrowAnException()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$this->expectExceptionMessage('The presented password must not be empty.');
$userProvider = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock();
$ldap = $this->getMockBuilder('Symfony\Component\Ldap\LdapInterface')->getMock();
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap);
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', null, 'key'));
}
public function testBindFailureShouldThrowAnException()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$this->expectExceptionMessage('The presented password is invalid.');
$userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock();
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$ldap
->expects($this->once())
->method('bind')
->will($this->throwException(new ConnectionException()))
->willThrowException(new ConnectionException())
;
$userChecker = $this->getMockBuilder(UserCheckerInterface::class)->getMock();
@@ -82,4 +96,71 @@ class LdapBindAuthenticationProviderTest extends TestCase
$reflection->invoke($provider, 'foo', new UsernamePasswordToken('foo', 'bar', 'key'));
}
public function testQueryForDn()
{
$userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock();
$collection = new \ArrayIterator([new Entry('')]);
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->willReturn($collection)
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$ldap
->expects($this->once())
->method('escape')
->with('foo', '')
->willReturn('foo')
;
$ldap
->expects($this->once())
->method('query')
->with('{username}', 'foobar')
->willReturn($query)
;
$userChecker = $this->getMockBuilder(UserCheckerInterface::class)->getMock();
$provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap);
$provider->setQueryString('{username}bar');
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', 'bar', 'key'));
}
public function testEmptyQueryResultShouldThrowAnException()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$this->expectExceptionMessage('The presented username is invalid.');
$userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock();
$collection = $this->getMockBuilder(CollectionInterface::class)->getMock();
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->willReturn($collection)
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$ldap
->expects($this->once())
->method('query')
->willReturn($query)
;
$userChecker = $this->getMockBuilder(UserCheckerInterface::class)->getMock();
$provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap);
$provider->setQueryString('{username}bar');
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', 'bar', 'key'));
}
}
@@ -31,23 +31,23 @@ class PreAuthenticatedAuthenticationProviderTest extends TestCase
$token
->expects($this->once())
->method('getProviderKey')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$this->assertFalse($provider->supports($token));
}
public function testAuthenticateWhenTokenIsNotSupported()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationException');
$this->expectExceptionMessage('The token is not supported by this authentication provider.');
$provider = $this->getProvider();
$this->assertNull($provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
$provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testAuthenticateWhenNoUserIsSet()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$provider = $this->getProvider();
$provider->authenticate($this->getSupportedToken(''));
}
@@ -58,7 +58,7 @@ class PreAuthenticatedAuthenticationProviderTest extends TestCase
$user
->expects($this->once())
->method('getRoles')
->will($this->returnValue(array()))
->willReturn([])
;
$provider = $this->getProvider($user);
@@ -66,22 +66,20 @@ class PreAuthenticatedAuthenticationProviderTest extends TestCase
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken', $token);
$this->assertEquals('pass', $token->getCredentials());
$this->assertEquals('key', $token->getProviderKey());
$this->assertEquals(array(), $token->getRoles());
$this->assertEquals(array('foo' => 'bar'), $token->getAttributes(), '->authenticate() copies token attributes');
$this->assertEquals([], $token->getRoles());
$this->assertEquals(['foo' => 'bar'], $token->getAttributes(), '->authenticate() copies token attributes');
$this->assertSame($user, $token->getUser());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\LockedException
*/
public function testAuthenticateWhenUserCheckerThrowsException()
{
$this->expectException('Symfony\Component\Security\Core\Exception\LockedException');
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$userChecker->expects($this->once())
->method('checkPostAuth')
->will($this->throwException(new LockedException()))
->willThrowException(new LockedException())
;
$provider = $this->getProvider($user, $userChecker);
@@ -91,27 +89,27 @@ class PreAuthenticatedAuthenticationProviderTest extends TestCase
protected function getSupportedToken($user = false, $credentials = false)
{
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken')->setMethods(array('getUser', 'getCredentials', 'getProviderKey'))->disableOriginalConstructor()->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken')->setMethods(['getUser', 'getCredentials', 'getProviderKey'])->disableOriginalConstructor()->getMock();
if (false !== $user) {
$token->expects($this->once())
->method('getUser')
->will($this->returnValue($user))
->willReturn($user)
;
}
if (false !== $credentials) {
$token->expects($this->once())
->method('getCredentials')
->will($this->returnValue($credentials))
->willReturn($credentials)
;
}
$token
->expects($this->any())
->method('getProviderKey')
->will($this->returnValue('key'))
->willReturn('key')
;
$token->setAttributes(array('foo' => 'bar'));
$token->setAttributes(['foo' => 'bar']);
return $token;
}
@@ -122,7 +120,7 @@ class PreAuthenticatedAuthenticationProviderTest extends TestCase
if (null !== $user) {
$userProvider->expects($this->once())
->method('loadUserByUsername')
->will($this->returnValue($user))
->willReturn($user)
;
}
@@ -13,8 +13,10 @@ namespace Symfony\Component\Security\Core\Tests\Authentication\Provider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Provider\RememberMeAuthenticationProvider;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\User;
class RememberMeAuthenticationProviderTest extends TestCase
{
@@ -24,36 +26,46 @@ class RememberMeAuthenticationProviderTest extends TestCase
$this->assertTrue($provider->supports($this->getSupportedToken()));
$this->assertFalse($provider->supports($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
$this->assertFalse($provider->supports($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken')->disableOriginalConstructor()->getMock()));
}
public function testAuthenticateWhenTokenIsNotSupported()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationException');
$this->expectExceptionMessage('The token is not supported by this authentication provider.');
$provider = $this->getProvider();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$this->assertNull($provider->authenticate($token));
$provider->authenticate($token);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testAuthenticateWhenSecretsDoNotMatch()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$provider = $this->getProvider(null, 'secret1');
$token = $this->getSupportedToken(null, 'secret2');
$provider->authenticate($token);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\DisabledException
*/
public function testAuthenticateThrowsOnNonUserInterfaceInstance()
{
$this->expectException('Symfony\Component\Security\Core\Exception\LogicException');
$this->expectExceptionMessage('Method "Symfony\Component\Security\Core\Authentication\Token\RememberMeToken::getUser()" must return a "Symfony\Component\Security\Core\User\UserInterface" instance, "string" returned.');
$provider = $this->getProvider();
$token = new RememberMeToken(new User('dummyuser', null), 'foo', 'test');
$token->setUser('stringish-user');
$provider->authenticate($token);
}
public function testAuthenticateWhenPreChecksFails()
{
$this->expectException('Symfony\Component\Security\Core\Exception\DisabledException');
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$userChecker->expects($this->once())
->method('checkPreAuth')
->will($this->throwException(new DisabledException()));
->willThrowException(new DisabledException());
$provider = $this->getProvider($userChecker);
@@ -65,7 +77,7 @@ class RememberMeAuthenticationProviderTest extends TestCase
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->exactly(2))
->method('getRoles')
->will($this->returnValue(array('ROLE_FOO')));
->willReturn(['ROLE_FOO']);
$provider = $this->getProvider();
@@ -74,7 +86,7 @@ class RememberMeAuthenticationProviderTest extends TestCase
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', $authToken);
$this->assertSame($user, $authToken->getUser());
$this->assertEquals(array(new Role('ROLE_FOO')), $authToken->getRoles());
$this->assertEquals([new Role('ROLE_FOO')], $authToken->getRoles());
$this->assertEquals('', $authToken->getCredentials());
}
@@ -85,14 +97,14 @@ class RememberMeAuthenticationProviderTest extends TestCase
$user
->expects($this->any())
->method('getRoles')
->will($this->returnValue(array()));
->willReturn([]);
}
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken')->setMethods(array('getProviderKey'))->setConstructorArgs(array($user, 'foo', $secret))->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken')->setMethods(['getProviderKey'])->setConstructorArgs([$user, 'foo', $secret])->getMock();
$token
->expects($this->once())
->method('getProviderKey')
->will($this->returnValue('foo'));
->willReturn('foo');
return $token;
}
@@ -18,6 +18,7 @@ use Symfony\Component\Security\Core\Exception\CredentialsExpiredException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Core\User\UserInterface;
class UserAuthenticationProviderTest extends TestCase
{
@@ -31,126 +32,135 @@ class UserAuthenticationProviderTest extends TestCase
public function testAuthenticateWhenTokenIsNotSupported()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationException');
$this->expectExceptionMessage('The token is not supported by this authentication provider.');
$provider = $this->getProvider();
$this->assertNull($provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
$provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testAuthenticateWhenUsernameIsNotFound()
{
$this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException');
$provider = $this->getProvider(false, false);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->throwException(new UsernameNotFoundException()))
->willThrowException(new UsernameNotFoundException())
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testAuthenticateWhenUsernameIsNotFoundAndHideIsTrue()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$provider = $this->getProvider(false, true);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->throwException(new UsernameNotFoundException()))
->willThrowException(new UsernameNotFoundException())
;
$provider->authenticate($this->getSupportedToken());
}
public function testAuthenticateWhenCredentialsAreInvalidAndHideIsTrue()
{
$provider = $this->getProvider();
$provider->expects($this->once())
->method('retrieveUser')
->willReturn($this->createMock(UserInterface::class))
;
$provider->expects($this->once())
->method('checkAuthentication')
->willThrowException(new BadCredentialsException())
;
$this->expectException(BadCredentialsException::class);
$this->expectExceptionMessage('Bad credentials.');
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationServiceException
* @group legacy
*/
public function testAuthenticateWhenProviderDoesNotReturnAnUserInterface()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationServiceException');
$provider = $this->getProvider(false, true);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue(null))
->willReturn(null)
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\CredentialsExpiredException
*/
public function testAuthenticateWhenPreChecksFails()
{
$this->expectException(BadCredentialsException::class);
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$userChecker->expects($this->once())
->method('checkPreAuth')
->will($this->throwException(new CredentialsExpiredException()))
->willThrowException(new CredentialsExpiredException())
;
$provider = $this->getProvider($userChecker);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock()))
->willReturn($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock())
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AccountExpiredException
*/
public function testAuthenticateWhenPostChecksFails()
{
$this->expectException(BadCredentialsException::class);
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$userChecker->expects($this->once())
->method('checkPostAuth')
->will($this->throwException(new AccountExpiredException()))
->willThrowException(new AccountExpiredException())
;
$provider = $this->getProvider($userChecker);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock()))
->willReturn($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock())
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
* @expectedExceptionMessage Bad credentials
*/
public function testAuthenticateWhenPostCheckAuthenticationFails()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$this->expectExceptionMessage('Bad credentials.');
$provider = $this->getProvider();
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock()))
->willReturn($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock())
;
$provider->expects($this->once())
->method('checkAuthentication')
->will($this->throwException(new BadCredentialsException()))
->willThrowException(new CredentialsExpiredException())
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
* @expectedExceptionMessage Foo
*/
public function testAuthenticateWhenPostCheckAuthenticationFailsWithHideFalse()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$this->expectExceptionMessage('Foo');
$provider = $this->getProvider(false, false);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock()))
->willReturn($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock())
;
$provider->expects($this->once())
->method('checkAuthentication')
->will($this->throwException(new BadCredentialsException('Foo')))
->willThrowException(new BadCredentialsException('Foo'))
;
$provider->authenticate($this->getSupportedToken());
@@ -161,33 +171,33 @@ class UserAuthenticationProviderTest extends TestCase
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->once())
->method('getRoles')
->will($this->returnValue(array('ROLE_FOO')))
->willReturn(['ROLE_FOO'])
;
$provider = $this->getProvider();
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($user))
->willReturn($user)
;
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getCredentials')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$token->expects($this->once())
->method('getRoles')
->will($this->returnValue(array()))
->willReturn([])
;
$authToken = $provider->authenticate($token);
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $authToken);
$this->assertSame($user, $authToken->getUser());
$this->assertEquals(array(new Role('ROLE_FOO')), $authToken->getRoles());
$this->assertEquals([new Role('ROLE_FOO')], $authToken->getRoles());
$this->assertEquals('foo', $authToken->getCredentials());
$this->assertEquals(array('foo' => 'bar'), $authToken->getAttributes(), '->authenticate() copies token attributes');
$this->assertEquals(['foo' => 'bar'], $authToken->getAttributes(), '->authenticate() copies token attributes');
}
public function testAuthenticateWithPreservingRoleSwitchUserRole()
@@ -195,47 +205,47 @@ class UserAuthenticationProviderTest extends TestCase
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->once())
->method('getRoles')
->will($this->returnValue(array('ROLE_FOO')))
->willReturn(['ROLE_FOO'])
;
$provider = $this->getProvider();
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($user))
->willReturn($user)
;
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getCredentials')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$switchUserRole = new SwitchUserRole('foo', $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$token->expects($this->once())
->method('getRoles')
->will($this->returnValue(array($switchUserRole)))
->willReturn([$switchUserRole])
;
$authToken = $provider->authenticate($token);
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $authToken);
$this->assertSame($user, $authToken->getUser());
$this->assertContains(new Role('ROLE_FOO'), $authToken->getRoles(), '', false, false);
$this->assertContains($switchUserRole, $authToken->getRoles(), '', false, false);
$this->assertContainsEquals(new Role('ROLE_FOO'), $authToken->getRoles());
$this->assertContainsEquals($switchUserRole, $authToken->getRoles());
$this->assertEquals('foo', $authToken->getCredentials());
$this->assertEquals(array('foo' => 'bar'), $authToken->getAttributes(), '->authenticate() copies token attributes');
$this->assertEquals(['foo' => 'bar'], $authToken->getAttributes(), '->authenticate() copies token attributes');
}
protected function getSupportedToken()
{
$mock = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken')->setMethods(array('getCredentials', 'getProviderKey', 'getRoles'))->disableOriginalConstructor()->getMock();
$mock = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken')->setMethods(['getCredentials', 'getProviderKey', 'getRoles'])->disableOriginalConstructor()->getMock();
$mock
->expects($this->any())
->method('getProviderKey')
->will($this->returnValue('key'))
->willReturn('key')
;
$mock->setAttributes(array('foo' => 'bar'));
$mock->setAttributes(['foo' => 'bar']);
return $mock;
}
@@ -246,6 +256,6 @@ class UserAuthenticationProviderTest extends TestCase
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
}
return $this->getMockForAbstractClass('Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider', array($userChecker, 'key', $hide));
return $this->getMockForAbstractClass('Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider', [$userChecker, 'key', $hide]);
}
}
@@ -12,8 +12,8 @@
namespace Symfony\Component\Security\Core\Tests\Authentication\RememberMe;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
use Symfony\Component\Security\Core\Authentication\RememberMe\InMemoryTokenProvider;
use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
class InMemoryTokenProviderTest extends TestCase
{
@@ -27,11 +27,9 @@ class InMemoryTokenProviderTest extends TestCase
$this->assertSame($provider->loadTokenBySeries('foo'), $token);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\TokenNotFoundException
*/
public function testLoadTokenBySeriesThrowsNotFoundException()
{
$this->expectException('Symfony\Component\Security\Core\Exception\TokenNotFoundException');
$provider = new InMemoryTokenProvider();
$provider->loadTokenBySeries('foo');
}
@@ -49,11 +47,9 @@ class InMemoryTokenProviderTest extends TestCase
$this->assertSame($token->getLastUsed(), $lastUsed);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\TokenNotFoundException
*/
public function testDeleteToken()
{
$this->expectException('Symfony\Component\Security\Core\Exception\TokenNotFoundException');
$provider = new InMemoryTokenProvider();
$token = new PersistentToken('foo', 'foo', 'foo', 'foo', new \DateTime());
@@ -36,16 +36,21 @@ class ConcreteToken extends AbstractToken
{
private $credentials = 'credentials_value';
public function __construct($user, array $roles = array())
public function __construct($user, array $roles = [])
{
parent::__construct($roles);
$this->setUser($user);
}
/**
* {@inheritdoc}
*/
public function serialize()
{
return serialize(array($this->credentials, parent::serialize()));
$serialized = [$this->credentials, parent::serialize(true)];
return $this->doSerialize($serialized, \func_num_args() ? func_get_arg(0) : null);
}
public function unserialize($serialized)
@@ -64,7 +69,7 @@ class AbstractTokenTest extends TestCase
{
public function testGetUsername()
{
$token = $this->getToken(array('ROLE_FOO'));
$token = $this->getToken(['ROLE_FOO']);
$token->setUser('fabien');
$this->assertEquals('fabien', $token->getUsername());
@@ -72,14 +77,14 @@ class AbstractTokenTest extends TestCase
$this->assertEquals('fabien', $token->getUsername());
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->once())->method('getUsername')->will($this->returnValue('fabien'));
$user->expects($this->once())->method('getUsername')->willReturn('fabien');
$token->setUser($user);
$this->assertEquals('fabien', $token->getUsername());
}
public function testEraseCredentials()
{
$token = $this->getToken(array('ROLE_FOO'));
$token = $this->getToken(['ROLE_FOO']);
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->once())->method('eraseCredentials');
@@ -90,8 +95,8 @@ class AbstractTokenTest extends TestCase
public function testSerialize()
{
$token = $this->getToken(array('ROLE_FOO', new Role('ROLE_BAR')));
$token->setAttributes(array('foo' => 'bar'));
$token = $this->getToken(['ROLE_FOO', new Role('ROLE_BAR')]);
$token->setAttributes(['foo' => 'bar']);
$uToken = unserialize(serialize($token));
@@ -101,7 +106,7 @@ class AbstractTokenTest extends TestCase
public function testSerializeWithRoleObjects()
{
$user = new User('name', 'password', array(new Role('ROLE_FOO'), new Role('ROLE_BAR')));
$user = new User('name', 'password', [new Role('ROLE_FOO'), new Role('ROLE_BAR')]);
$token = new ConcreteToken($user, $user->getRoles());
$serialized = serialize($token);
@@ -115,9 +120,9 @@ class AbstractTokenTest extends TestCase
public function testSerializeParent()
{
$user = new TestUser('fabien');
$token = new ConcreteToken($user, array('ROLE_FOO'));
$token = new ConcreteToken($user, ['ROLE_FOO']);
$parentToken = new ConcreteToken($user, array(new SwitchUserRole('ROLE_PREVIOUS', $token)));
$parentToken = new ConcreteToken($user, [new SwitchUserRole('ROLE_PREVIOUS', $token)]);
$uToken = unserialize(serialize($parentToken));
$this->assertEquals(
@@ -128,14 +133,14 @@ class AbstractTokenTest extends TestCase
public function testConstructor()
{
$token = $this->getToken(array('ROLE_FOO'));
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$token = $this->getToken(['ROLE_FOO']);
$this->assertEquals([new Role('ROLE_FOO')], $token->getRoles());
$token = $this->getToken(array(new Role('ROLE_FOO')));
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$token = $this->getToken([new Role('ROLE_FOO')]);
$this->assertEquals([new Role('ROLE_FOO')], $token->getRoles());
$token = $this->getToken(array(new Role('ROLE_FOO'), 'ROLE_BAR'));
$this->assertEquals(array(new Role('ROLE_FOO'), new Role('ROLE_BAR')), $token->getRoles());
$token = $this->getToken([new Role('ROLE_FOO'), 'ROLE_BAR']);
$this->assertEquals([new Role('ROLE_FOO'), new Role('ROLE_BAR')], $token->getRoles());
}
public function testAuthenticatedFlag()
@@ -152,7 +157,7 @@ class AbstractTokenTest extends TestCase
public function testAttributes()
{
$attributes = array('foo' => 'bar');
$attributes = ['foo' => 'bar'];
$token = $this->getToken();
$token->setAttributes($attributes);
@@ -187,12 +192,12 @@ class AbstractTokenTest extends TestCase
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$advancedUser = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
return array(
array($advancedUser),
array($user),
array(new TestUser('foo')),
array('foo'),
);
return [
[$advancedUser],
[$user],
[new TestUser('foo')],
['foo'],
];
}
/**
@@ -216,50 +221,50 @@ class AbstractTokenTest extends TestCase
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$advancedUser = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
return array(
array(
return [
[
'foo', 'bar',
),
array(
],
[
'foo', new TestUser('bar'),
),
array(
],
[
'foo', $user,
),
array(
],
[
'foo', $advancedUser,
),
array(
],
[
$user, 'foo',
),
array(
],
[
$advancedUser, 'foo',
),
array(
],
[
$user, new TestUser('foo'),
),
array(
],
[
$advancedUser, new TestUser('foo'),
),
array(
],
[
new TestUser('foo'), new TestUser('bar'),
),
array(
],
[
new TestUser('foo'), 'bar',
),
array(
],
[
new TestUser('foo'), $user,
),
array(
],
[
new TestUser('foo'), $advancedUser,
),
array(
],
[
$user, $advancedUser,
),
array(
],
[
$advancedUser, $user,
),
);
],
];
}
/**
@@ -278,8 +283,8 @@ class AbstractTokenTest extends TestCase
$this->assertTrue($token->isAuthenticated());
}
protected function getToken(array $roles = array())
protected function getToken(array $roles = [])
{
return $this->getMockForAbstractClass('Symfony\Component\Security\Core\Authentication\Token\AbstractToken', array($roles));
return $this->getMockForAbstractClass('Symfony\Component\Security\Core\Authentication\Token\AbstractToken', [$roles]);
}
}
@@ -22,8 +22,8 @@ class AnonymousTokenTest extends TestCase
$token = new AnonymousToken('foo', 'bar');
$this->assertTrue($token->isAuthenticated());
$token = new AnonymousToken('foo', 'bar', array('ROLE_FOO'));
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$token = new AnonymousToken('foo', 'bar', ['ROLE_FOO']);
$this->assertEquals([new Role('ROLE_FOO')], $token->getRoles());
}
public function testGetKey()
@@ -22,9 +22,9 @@ class PreAuthenticatedTokenTest extends TestCase
$token = new PreAuthenticatedToken('foo', 'bar', 'key');
$this->assertFalse($token->isAuthenticated());
$token = new PreAuthenticatedToken('foo', 'bar', 'key', array('ROLE_FOO'));
$token = new PreAuthenticatedToken('foo', 'bar', 'key', ['ROLE_FOO']);
$this->assertTrue($token->isAuthenticated());
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$this->assertEquals([new Role('ROLE_FOO')], $token->getRoles());
$this->assertEquals('key', $token->getProviderKey());
}
@@ -24,16 +24,14 @@ class RememberMeTokenTest extends TestCase
$this->assertEquals('fookey', $token->getProviderKey());
$this->assertEquals('foo', $token->getSecret());
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$this->assertEquals([new Role('ROLE_FOO')], $token->getRoles());
$this->assertSame($user, $token->getUser());
$this->assertTrue($token->isAuthenticated());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testConstructorSecretCannotBeNull()
{
$this->expectException('InvalidArgumentException');
new RememberMeToken(
$this->getUser(),
null,
@@ -41,11 +39,9 @@ class RememberMeTokenTest extends TestCase
);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testConstructorSecretCannotBeEmptyString()
{
$this->expectException('InvalidArgumentException');
new RememberMeToken(
$this->getUser(),
'',
@@ -53,13 +49,13 @@ class RememberMeTokenTest extends TestCase
);
}
protected function getUser($roles = array('ROLE_FOO'))
protected function getUser($roles = ['ROLE_FOO'])
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user
->expects($this->once())
->method('getRoles')
->will($this->returnValue($roles))
->willReturn($roles)
;
return $user;
@@ -22,17 +22,15 @@ class UsernamePasswordTokenTest extends TestCase
$token = new UsernamePasswordToken('foo', 'bar', 'key');
$this->assertFalse($token->isAuthenticated());
$token = new UsernamePasswordToken('foo', 'bar', 'key', array('ROLE_FOO'));
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$token = new UsernamePasswordToken('foo', 'bar', 'key', ['ROLE_FOO']);
$this->assertEquals([new Role('ROLE_FOO')], $token->getRoles());
$this->assertTrue($token->isAuthenticated());
$this->assertEquals('key', $token->getProviderKey());
}
/**
* @expectedException \LogicException
*/
public function testSetAuthenticatedToTrue()
{
$this->expectException('LogicException');
$token = new UsernamePasswordToken('foo', 'bar', 'key');
$token->setAuthenticated(true);
}
@@ -53,7 +51,7 @@ class UsernamePasswordTokenTest extends TestCase
public function testToString()
{
$token = new UsernamePasswordToken('foo', '', 'foo', array('A', 'B'));
$token = new UsernamePasswordToken('foo', '', 'foo', ['A', 'B']);
$this->assertEquals('UsernamePasswordToken(user="foo", authenticated=true, roles="A, B")', (string) $token);
}
}
@@ -12,17 +12,18 @@
namespace Symfony\Component\Security\Core\Tests\Authorization;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManager;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Exception\LogicException;
use Symfony\Component\Security\Core\Tests\Authorization\Stub\VoterWithoutInterface;
class AccessDecisionManagerTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testSetUnsupportedStrategy()
{
new AccessDecisionManager(array($this->getVoter(VoterInterface::ACCESS_GRANTED)), 'fooBar');
$this->expectException('InvalidArgumentException');
new AccessDecisionManager([$this->getVoter(VoterInterface::ACCESS_GRANTED)], 'fooBar');
}
/**
@@ -33,7 +34,7 @@ class AccessDecisionManagerTest extends TestCase
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$manager = new AccessDecisionManager($voters, $strategy, $allowIfAllAbstainDecisions, $allowIfEqualGrantedDeniedDecisions);
$this->assertSame($expected, $manager->decide($token, array('ROLE_FOO')));
$this->assertSame($expected, $manager->decide($token, ['ROLE_FOO']));
}
/**
@@ -41,27 +42,27 @@ class AccessDecisionManagerTest extends TestCase
*/
public function testStrategiesWith2Roles($token, $strategy, $voter, $expected)
{
$manager = new AccessDecisionManager(array($voter), $strategy);
$manager = new AccessDecisionManager([$voter], $strategy);
$this->assertSame($expected, $manager->decide($token, array('ROLE_FOO', 'ROLE_BAR')));
$this->assertSame($expected, $manager->decide($token, ['ROLE_FOO', 'ROLE_BAR']));
}
public function getStrategiesWith2RolesTests()
{
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
return array(
array($token, 'affirmative', $this->getVoter(VoterInterface::ACCESS_DENIED), false),
array($token, 'affirmative', $this->getVoter(VoterInterface::ACCESS_GRANTED), true),
return [
[$token, 'affirmative', $this->getVoter(VoterInterface::ACCESS_DENIED), false],
[$token, 'affirmative', $this->getVoter(VoterInterface::ACCESS_GRANTED), true],
array($token, 'consensus', $this->getVoter(VoterInterface::ACCESS_DENIED), false),
array($token, 'consensus', $this->getVoter(VoterInterface::ACCESS_GRANTED), true),
[$token, 'consensus', $this->getVoter(VoterInterface::ACCESS_DENIED), false],
[$token, 'consensus', $this->getVoter(VoterInterface::ACCESS_GRANTED), true],
array($token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_DENIED, VoterInterface::ACCESS_DENIED), false),
array($token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_DENIED, VoterInterface::ACCESS_GRANTED), false),
array($token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_GRANTED, VoterInterface::ACCESS_DENIED), false),
array($token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_GRANTED, VoterInterface::ACCESS_GRANTED), true),
);
[$token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_DENIED, VoterInterface::ACCESS_DENIED), false],
[$token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_DENIED, VoterInterface::ACCESS_GRANTED), false],
[$token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_GRANTED, VoterInterface::ACCESS_DENIED), false],
[$token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_GRANTED, VoterInterface::ACCESS_GRANTED), true],
];
}
protected function getVoterFor2Roles($token, $vote1, $vote2)
@@ -69,10 +70,10 @@ class AccessDecisionManagerTest extends TestCase
$voter = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\Voter\VoterInterface')->getMock();
$voter->expects($this->any())
->method('vote')
->will($this->returnValueMap(array(
array($token, null, array('ROLE_FOO'), $vote1),
array($token, null, array('ROLE_BAR'), $vote2),
)))
->willReturnMap([
[$token, null, ['ROLE_FOO'], $vote1],
[$token, null, ['ROLE_BAR'], $vote2],
])
;
return $voter;
@@ -80,42 +81,42 @@ class AccessDecisionManagerTest extends TestCase
public function getStrategyTests()
{
return array(
return [
// affirmative
array(AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(1, 0, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(1, 2, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(0, 1, 0), false, true, false),
array(AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(0, 0, 1), false, true, false),
array(AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(0, 0, 1), true, true, true),
[AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(1, 0, 0), false, true, true],
[AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(1, 2, 0), false, true, true],
[AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(0, 1, 0), false, true, false],
[AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(0, 0, 1), false, true, false],
[AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(0, 0, 1), true, true, true],
// consensus
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(1, 0, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(1, 2, 0), false, true, false),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 1, 0), false, true, true),
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(1, 0, 0), false, true, true],
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(1, 2, 0), false, true, false],
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 1, 0), false, true, true],
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(0, 0, 1), false, true, false),
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(0, 0, 1), false, true, false],
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(0, 0, 1), true, true, true),
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(0, 0, 1), true, true, true],
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 1), false, true, true),
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 0), false, true, true],
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 1), false, true, true],
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 0), false, false, false),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 1), false, false, false),
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 0), false, false, false],
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 1), false, false, false],
// unanimous
array(AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(1, 0, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(1, 0, 1), false, true, true),
array(AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(1, 1, 0), false, true, false),
[AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(1, 0, 0), false, true, true],
[AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(1, 0, 1), false, true, true],
[AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(1, 1, 0), false, true, false],
array(AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(0, 0, 2), false, true, false),
array(AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(0, 0, 2), true, true, true),
);
[AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(0, 0, 2), false, true, false],
[AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(0, 0, 2), true, true, true],
];
}
protected function getVoters($grants, $denies, $abstains)
{
$voters = array();
$voters = [];
for ($i = 0; $i < $grants; ++$i) {
$voters[] = $this->getVoter(VoterInterface::ACCESS_GRANTED);
}
@@ -134,8 +135,34 @@ class AccessDecisionManagerTest extends TestCase
$voter = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\Voter\VoterInterface')->getMock();
$voter->expects($this->any())
->method('vote')
->will($this->returnValue($vote));
->willReturn($vote);
return $voter;
}
public function testVotingWrongTypeNoVoteMethod()
{
$exception = LogicException::class;
$message = sprintf('"stdClass" should implement the "%s" interface when used as voter.', VoterInterface::class);
$this->expectException($exception);
$this->expectExceptionMessage($message);
$adm = new AccessDecisionManager([new \stdClass()]);
$token = $this->getMockBuilder(TokenInterface::class)->getMock();
$adm->decide($token, ['TEST']);
}
/**
* @group legacy
* @expectedDeprecation Calling vote() on an voter without Symfony\Component\Security\Core\Authorization\Voter\VoterInterface is deprecated as of 3.4 and will be removed in 4.0. Implement the Symfony\Component\Security\Core\Authorization\Voter\VoterInterface on your voter.
*/
public function testVotingWrongTypeWithVote()
{
$adm = new AccessDecisionManager([new VoterWithoutInterface()]);
$token = $this->getMockBuilder(TokenInterface::class)->getMock();
$adm->decide($token, ['TEST']);
}
}
@@ -46,7 +46,7 @@ class AuthorizationCheckerTest extends TestCase
->expects($this->once())
->method('authenticate')
->with($this->equalTo($token))
->will($this->returnValue($newToken));
->willReturn($newToken);
// default with() isn't a strict check
$tokenComparison = function ($value) use ($newToken) {
@@ -58,19 +58,17 @@ class AuthorizationCheckerTest extends TestCase
->expects($this->once())
->method('decide')
->with($this->callback($tokenComparison))
->will($this->returnValue(true));
->willReturn(true);
// first run the token has not been re-authenticated yet, after isGranted is called, it should be equal
$this->assertFalse($newToken === $this->tokenStorage->getToken());
$this->assertNotSame($newToken, $this->tokenStorage->getToken());
$this->assertTrue($this->authorizationChecker->isGranted('foo'));
$this->assertTrue($newToken === $this->tokenStorage->getToken());
$this->assertSame($newToken, $this->tokenStorage->getToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
*/
public function testVoteWithoutAuthenticationToken()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException');
$this->authorizationChecker->isGranted('ROLE_FOO');
}
@@ -83,18 +81,18 @@ class AuthorizationCheckerTest extends TestCase
$token
->expects($this->once())
->method('isAuthenticated')
->will($this->returnValue(true));
->willReturn(true);
$this->accessDecisionManager
->expects($this->once())
->method('decide')
->will($this->returnValue($decide));
->willReturn($decide);
$this->tokenStorage->setToken($token);
$this->assertTrue($decide === $this->authorizationChecker->isGranted('ROLE_FOO'));
$this->assertSame($decide, $this->authorizationChecker->isGranted('ROLE_FOO'));
}
public function isGrantedProvider()
{
return array(array(true), array(false));
return [[true], [false]];
}
}
@@ -1,44 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core\Tests\Authorization;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManager;
use Symfony\Component\Security\Core\Authorization\DebugAccessDecisionManager;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class DebugAccessDecisionManagerTest extends TestCase
{
/**
* @dataProvider provideObjectsAndLogs
*/
public function testDecideLog($expectedLog, $object)
{
$adm = new DebugAccessDecisionManager(new AccessDecisionManager());
$adm->decide($this->getMockBuilder(TokenInterface::class)->getMock(), array('ATTRIBUTE_1'), $object);
$this->assertSame($expectedLog, $adm->getDecisionLog());
}
public function provideObjectsAndLogs()
{
$object = new \stdClass();
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => null, 'result' => false)), null);
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => true, 'result' => false)), true);
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => 'jolie string', 'result' => false)), 'jolie string');
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => 12345, 'result' => false)), 12345);
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => $x = fopen(__FILE__, 'r'), 'result' => false)), $x);
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => $x = array(), 'result' => false)), $x);
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => $object, 'result' => false)), $object);
}
}
@@ -12,11 +12,11 @@
namespace Symfony\Component\Security\Core\Tests\Authorization;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage;
use Symfony\Component\Security\Core\User\User;
class ExpressionLanguageTest extends TestCase
@@ -24,14 +24,14 @@ class ExpressionLanguageTest extends TestCase
/**
* @dataProvider provider
*/
public function testIsAuthenticated($token, $expression, $result, array $roles = array())
public function testIsAuthenticated($token, $expression, $result, array $roles = [])
{
$anonymousTokenClass = 'Symfony\\Component\\Security\\Core\\Authentication\\Token\\AnonymousToken';
$rememberMeTokenClass = 'Symfony\\Component\\Security\\Core\\Authentication\\Token\\RememberMeToken';
$expressionLanguage = new ExpressionLanguage();
$trustResolver = new AuthenticationTrustResolver($anonymousTokenClass, $rememberMeTokenClass);
$context = array();
$context = [];
$context['trust_resolver'] = $trustResolver;
$context['token'] = $token;
$context['roles'] = $roles;
@@ -41,7 +41,7 @@ class ExpressionLanguageTest extends TestCase
public function provider()
{
$roles = array('ROLE_USER', 'ROLE_ADMIN');
$roles = ['ROLE_USER', 'ROLE_ADMIN'];
$user = new User('username', 'password', $roles);
$noToken = null;
@@ -49,32 +49,32 @@ class ExpressionLanguageTest extends TestCase
$rememberMeToken = new RememberMeToken($user, 'providerkey', 'firewall');
$usernamePasswordToken = new UsernamePasswordToken('username', 'password', 'providerkey', $roles);
return array(
array($noToken, 'is_anonymous()', false),
array($noToken, 'is_authenticated()', false),
array($noToken, 'is_fully_authenticated()', false),
array($noToken, 'is_remember_me()', false),
array($noToken, "has_role('ROLE_USER')", false),
return [
[$noToken, 'is_anonymous()', false],
[$noToken, 'is_authenticated()', false],
[$noToken, 'is_fully_authenticated()', false],
[$noToken, 'is_remember_me()', false],
[$noToken, "has_role('ROLE_USER')", false],
array($anonymousToken, 'is_anonymous()', true),
array($anonymousToken, 'is_authenticated()', false),
array($anonymousToken, 'is_fully_authenticated()', false),
array($anonymousToken, 'is_remember_me()', false),
array($anonymousToken, "has_role('ROLE_USER')", false),
[$anonymousToken, 'is_anonymous()', true],
[$anonymousToken, 'is_authenticated()', false],
[$anonymousToken, 'is_fully_authenticated()', false],
[$anonymousToken, 'is_remember_me()', false],
[$anonymousToken, "has_role('ROLE_USER')", false],
array($rememberMeToken, 'is_anonymous()', false),
array($rememberMeToken, 'is_authenticated()', true),
array($rememberMeToken, 'is_fully_authenticated()', false),
array($rememberMeToken, 'is_remember_me()', true),
array($rememberMeToken, "has_role('ROLE_FOO')", false, $roles),
array($rememberMeToken, "has_role('ROLE_USER')", true, $roles),
[$rememberMeToken, 'is_anonymous()', false],
[$rememberMeToken, 'is_authenticated()', true],
[$rememberMeToken, 'is_fully_authenticated()', false],
[$rememberMeToken, 'is_remember_me()', true],
[$rememberMeToken, "has_role('ROLE_FOO')", false, $roles],
[$rememberMeToken, "has_role('ROLE_USER')", true, $roles],
array($usernamePasswordToken, 'is_anonymous()', false),
array($usernamePasswordToken, 'is_authenticated()', true),
array($usernamePasswordToken, 'is_fully_authenticated()', true),
array($usernamePasswordToken, 'is_remember_me()', false),
array($usernamePasswordToken, "has_role('ROLE_FOO')", false, $roles),
array($usernamePasswordToken, "has_role('ROLE_USER')", true, $roles),
);
[$usernamePasswordToken, 'is_anonymous()', false],
[$usernamePasswordToken, 'is_authenticated()', true],
[$usernamePasswordToken, 'is_fully_authenticated()', true],
[$usernamePasswordToken, 'is_remember_me()', false],
[$usernamePasswordToken, "has_role('ROLE_FOO')", false, $roles],
[$usernamePasswordToken, "has_role('ROLE_USER')", true, $roles],
];
}
}
@@ -30,26 +30,26 @@ class AuthenticatedVoterTest extends TestCase
public function getVoteTests()
{
return array(
array('fully', array(), VoterInterface::ACCESS_ABSTAIN),
array('fully', array('FOO'), VoterInterface::ACCESS_ABSTAIN),
array('remembered', array(), VoterInterface::ACCESS_ABSTAIN),
array('remembered', array('FOO'), VoterInterface::ACCESS_ABSTAIN),
array('anonymously', array(), VoterInterface::ACCESS_ABSTAIN),
array('anonymously', array('FOO'), VoterInterface::ACCESS_ABSTAIN),
return [
['fully', [], VoterInterface::ACCESS_ABSTAIN],
['fully', ['FOO'], VoterInterface::ACCESS_ABSTAIN],
['remembered', [], VoterInterface::ACCESS_ABSTAIN],
['remembered', ['FOO'], VoterInterface::ACCESS_ABSTAIN],
['anonymously', [], VoterInterface::ACCESS_ABSTAIN],
['anonymously', ['FOO'], VoterInterface::ACCESS_ABSTAIN],
array('fully', array('IS_AUTHENTICATED_ANONYMOUSLY'), VoterInterface::ACCESS_GRANTED),
array('remembered', array('IS_AUTHENTICATED_ANONYMOUSLY'), VoterInterface::ACCESS_GRANTED),
array('anonymously', array('IS_AUTHENTICATED_ANONYMOUSLY'), VoterInterface::ACCESS_GRANTED),
['fully', ['IS_AUTHENTICATED_ANONYMOUSLY'], VoterInterface::ACCESS_GRANTED],
['remembered', ['IS_AUTHENTICATED_ANONYMOUSLY'], VoterInterface::ACCESS_GRANTED],
['anonymously', ['IS_AUTHENTICATED_ANONYMOUSLY'], VoterInterface::ACCESS_GRANTED],
array('fully', array('IS_AUTHENTICATED_REMEMBERED'), VoterInterface::ACCESS_GRANTED),
array('remembered', array('IS_AUTHENTICATED_REMEMBERED'), VoterInterface::ACCESS_GRANTED),
array('anonymously', array('IS_AUTHENTICATED_REMEMBERED'), VoterInterface::ACCESS_DENIED),
['fully', ['IS_AUTHENTICATED_REMEMBERED'], VoterInterface::ACCESS_GRANTED],
['remembered', ['IS_AUTHENTICATED_REMEMBERED'], VoterInterface::ACCESS_GRANTED],
['anonymously', ['IS_AUTHENTICATED_REMEMBERED'], VoterInterface::ACCESS_DENIED],
array('fully', array('IS_AUTHENTICATED_FULLY'), VoterInterface::ACCESS_GRANTED),
array('remembered', array('IS_AUTHENTICATED_FULLY'), VoterInterface::ACCESS_DENIED),
array('anonymously', array('IS_AUTHENTICATED_FULLY'), VoterInterface::ACCESS_DENIED),
);
['fully', ['IS_AUTHENTICATED_FULLY'], VoterInterface::ACCESS_GRANTED],
['remembered', ['IS_AUTHENTICATED_FULLY'], VoterInterface::ACCESS_DENIED],
['anonymously', ['IS_AUTHENTICATED_FULLY'], VoterInterface::ACCESS_DENIED],
];
}
protected function getResolver()
@@ -65,9 +65,9 @@ class AuthenticatedVoterTest extends TestCase
if ('fully' === $authenticated) {
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
} elseif ('remembered' === $authenticated) {
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken')->setMethods(array('setPersistent'))->disableOriginalConstructor()->getMock();
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken')->setMethods(['setPersistent'])->disableOriginalConstructor()->getMock();
} else {
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')->setConstructorArgs(array('', ''))->getMock();
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')->setConstructorArgs(['', ''])->getMock();
}
}
}
@@ -30,15 +30,15 @@ class ExpressionVoterTest extends TestCase
public function getVoteTests()
{
return array(
array(array(), array(), VoterInterface::ACCESS_ABSTAIN, false, false),
array(array(), array('FOO'), VoterInterface::ACCESS_ABSTAIN, false, false),
return [
[[], [], VoterInterface::ACCESS_ABSTAIN, false, false],
[[], ['FOO'], VoterInterface::ACCESS_ABSTAIN, false, false],
array(array(), array($this->createExpression()), VoterInterface::ACCESS_DENIED, true, false),
[[], [$this->createExpression()], VoterInterface::ACCESS_DENIED, true, false],
array(array('ROLE_FOO'), array($this->createExpression(), $this->createExpression()), VoterInterface::ACCESS_GRANTED),
array(array('ROLE_BAR', 'ROLE_FOO'), array($this->createExpression()), VoterInterface::ACCESS_GRANTED),
);
[['ROLE_FOO'], [$this->createExpression(), $this->createExpression()], VoterInterface::ACCESS_GRANTED],
[['ROLE_BAR', 'ROLE_FOO'], [$this->createExpression()], VoterInterface::ACCESS_GRANTED],
];
}
protected function getToken(array $roles, $tokenExpectsGetRoles = true)
@@ -51,7 +51,7 @@ class ExpressionVoterTest extends TestCase
if ($tokenExpectsGetRoles) {
$token->expects($this->once())
->method('getRoles')
->will($this->returnValue($roles));
->willReturn($roles);
}
return $token;
@@ -64,7 +64,7 @@ class ExpressionVoterTest extends TestCase
if ($expressionLanguageExpectsEvaluate) {
$mock->expects($this->once())
->method('evaluate')
->will($this->returnValue(true));
->willReturn(true);
}
return $mock;
@@ -22,16 +22,16 @@ class RoleHierarchyVoterTest extends RoleVoterTest
*/
public function testVote($roles, $attributes, $expected)
{
$voter = new RoleHierarchyVoter(new RoleHierarchy(array('ROLE_FOO' => array('ROLE_FOOBAR'))));
$voter = new RoleHierarchyVoter(new RoleHierarchy(['ROLE_FOO' => ['ROLE_FOOBAR']]));
$this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
}
public function getVoteTests()
{
return array_merge(parent::getVoteTests(), array(
array(array('ROLE_FOO'), array('ROLE_FOOBAR'), VoterInterface::ACCESS_GRANTED),
));
return array_merge(parent::getVoteTests(), [
[['ROLE_FOO'], ['ROLE_FOOBAR'], VoterInterface::ACCESS_GRANTED],
]);
}
/**
@@ -39,7 +39,7 @@ class RoleHierarchyVoterTest extends RoleVoterTest
*/
public function testVoteWithEmptyHierarchy($roles, $attributes, $expected)
{
$voter = new RoleHierarchyVoter(new RoleHierarchy(array()));
$voter = new RoleHierarchyVoter(new RoleHierarchy([]));
$this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
}
@@ -30,20 +30,20 @@ class RoleVoterTest extends TestCase
public function getVoteTests()
{
return array(
array(array(), array(), VoterInterface::ACCESS_ABSTAIN),
array(array(), array('FOO'), VoterInterface::ACCESS_ABSTAIN),
array(array(), array('ROLE_FOO'), VoterInterface::ACCESS_DENIED),
array(array('ROLE_FOO'), array('ROLE_FOO'), VoterInterface::ACCESS_GRANTED),
array(array('ROLE_FOO'), array('FOO', 'ROLE_FOO'), VoterInterface::ACCESS_GRANTED),
array(array('ROLE_BAR', 'ROLE_FOO'), array('ROLE_FOO'), VoterInterface::ACCESS_GRANTED),
return [
[[], [], VoterInterface::ACCESS_ABSTAIN],
[[], ['FOO'], VoterInterface::ACCESS_ABSTAIN],
[[], ['ROLE_FOO'], VoterInterface::ACCESS_DENIED],
[['ROLE_FOO'], ['ROLE_FOO'], VoterInterface::ACCESS_GRANTED],
[['ROLE_FOO'], ['FOO', 'ROLE_FOO'], VoterInterface::ACCESS_GRANTED],
[['ROLE_BAR', 'ROLE_FOO'], ['ROLE_FOO'], VoterInterface::ACCESS_GRANTED],
// Test mixed Types
array(array(), array(array()), VoterInterface::ACCESS_ABSTAIN),
array(array(), array(new \stdClass()), VoterInterface::ACCESS_ABSTAIN),
array(array('ROLE_BAR'), array(new Role('ROLE_BAR')), VoterInterface::ACCESS_GRANTED),
array(array('ROLE_BAR'), array(new Role('ROLE_FOO')), VoterInterface::ACCESS_DENIED),
);
[[], [[]], VoterInterface::ACCESS_ABSTAIN],
[[], [new \stdClass()], VoterInterface::ACCESS_ABSTAIN],
[['ROLE_BAR'], [new Role('ROLE_BAR')], VoterInterface::ACCESS_GRANTED],
[['ROLE_BAR'], [new Role('ROLE_FOO')], VoterInterface::ACCESS_DENIED],
];
}
protected function getToken(array $roles)
@@ -54,7 +54,7 @@ class RoleVoterTest extends TestCase
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token->expects($this->once())
->method('getRoles')
->will($this->returnValue($roles));
->willReturn($roles);
return $token;
}
@@ -27,23 +27,23 @@ class VoterTest extends TestCase
public function getTests()
{
return array(
array(array('EDIT'), VoterInterface::ACCESS_GRANTED, new \stdClass(), 'ACCESS_GRANTED if attribute and class are supported and attribute grants access'),
array(array('CREATE'), VoterInterface::ACCESS_DENIED, new \stdClass(), 'ACCESS_DENIED if attribute and class are supported and attribute does not grant access'),
return [
[['EDIT'], VoterInterface::ACCESS_GRANTED, new \stdClass(), 'ACCESS_GRANTED if attribute and class are supported and attribute grants access'],
[['CREATE'], VoterInterface::ACCESS_DENIED, new \stdClass(), 'ACCESS_DENIED if attribute and class are supported and attribute does not grant access'],
array(array('DELETE', 'EDIT'), VoterInterface::ACCESS_GRANTED, new \stdClass(), 'ACCESS_GRANTED if one attribute is supported and grants access'),
array(array('DELETE', 'CREATE'), VoterInterface::ACCESS_DENIED, new \stdClass(), 'ACCESS_DENIED if one attribute is supported and denies access'),
[['DELETE', 'EDIT'], VoterInterface::ACCESS_GRANTED, new \stdClass(), 'ACCESS_GRANTED if one attribute is supported and grants access'],
[['DELETE', 'CREATE'], VoterInterface::ACCESS_DENIED, new \stdClass(), 'ACCESS_DENIED if one attribute is supported and denies access'],
array(array('CREATE', 'EDIT'), VoterInterface::ACCESS_GRANTED, new \stdClass(), 'ACCESS_GRANTED if one attribute grants access'),
[['CREATE', 'EDIT'], VoterInterface::ACCESS_GRANTED, new \stdClass(), 'ACCESS_GRANTED if one attribute grants access'],
array(array('DELETE'), VoterInterface::ACCESS_ABSTAIN, new \stdClass(), 'ACCESS_ABSTAIN if no attribute is supported'),
[['DELETE'], VoterInterface::ACCESS_ABSTAIN, new \stdClass(), 'ACCESS_ABSTAIN if no attribute is supported'],
array(array('EDIT'), VoterInterface::ACCESS_ABSTAIN, $this, 'ACCESS_ABSTAIN if class is not supported'),
[['EDIT'], VoterInterface::ACCESS_ABSTAIN, $this, 'ACCESS_ABSTAIN if class is not supported'],
array(array('EDIT'), VoterInterface::ACCESS_ABSTAIN, null, 'ACCESS_ABSTAIN if object is null'),
[['EDIT'], VoterInterface::ACCESS_ABSTAIN, null, 'ACCESS_ABSTAIN if object is null'],
array(array(), VoterInterface::ACCESS_ABSTAIN, new \stdClass(), 'ACCESS_ABSTAIN if no attributes were provided'),
);
[[], VoterInterface::ACCESS_ABSTAIN, new \stdClass(), 'ACCESS_ABSTAIN if no attributes were provided'],
];
}
/**
@@ -66,6 +66,6 @@ class VoterTest_Voter extends Voter
protected function supports($attribute, $object)
{
return $object instanceof \stdClass && in_array($attribute, array('EDIT', 'CREATE'));
return $object instanceof \stdClass && \in_array($attribute, ['EDIT', 'CREATE']);
}
}
@@ -22,19 +22,15 @@ class BCryptPasswordEncoderTest extends TestCase
const PASSWORD = 'password';
const VALID_COST = '04';
/**
* @expectedException \InvalidArgumentException
*/
public function testCostBelowRange()
{
$this->expectException('InvalidArgumentException');
new BCryptPasswordEncoder(3);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testCostAboveRange()
{
$this->expectException('InvalidArgumentException');
new BCryptPasswordEncoder(32);
}
@@ -49,7 +45,7 @@ class BCryptPasswordEncoderTest extends TestCase
public function validRangeData()
{
$costs = range(4, 31);
array_walk($costs, function (&$cost) { $cost = array($cost); });
array_walk($costs, function (&$cost) { $cost = [$cost]; });
return $costs;
}
@@ -58,7 +54,7 @@ class BCryptPasswordEncoderTest extends TestCase
{
$encoder = new BCryptPasswordEncoder(self::VALID_COST);
$result = $encoder->encodePassword(self::PASSWORD, null);
$this->assertEquals(60, strlen($result));
$this->assertEquals(60, \strlen($result));
}
public function testValidation()
@@ -69,11 +65,9 @@ class BCryptPasswordEncoderTest extends TestCase
$this->assertFalse($encoder->isPasswordValid($result, 'anotherPassword', null));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testEncodePasswordLength()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$encoder = new BCryptPasswordEncoder(self::VALID_COST);
$encoder->encodePassword(str_repeat('a', 73), 'salt');
@@ -35,9 +35,9 @@ class BasePasswordEncoderTest extends TestCase
public function testDemergePasswordAndSalt()
{
$this->assertEquals(array('password', 'salt'), $this->invokeDemergePasswordAndSalt('password{salt}'));
$this->assertEquals(array('password', ''), $this->invokeDemergePasswordAndSalt('password'));
$this->assertEquals(array('', ''), $this->invokeDemergePasswordAndSalt(''));
$this->assertEquals(['password', 'salt'], $this->invokeDemergePasswordAndSalt('password{salt}'));
$this->assertEquals(['password', ''], $this->invokeDemergePasswordAndSalt('password'));
$this->assertEquals(['', ''], $this->invokeDemergePasswordAndSalt(''));
}
public function testMergePasswordAndSalt()
@@ -46,11 +46,9 @@ class BasePasswordEncoderTest extends TestCase
$this->assertEquals('password', $this->invokeMergePasswordAndSalt('password', ''));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testMergePasswordAndSaltWithException()
{
$this->expectException('InvalidArgumentException');
$this->invokeMergePasswordAndSalt('password', '{foo}');
}
@@ -12,9 +12,9 @@
namespace Symfony\Component\Security\Core\Tests\Encoder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Encoder\EncoderAwareInterface;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
@@ -22,10 +22,10 @@ class EncoderFactoryTest extends TestCase
{
public function testGetEncoderWithMessageDigestEncoder()
{
$factory = new EncoderFactory(array('Symfony\Component\Security\Core\User\UserInterface' => array(
$factory = new EncoderFactory(['Symfony\Component\Security\Core\User\UserInterface' => [
'class' => 'Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder',
'arguments' => array('sha512', true, 5),
)));
'arguments' => ['sha512', true, 5],
]]);
$encoder = $factory->getEncoder($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock());
$expectedEncoder = new MessageDigestPasswordEncoder('sha512', true, 5);
@@ -35,9 +35,9 @@ class EncoderFactoryTest extends TestCase
public function testGetEncoderWithService()
{
$factory = new EncoderFactory(array(
$factory = new EncoderFactory([
'Symfony\Component\Security\Core\User\UserInterface' => new MessageDigestPasswordEncoder('sha1'),
));
]);
$encoder = $factory->getEncoder($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock());
$expectedEncoder = new MessageDigestPasswordEncoder('sha1');
@@ -50,9 +50,9 @@ class EncoderFactoryTest extends TestCase
public function testGetEncoderWithClassName()
{
$factory = new EncoderFactory(array(
$factory = new EncoderFactory([
'Symfony\Component\Security\Core\User\UserInterface' => new MessageDigestPasswordEncoder('sha1'),
));
]);
$encoder = $factory->getEncoder('Symfony\Component\Security\Core\Tests\Encoder\SomeChildUser');
$expectedEncoder = new MessageDigestPasswordEncoder('sha1');
@@ -61,9 +61,9 @@ class EncoderFactoryTest extends TestCase
public function testGetEncoderConfiguredForConcreteClassWithService()
{
$factory = new EncoderFactory(array(
$factory = new EncoderFactory([
'Symfony\Component\Security\Core\User\User' => new MessageDigestPasswordEncoder('sha1'),
));
]);
$encoder = $factory->getEncoder(new User('user', 'pass'));
$expectedEncoder = new MessageDigestPasswordEncoder('sha1');
@@ -72,9 +72,9 @@ class EncoderFactoryTest extends TestCase
public function testGetEncoderConfiguredForConcreteClassWithClassName()
{
$factory = new EncoderFactory(array(
$factory = new EncoderFactory([
'Symfony\Component\Security\Core\Tests\Encoder\SomeUser' => new MessageDigestPasswordEncoder('sha1'),
));
]);
$encoder = $factory->getEncoder('Symfony\Component\Security\Core\Tests\Encoder\SomeChildUser');
$expectedEncoder = new MessageDigestPasswordEncoder('sha1');
@@ -83,10 +83,10 @@ class EncoderFactoryTest extends TestCase
public function testGetNamedEncoderForEncoderAware()
{
$factory = new EncoderFactory(array(
$factory = new EncoderFactory([
'Symfony\Component\Security\Core\Tests\Encoder\EncAwareUser' => new MessageDigestPasswordEncoder('sha256'),
'encoder_name' => new MessageDigestPasswordEncoder('sha1'),
));
]);
$encoder = $factory->getEncoder(new EncAwareUser('user', 'pass'));
$expectedEncoder = new MessageDigestPasswordEncoder('sha1');
@@ -95,10 +95,10 @@ class EncoderFactoryTest extends TestCase
public function testGetNullNamedEncoderForEncoderAware()
{
$factory = new EncoderFactory(array(
$factory = new EncoderFactory([
'Symfony\Component\Security\Core\Tests\Encoder\EncAwareUser' => new MessageDigestPasswordEncoder('sha1'),
'encoder_name' => new MessageDigestPasswordEncoder('sha256'),
));
]);
$user = new EncAwareUser('user', 'pass');
$user->encoderName = null;
@@ -107,27 +107,25 @@ class EncoderFactoryTest extends TestCase
$this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));
}
/**
* @expectedException \RuntimeException
*/
public function testGetInvalidNamedEncoderForEncoderAware()
{
$factory = new EncoderFactory(array(
$this->expectException('RuntimeException');
$factory = new EncoderFactory([
'Symfony\Component\Security\Core\Tests\Encoder\EncAwareUser' => new MessageDigestPasswordEncoder('sha1'),
'encoder_name' => new MessageDigestPasswordEncoder('sha256'),
));
]);
$user = new EncAwareUser('user', 'pass');
$user->encoderName = 'invalid_encoder_name';
$encoder = $factory->getEncoder($user);
$factory->getEncoder($user);
}
public function testGetEncoderForEncoderAwareWithClassName()
{
$factory = new EncoderFactory(array(
$factory = new EncoderFactory([
'Symfony\Component\Security\Core\Tests\Encoder\EncAwareUser' => new MessageDigestPasswordEncoder('sha1'),
'encoder_name' => new MessageDigestPasswordEncoder('sha256'),
));
]);
$encoder = $factory->getEncoder('Symfony\Component\Security\Core\Tests\Encoder\EncAwareUser');
$expectedEncoder = new MessageDigestPasswordEncoder('sha1');
@@ -35,20 +35,16 @@ class MessageDigestPasswordEncoderTest extends TestCase
$this->assertSame(hash('sha256', hash('sha256', 'password', true).'password'), $encoder->encodePassword('password', ''));
}
/**
* @expectedException \LogicException
*/
public function testEncodePasswordAlgorithmDoesNotExist()
{
$this->expectException('LogicException');
$encoder = new MessageDigestPasswordEncoder('foobar');
$encoder->encodePassword('password', '');
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testEncodePasswordLength()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$encoder = new MessageDigestPasswordEncoder();
$encoder->encodePassword(str_repeat('a', 5000), 'salt');
@@ -35,20 +35,16 @@ class Pbkdf2PasswordEncoderTest extends TestCase
$this->assertSame('8bc2f9167a81cdcfad1235cd9047f1136271c1f978fcfcb35e22dbeafa4634f6fd2214218ed63ebb', $encoder->encodePassword('password', ''));
}
/**
* @expectedException \LogicException
*/
public function testEncodePasswordAlgorithmDoesNotExist()
{
$this->expectException('LogicException');
$encoder = new Pbkdf2PasswordEncoder('foobar');
$encoder->encodePassword('password', '');
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testEncodePasswordLength()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$encoder = new Pbkdf2PasswordEncoder('foobar');
$encoder->encodePassword(str_repeat('a', 5000), 'salt');
@@ -38,11 +38,9 @@ class PlaintextPasswordEncoderTest extends TestCase
$this->assertSame('foo', $encoder->encodePassword('foo', ''));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testEncodePasswordLength()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$encoder = new PlaintextPasswordEncoder();
$encoder->encodePassword(str_repeat('a', 5000), 'salt');
@@ -21,19 +21,19 @@ class UserPasswordEncoderTest extends TestCase
$userMock = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$userMock->expects($this->any())
->method('getSalt')
->will($this->returnValue('userSalt'));
->willReturn('userSalt');
$mockEncoder = $this->getMockBuilder('Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface')->getMock();
$mockEncoder->expects($this->any())
->method('encodePassword')
->with($this->equalTo('plainPassword'), $this->equalTo('userSalt'))
->will($this->returnValue('encodedPassword'));
->willReturn('encodedPassword');
$mockEncoderFactory = $this->getMockBuilder('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface')->getMock();
$mockEncoderFactory->expects($this->any())
->method('getEncoder')
->with($this->equalTo($userMock))
->will($this->returnValue($mockEncoder));
->willReturn($mockEncoder);
$passwordEncoder = new UserPasswordEncoder($mockEncoderFactory);
@@ -46,22 +46,22 @@ class UserPasswordEncoderTest extends TestCase
$userMock = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$userMock->expects($this->any())
->method('getSalt')
->will($this->returnValue('userSalt'));
->willReturn('userSalt');
$userMock->expects($this->any())
->method('getPassword')
->will($this->returnValue('encodedPassword'));
->willReturn('encodedPassword');
$mockEncoder = $this->getMockBuilder('Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface')->getMock();
$mockEncoder->expects($this->any())
->method('isPasswordValid')
->with($this->equalTo('encodedPassword'), $this->equalTo('plainPassword'), $this->equalTo('userSalt'))
->will($this->returnValue(true));
->willReturn(true);
$mockEncoderFactory = $this->getMockBuilder('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface')->getMock();
$mockEncoderFactory->expects($this->any())
->method('getEncoder')
->with($this->equalTo($userMock))
->will($this->returnValue($mockEncoder));
->willReturn($mockEncoder);
$passwordEncoder = new UserPasswordEncoder($mockEncoderFactory);
@@ -12,16 +12,60 @@
namespace Symfony\Component\Security\Core\Tests\Exception;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
class ChildCustomUserMessageAuthenticationException extends CustomUserMessageAuthenticationException
{
public function serialize()
{
return serialize([$this->childMember, parent::serialize()]);
}
public function unserialize($str)
{
list($this->childMember, $parentData) = unserialize($str);
parent::unserialize($parentData);
}
}
class CustomUserMessageAuthenticationExceptionTest extends TestCase
{
public function testConstructWithSAfeMessage()
{
$e = new CustomUserMessageAuthenticationException('SAFE MESSAGE', array('foo' => true));
$e = new CustomUserMessageAuthenticationException('SAFE MESSAGE', ['foo' => true]);
$this->assertEquals('SAFE MESSAGE', $e->getMessageKey());
$this->assertEquals(array('foo' => true), $e->getMessageData());
$this->assertEquals(['foo' => true], $e->getMessageData());
$this->assertEquals('SAFE MESSAGE', $e->getMessage());
}
public function testSharedSerializedData()
{
$token = new AnonymousToken('foo', 'bar');
$exception = new CustomUserMessageAuthenticationException();
$exception->setToken($token);
$exception->setSafeMessage('message', ['token' => $token]);
$processed = unserialize(serialize($exception));
$this->assertEquals($token, $processed->getToken());
$this->assertEquals($token, $processed->getMessageData()['token']);
$this->assertSame($processed->getToken(), $processed->getMessageData()['token']);
}
public function testSharedSerializedDataFromChild()
{
$token = new AnonymousToken('foo', 'bar');
$exception = new ChildCustomUserMessageAuthenticationException();
$exception->childMember = $token;
$exception->setToken($token);
$processed = unserialize(serialize($exception));
$this->assertEquals($token, $processed->childMember);
$this->assertEquals($token, $processed->getToken());
$this->assertSame($processed->getToken(), $processed->childMember);
}
}
@@ -19,8 +19,8 @@ class UsernameNotFoundExceptionTest extends TestCase
public function testGetMessageData()
{
$exception = new UsernameNotFoundException('Username could not be found.');
$this->assertEquals(array('{{ username }}' => null), $exception->getMessageData());
$this->assertEquals(['{{ username }}' => null], $exception->getMessageData());
$exception->setUsername('username');
$this->assertEquals(array('{{ username }}' => 'username'), $exception->getMessageData());
$this->assertEquals(['{{ username }}' => 'username'], $exception->getMessageData());
}
}
@@ -12,6 +12,7 @@
namespace Symfony\Component\Security\Core\Tests\Resources;
use PHPUnit\Framework\TestCase;
use PHPUnit\Util\Xml\Loader;
class TranslationFilesTest extends TestCase
{
@@ -20,11 +21,11 @@ class TranslationFilesTest extends TestCase
*/
public function testTranslationFileIsValid($filePath)
{
if (class_exists('PHPUnit_Util_XML')) {
\PHPUnit_Util_XML::loadfile($filePath, false, false, true);
} else {
\PHPUnit\Util\XML::loadfile($filePath, false, false, true);
}
$loader = class_exists(Loader::class)
? [new Loader(), 'loadFile']
: ['PHPUnit\Util\XML', 'loadfile'];
$loader($filePath, false, false, true);
$this->addToAssertionCount(1);
}
@@ -33,7 +34,16 @@ class TranslationFilesTest extends TestCase
{
return array_map(
function ($filePath) { return (array) $filePath; },
glob(dirname(dirname(__DIR__)).'/Resources/translations/*.xlf')
glob(\dirname(\dirname(__DIR__)).'/Resources/translations/*.xlf')
);
}
public function testNorwegianAlias()
{
$this->assertFileEquals(
\dirname(\dirname(__DIR__)).'/Resources/translations/security.nb.xlf',
\dirname(\dirname(__DIR__)).'/Resources/translations/security.no.xlf',
'The NO locale should be an alias for the NB variant of the Norwegian language.'
);
}
}
+10 -10
View File
@@ -12,22 +12,22 @@
namespace Symfony\Component\Security\Core\Tests\Role;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
class RoleHierarchyTest extends TestCase
{
public function testGetReachableRoles()
{
$role = new RoleHierarchy(array(
'ROLE_ADMIN' => array('ROLE_USER'),
'ROLE_SUPER_ADMIN' => array('ROLE_ADMIN', 'ROLE_FOO'),
));
$role = new RoleHierarchy([
'ROLE_ADMIN' => ['ROLE_USER'],
'ROLE_SUPER_ADMIN' => ['ROLE_ADMIN', 'ROLE_FOO'],
]);
$this->assertEquals(array(new Role('ROLE_USER')), $role->getReachableRoles(array(new Role('ROLE_USER'))));
$this->assertEquals(array(new Role('ROLE_FOO')), $role->getReachableRoles(array(new Role('ROLE_FOO'))));
$this->assertEquals(array(new Role('ROLE_ADMIN'), new Role('ROLE_USER')), $role->getReachableRoles(array(new Role('ROLE_ADMIN'))));
$this->assertEquals(array(new Role('ROLE_FOO'), new Role('ROLE_ADMIN'), new Role('ROLE_USER')), $role->getReachableRoles(array(new Role('ROLE_FOO'), new Role('ROLE_ADMIN'))));
$this->assertEquals(array(new Role('ROLE_SUPER_ADMIN'), new Role('ROLE_ADMIN'), new Role('ROLE_FOO'), new Role('ROLE_USER')), $role->getReachableRoles(array(new Role('ROLE_SUPER_ADMIN'))));
$this->assertEquals([new Role('ROLE_USER')], $role->getReachableRoles([new Role('ROLE_USER')]));
$this->assertEquals([new Role('ROLE_FOO')], $role->getReachableRoles([new Role('ROLE_FOO')]));
$this->assertEquals([new Role('ROLE_ADMIN'), new Role('ROLE_USER')], $role->getReachableRoles([new Role('ROLE_ADMIN')]));
$this->assertEquals([new Role('ROLE_FOO'), new Role('ROLE_ADMIN'), new Role('ROLE_USER')], $role->getReachableRoles([new Role('ROLE_FOO'), new Role('ROLE_ADMIN')]));
$this->assertEquals([new Role('ROLE_SUPER_ADMIN'), new Role('ROLE_ADMIN'), new Role('ROLE_FOO'), new Role('ROLE_USER')], $role->getReachableRoles([new Role('ROLE_SUPER_ADMIN')]));
}
}
@@ -13,8 +13,8 @@ namespace Symfony\Component\Security\Core\Tests\User;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\ChainUserProvider;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\ChainUserProvider;
class ChainUserProviderTest extends TestCase
{
@@ -25,7 +25,7 @@ class ChainUserProviderTest extends TestCase
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo('foo'))
->will($this->throwException(new UsernameNotFoundException('not found')))
->willThrowException(new UsernameNotFoundException('not found'))
;
$provider2 = $this->getProvider();
@@ -33,24 +33,22 @@ class ChainUserProviderTest extends TestCase
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo('foo'))
->will($this->returnValue($account = $this->getAccount()))
->willReturn($account = $this->getAccount())
;
$provider = new ChainUserProvider(array($provider1, $provider2));
$provider = new ChainUserProvider([$provider1, $provider2]);
$this->assertSame($account, $provider->loadUserByUsername('foo'));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testLoadUserByUsernameThrowsUsernameNotFoundException()
{
$this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException');
$provider1 = $this->getProvider();
$provider1
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo('foo'))
->will($this->throwException(new UsernameNotFoundException('not found')))
->willThrowException(new UsernameNotFoundException('not found'))
;
$provider2 = $this->getProvider();
@@ -58,10 +56,10 @@ class ChainUserProviderTest extends TestCase
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo('foo'))
->will($this->throwException(new UsernameNotFoundException('not found')))
->willThrowException(new UsernameNotFoundException('not found'))
;
$provider = new ChainUserProvider(array($provider1, $provider2));
$provider = new ChainUserProvider([$provider1, $provider2]);
$provider->loadUserByUsername('foo');
}
@@ -70,18 +68,37 @@ class ChainUserProviderTest extends TestCase
$provider1 = $this->getProvider();
$provider1
->expects($this->once())
->method('refreshUser')
->will($this->throwException(new UnsupportedUserException('unsupported')))
->method('supportsClass')
->willReturn(false)
;
$provider2 = $this->getProvider();
$provider2
->expects($this->once())
->method('refreshUser')
->will($this->returnValue($account = $this->getAccount()))
->method('supportsClass')
->willReturn(true)
;
$provider = new ChainUserProvider(array($provider1, $provider2));
$provider2
->expects($this->once())
->method('refreshUser')
->willThrowException(new UnsupportedUserException('unsupported'))
;
$provider3 = $this->getProvider();
$provider3
->expects($this->once())
->method('supportsClass')
->willReturn(true)
;
$provider3
->expects($this->once())
->method('refreshUser')
->willReturn($account = $this->getAccount())
;
$provider = new ChainUserProvider([$provider1, $provider2, $provider3]);
$this->assertSame($account, $provider->refreshUser($this->getAccount()));
}
@@ -90,41 +107,63 @@ class ChainUserProviderTest extends TestCase
$provider1 = $this->getProvider();
$provider1
->expects($this->once())
->method('refreshUser')
->will($this->throwException(new UsernameNotFoundException('not found')))
->method('supportsClass')
->willReturn(true)
;
$provider2 = $this->getProvider();
$provider2
->expects($this->once())
->method('refreshUser')
->will($this->returnValue($account = $this->getAccount()))
;
$provider = new ChainUserProvider(array($provider1, $provider2));
$this->assertSame($account, $provider->refreshUser($this->getAccount()));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UnsupportedUserException
*/
public function testRefreshUserThrowsUnsupportedUserException()
{
$provider1 = $this->getProvider();
$provider1
->expects($this->once())
->method('refreshUser')
->will($this->throwException(new UnsupportedUserException('unsupported')))
->willThrowException(new UsernameNotFoundException('not found'))
;
$provider2 = $this->getProvider();
$provider2
->expects($this->once())
->method('refreshUser')
->will($this->throwException(new UnsupportedUserException('unsupported')))
->method('supportsClass')
->willReturn(true)
;
$provider = new ChainUserProvider(array($provider1, $provider2));
$provider2
->expects($this->once())
->method('refreshUser')
->willReturn($account = $this->getAccount())
;
$provider = new ChainUserProvider([$provider1, $provider2]);
$this->assertSame($account, $provider->refreshUser($this->getAccount()));
}
public function testRefreshUserThrowsUnsupportedUserException()
{
$this->expectException('Symfony\Component\Security\Core\Exception\UnsupportedUserException');
$provider1 = $this->getProvider();
$provider1
->expects($this->once())
->method('supportsClass')
->willReturn(true)
;
$provider1
->expects($this->once())
->method('refreshUser')
->willThrowException(new UnsupportedUserException('unsupported'))
;
$provider2 = $this->getProvider();
$provider2
->expects($this->once())
->method('supportsClass')
->willReturn(true)
;
$provider2
->expects($this->once())
->method('refreshUser')
->willThrowException(new UnsupportedUserException('unsupported'))
;
$provider = new ChainUserProvider([$provider1, $provider2]);
$provider->refreshUser($this->getAccount());
}
@@ -135,7 +174,7 @@ class ChainUserProviderTest extends TestCase
->expects($this->once())
->method('supportsClass')
->with($this->equalTo('foo'))
->will($this->returnValue(false))
->willReturn(false)
;
$provider2 = $this->getProvider();
@@ -143,10 +182,10 @@ class ChainUserProviderTest extends TestCase
->expects($this->once())
->method('supportsClass')
->with($this->equalTo('foo'))
->will($this->returnValue(true))
->willReturn(true)
;
$provider = new ChainUserProvider(array($provider1, $provider2));
$provider = new ChainUserProvider([$provider1, $provider2]);
$this->assertTrue($provider->supportsClass('foo'));
}
@@ -157,7 +196,7 @@ class ChainUserProviderTest extends TestCase
->expects($this->once())
->method('supportsClass')
->with($this->equalTo('foo'))
->will($this->returnValue(false))
->willReturn(false)
;
$provider2 = $this->getProvider();
@@ -165,13 +204,45 @@ class ChainUserProviderTest extends TestCase
->expects($this->once())
->method('supportsClass')
->with($this->equalTo('foo'))
->will($this->returnValue(false))
->willReturn(false)
;
$provider = new ChainUserProvider(array($provider1, $provider2));
$provider = new ChainUserProvider([$provider1, $provider2]);
$this->assertFalse($provider->supportsClass('foo'));
}
public function testAcceptsTraversable()
{
$provider1 = $this->getProvider();
$provider1
->expects($this->once())
->method('supportsClass')
->willReturn(true)
;
$provider1
->expects($this->once())
->method('refreshUser')
->willThrowException(new UnsupportedUserException('unsupported'))
;
$provider2 = $this->getProvider();
$provider2
->expects($this->once())
->method('supportsClass')
->willReturn(true)
;
$provider2
->expects($this->once())
->method('refreshUser')
->willReturn($account = $this->getAccount())
;
$provider = new ChainUserProvider(new \ArrayObject([$provider1, $provider2]));
$this->assertSame($account, $provider->refreshUser($this->getAccount()));
}
protected function getAccount()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
@@ -23,7 +23,7 @@ class InMemoryUserProviderTest extends TestCase
$user = $provider->loadUserByUsername('fabien');
$this->assertEquals('foo', $user->getPassword());
$this->assertEquals(array('ROLE_USER'), $user->getRoles());
$this->assertEquals(['ROLE_USER'], $user->getRoles());
$this->assertFalse($user->isEnabled());
}
@@ -35,7 +35,7 @@ class InMemoryUserProviderTest extends TestCase
$refreshedUser = $provider->refreshUser($user);
$this->assertEquals('foo', $refreshedUser->getPassword());
$this->assertEquals(array('ROLE_USER'), $refreshedUser->getRoles());
$this->assertEquals(['ROLE_USER'], $refreshedUser->getRoles());
$this->assertFalse($refreshedUser->isEnabled());
$this->assertFalse($refreshedUser->isCredentialsNonExpired());
}
@@ -45,13 +45,13 @@ class InMemoryUserProviderTest extends TestCase
*/
protected function createProvider()
{
return new InMemoryUserProvider(array(
'fabien' => array(
return new InMemoryUserProvider([
'fabien' => [
'password' => 'foo',
'enabled' => false,
'roles' => array('ROLE_USER'),
),
));
'roles' => ['ROLE_USER'],
],
]);
}
public function testCreateUser()
@@ -63,21 +63,17 @@ class InMemoryUserProviderTest extends TestCase
$this->assertEquals('foo', $user->getPassword());
}
/**
* @expectedException \LogicException
*/
public function testCreateUserAlreadyExist()
{
$this->expectException('LogicException');
$provider = new InMemoryUserProvider();
$provider->createUser(new User('fabien', 'foo'));
$provider->createUser(new User('fabien', 'foo'));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testLoadUserByUsernameDoesNotExist()
{
$this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException');
$provider = new InMemoryUserProvider();
$provider->loadUserByUsername('fabien');
}
@@ -15,137 +15,129 @@ use PHPUnit\Framework\TestCase;
use Symfony\Component\Ldap\Adapter\CollectionInterface;
use Symfony\Component\Ldap\Adapter\QueryInterface;
use Symfony\Component\Ldap\Entry;
use Symfony\Component\Ldap\Exception\ConnectionException;
use Symfony\Component\Ldap\LdapInterface;
use Symfony\Component\Security\Core\User\LdapUserProvider;
use Symfony\Component\Ldap\Exception\ConnectionException;
/**
* @requires extension ldap
*/
class LdapUserProviderTest extends TestCase
{
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testLoadUserByUsernameFailsIfCantConnectToLdap()
{
$this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException');
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$ldap
->expects($this->once())
->method('bind')
->will($this->throwException(new ConnectionException()))
->willThrowException(new ConnectionException())
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com');
$provider->loadUserByUsername('foo');
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testLoadUserByUsernameFailsIfNoLdapEntries()
{
$this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException');
$result = $this->getMockBuilder(CollectionInterface::class)->getMock();
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
->willReturn($result)
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(0))
->willReturn(0)
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
->willReturn($query)
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com');
$provider->loadUserByUsername('foo');
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testLoadUserByUsernameFailsIfMoreThanOneLdapEntry()
{
$this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException');
$result = $this->getMockBuilder(CollectionInterface::class)->getMock();
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
->willReturn($result)
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(2))
->willReturn(2)
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
->willReturn($query)
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com');
$provider->loadUserByUsername('foo');
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\InvalidArgumentException
*/
public function testLoadUserByUsernameFailsIfMoreThanOneLdapPasswordsInEntry()
{
$this->expectException('Symfony\Component\Security\Core\Exception\InvalidArgumentException');
$result = $this->getMockBuilder(CollectionInterface::class)->getMock();
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
->willReturn($result)
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$result
->expects($this->once())
->method('offsetGet')
->with(0)
->will($this->returnValue(new Entry('foo', array(
'sAMAccountName' => array('foo'),
'userpassword' => array('bar', 'baz'),
)
)))
->willReturn(new Entry('foo', [
'sAMAccountName' => ['foo'],
'userpassword' => ['bar', 'baz'],
]
))
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(1))
->willReturn(1)
;
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
->willReturn($query)
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com', null, null, array(), 'sAMAccountName', '({uid_key}={username})', 'userpassword');
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com', null, null, [], 'sAMAccountName', '({uid_key}={username})', 'userpassword');
$this->assertInstanceOf(
'Symfony\Component\Security\Core\User\User',
$provider->loadUserByUsername('foo')
@@ -159,77 +151,75 @@ class LdapUserProviderTest extends TestCase
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
->willReturn($result)
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$result
->expects($this->once())
->method('offsetGet')
->with(0)
->will($this->returnValue(new Entry('foo', array())))
->willReturn(new Entry('foo', []))
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(1))
->willReturn(1)
;
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
->willReturn($query)
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com', null, null, array(), 'sAMAccountName', '({uid_key}={username})');
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com', null, null, [], 'sAMAccountName', '({uid_key}={username})');
$this->assertInstanceOf(
'Symfony\Component\Security\Core\User\User',
$provider->loadUserByUsername('foo')
);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\InvalidArgumentException
*/
public function testLoadUserByUsernameFailsIfEntryHasNoPasswordAttribute()
{
$this->expectException('Symfony\Component\Security\Core\Exception\InvalidArgumentException');
$result = $this->getMockBuilder(CollectionInterface::class)->getMock();
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
->willReturn($result)
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$result
->expects($this->once())
->method('offsetGet')
->with(0)
->will($this->returnValue(new Entry('foo', array(
'sAMAccountName' => array('foo'),
)
)))
->willReturn(new Entry('foo', [
'sAMAccountName' => ['foo'],
]
))
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(1))
->willReturn(1)
;
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
->willReturn($query)
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com', null, null, array(), 'sAMAccountName', '({uid_key}={username})', 'userpassword');
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com', null, null, [], 'sAMAccountName', '({uid_key}={username})', 'userpassword');
$this->assertInstanceOf(
'Symfony\Component\Security\Core\User\User',
$provider->loadUserByUsername('foo')
@@ -243,32 +233,32 @@ class LdapUserProviderTest extends TestCase
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
->willReturn($result)
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$result
->expects($this->once())
->method('offsetGet')
->with(0)
->will($this->returnValue(new Entry('foo', array(
'sAMAccountName' => array('foo'),
)
)))
->willReturn(new Entry('foo', [
'sAMAccountName' => ['foo'],
]
))
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(1))
->willReturn(1)
;
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
->willReturn($query)
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com');
@@ -285,32 +275,32 @@ class LdapUserProviderTest extends TestCase
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
->willReturn($result)
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$result
->expects($this->once())
->method('offsetGet')
->with(0)
->will($this->returnValue(new Entry('foo', array(
'sAMAccountName' => array('foo'),
)
)))
->willReturn(new Entry('foo', [
'sAMAccountName' => ['foo'],
]
))
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(1))
->willReturn(1)
;
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('Foo'))
->willReturn('Foo')
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
->willReturn($query)
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com');
@@ -324,36 +314,36 @@ class LdapUserProviderTest extends TestCase
$query
->expects($this->once())
->method('execute')
->will($this->returnValue($result))
->willReturn($result)
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$result
->expects($this->once())
->method('offsetGet')
->with(0)
->will($this->returnValue(new Entry('foo', array(
'sAMAccountName' => array('foo'),
'userpassword' => array('bar'),
)
)))
->willReturn(new Entry('foo', [
'sAMAccountName' => ['foo'],
'userpassword' => ['bar'],
]
))
;
$result
->expects($this->once())
->method('count')
->will($this->returnValue(1))
->willReturn(1)
;
$ldap
->expects($this->once())
->method('escape')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$ldap
->expects($this->once())
->method('query')
->will($this->returnValue($query))
->willReturn($query)
;
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com', null, null, array(), 'sAMAccountName', '({uid_key}={username})', 'userpassword');
$provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com', null, null, [], 'sAMAccountName', '({uid_key}={username})', 'userpassword');
$this->assertInstanceOf(
'Symfony\Component\Security\Core\User\User',
$provider->loadUserByUsername('foo')
+15 -23
View File
@@ -28,20 +28,18 @@ class UserCheckerTest extends TestCase
$checker = new UserChecker();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
$account->expects($this->once())->method('isCredentialsNonExpired')->will($this->returnValue(true));
$account->expects($this->once())->method('isCredentialsNonExpired')->willReturn(true);
$this->assertNull($checker->checkPostAuth($account));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\CredentialsExpiredException
*/
public function testCheckPostAuthCredentialsExpired()
{
$this->expectException('Symfony\Component\Security\Core\Exception\CredentialsExpiredException');
$checker = new UserChecker();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
$account->expects($this->once())->method('isCredentialsNonExpired')->will($this->returnValue(false));
$account->expects($this->once())->method('isCredentialsNonExpired')->willReturn(false);
$checker->checkPostAuth($account);
}
@@ -58,51 +56,45 @@ class UserCheckerTest extends TestCase
$checker = new UserChecker();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
$account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(true));
$account->expects($this->once())->method('isEnabled')->will($this->returnValue(true));
$account->expects($this->once())->method('isAccountNonExpired')->will($this->returnValue(true));
$account->expects($this->once())->method('isAccountNonLocked')->willReturn(true);
$account->expects($this->once())->method('isEnabled')->willReturn(true);
$account->expects($this->once())->method('isAccountNonExpired')->willReturn(true);
$this->assertNull($checker->checkPreAuth($account));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\LockedException
*/
public function testCheckPreAuthAccountLocked()
{
$this->expectException('Symfony\Component\Security\Core\Exception\LockedException');
$checker = new UserChecker();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
$account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(false));
$account->expects($this->once())->method('isAccountNonLocked')->willReturn(false);
$checker->checkPreAuth($account);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\DisabledException
*/
public function testCheckPreAuthDisabled()
{
$this->expectException('Symfony\Component\Security\Core\Exception\DisabledException');
$checker = new UserChecker();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
$account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(true));
$account->expects($this->once())->method('isEnabled')->will($this->returnValue(false));
$account->expects($this->once())->method('isAccountNonLocked')->willReturn(true);
$account->expects($this->once())->method('isEnabled')->willReturn(false);
$checker->checkPreAuth($account);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AccountExpiredException
*/
public function testCheckPreAuthAccountExpired()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AccountExpiredException');
$checker = new UserChecker();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
$account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(true));
$account->expects($this->once())->method('isEnabled')->will($this->returnValue(true));
$account->expects($this->once())->method('isAccountNonExpired')->will($this->returnValue(false));
$account->expects($this->once())->method('isAccountNonLocked')->willReturn(true);
$account->expects($this->once())->method('isEnabled')->willReturn(true);
$account->expects($this->once())->method('isAccountNonExpired')->willReturn(false);
$checker->checkPreAuth($account);
}
+8 -10
View File
@@ -16,21 +16,19 @@ use Symfony\Component\Security\Core\User\User;
class UserTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testConstructorException()
{
$this->expectException('InvalidArgumentException');
new User('', 'superpass');
}
public function testGetRoles()
{
$user = new User('fabien', 'superpass');
$this->assertEquals(array(), $user->getRoles());
$this->assertEquals([], $user->getRoles());
$user = new User('fabien', 'superpass', array('ROLE_ADMIN'));
$this->assertEquals(array('ROLE_ADMIN'), $user->getRoles());
$user = new User('fabien', 'superpass', ['ROLE_ADMIN']);
$this->assertEquals(['ROLE_ADMIN'], $user->getRoles());
}
public function testGetPassword()
@@ -56,7 +54,7 @@ class UserTest extends TestCase
$user = new User('fabien', 'superpass');
$this->assertTrue($user->isAccountNonExpired());
$user = new User('fabien', 'superpass', array(), true, false);
$user = new User('fabien', 'superpass', [], true, false);
$this->assertFalse($user->isAccountNonExpired());
}
@@ -65,7 +63,7 @@ class UserTest extends TestCase
$user = new User('fabien', 'superpass');
$this->assertTrue($user->isCredentialsNonExpired());
$user = new User('fabien', 'superpass', array(), true, true, false);
$user = new User('fabien', 'superpass', [], true, true, false);
$this->assertFalse($user->isCredentialsNonExpired());
}
@@ -74,7 +72,7 @@ class UserTest extends TestCase
$user = new User('fabien', 'superpass');
$this->assertTrue($user->isAccountNonLocked());
$user = new User('fabien', 'superpass', array(), true, true, true, false);
$user = new User('fabien', 'superpass', [], true, true, true, false);
$this->assertFalse($user->isAccountNonLocked());
}
@@ -83,7 +81,7 @@ class UserTest extends TestCase
$user = new User('fabien', 'superpass');
$this->assertTrue($user->isEnabled());
$user = new User('fabien', 'superpass', array(), false);
$user = new User('fabien', 'superpass', [], false);
$this->assertFalse($user->isEnabled());
}
@@ -16,15 +16,14 @@ use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
use Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator;
use Symfony\Component\Validator\Tests\Constraints\AbstractConstraintValidatorTest;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
abstract class UserPasswordValidatorTest extends AbstractConstraintValidatorTest
abstract class UserPasswordValidatorTest extends ConstraintValidatorTestCase
{
const PASSWORD = 's3Cr3t';
const SALT = '^S4lt$';
/**
@@ -59,14 +58,14 @@ abstract class UserPasswordValidatorTest extends AbstractConstraintValidatorTest
public function testPasswordIsValid()
{
$constraint = new UserPassword(array(
$constraint = new UserPassword([
'message' => 'myMessage',
));
]);
$this->encoder->expects($this->once())
->method('isPasswordValid')
->with(static::PASSWORD, 'secret', static::SALT)
->will($this->returnValue(true));
->willReturn(true);
$this->validator->validate('secret', $constraint);
@@ -75,14 +74,14 @@ abstract class UserPasswordValidatorTest extends AbstractConstraintValidatorTest
public function testPasswordIsNotValid()
{
$constraint = new UserPassword(array(
$constraint = new UserPassword([
'message' => 'myMessage',
));
]);
$this->encoder->expects($this->once())
->method('isPasswordValid')
->with(static::PASSWORD, 'secret', static::SALT)
->will($this->returnValue(false));
->willReturn(false);
$this->validator->validate('secret', $constraint);
@@ -95,9 +94,9 @@ abstract class UserPasswordValidatorTest extends AbstractConstraintValidatorTest
*/
public function testEmptyPasswordsAreNotValid($password)
{
$constraint = new UserPassword(array(
$constraint = new UserPassword([
'message' => 'myMessage',
));
]);
$this->validator->validate($password, $constraint);
@@ -107,17 +106,15 @@ abstract class UserPasswordValidatorTest extends AbstractConstraintValidatorTest
public function emptyPasswordData()
{
return array(
array(null),
array(''),
);
return [
[null],
[''],
];
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testUserIsNotValid()
{
$this->expectException('Symfony\Component\Validator\Exception\ConstraintDefinitionException');
$user = $this->getMockBuilder('Foo\Bar\User')->getMock();
$this->tokenStorage = $this->createTokenStorage($user);
@@ -134,13 +131,13 @@ abstract class UserPasswordValidatorTest extends AbstractConstraintValidatorTest
$mock
->expects($this->any())
->method('getPassword')
->will($this->returnValue(static::PASSWORD))
->willReturn(static::PASSWORD)
;
$mock
->expects($this->any())
->method('getSalt')
->will($this->returnValue(static::SALT))
->willReturn(static::SALT)
;
return $mock;
@@ -158,7 +155,7 @@ abstract class UserPasswordValidatorTest extends AbstractConstraintValidatorTest
$mock
->expects($this->any())
->method('getEncoder')
->will($this->returnValue($encoder))
->willReturn($encoder)
;
return $mock;
@@ -172,7 +169,7 @@ abstract class UserPasswordValidatorTest extends AbstractConstraintValidatorTest
$mock
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
->willReturn($token)
;
return $mock;
@@ -184,7 +181,7 @@ abstract class UserPasswordValidatorTest extends AbstractConstraintValidatorTest
$mock
->expects($this->any())
->method('getUser')
->will($this->returnValue($user))
->willReturn($user)
;
return $mock;