UserRegistrationResourceTest.php in Drupal 10
File
core/modules/user/tests/src/Unit/UserRegistrationResourceTest.php
View source
<?php
namespace Drupal\Tests\user\Unit;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Session\AccountInterface;
use Drupal\Tests\UnitTestCase;
use Drupal\user\Entity\User;
use Drupal\user\Plugin\rest\resource\UserRegistrationResource;
use Drupal\user\UserInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class UserRegistrationResourceTest extends UnitTestCase {
const ERROR_MESSAGE = "Unprocessable Entity: validation failed.\nproperty_path: message\nproperty_path_2: message_2\n";
protected $testClass;
protected $reflection;
protected $userSettings;
protected $logger;
protected $currentUser;
protected function setUp() : void {
parent::setUp();
$this->logger = $this
->prophesize(LoggerInterface::class)
->reveal();
$this->userSettings = $this
->prophesize(ImmutableConfig::class);
$this->currentUser = $this
->prophesize(AccountInterface::class);
$this->testClass = new UserRegistrationResource([], 'plugin_id', '', [], $this->logger, $this->userSettings
->reveal(), $this->currentUser
->reveal());
$this->reflection = new \ReflectionClass($this->testClass);
}
public function testEmptyPost() {
$this
->expectException(BadRequestHttpException::class);
$this->testClass
->post(NULL);
}
public function testExistedEntityPost() {
$entity = $this
->prophesize(User::class);
$entity
->isNew()
->willReturn(FALSE);
$this
->expectException(BadRequestHttpException::class);
$this->testClass
->post($entity
->reveal());
}
public function testRegistrationAdminOnlyPost() {
$this->userSettings
->get('register')
->willReturn(UserInterface::REGISTER_ADMINISTRATORS_ONLY);
$this->currentUser
->isAnonymous()
->willReturn(TRUE);
$this->testClass = new UserRegistrationResource([], 'plugin_id', '', [], $this->logger, $this->userSettings
->reveal(), $this->currentUser
->reveal());
$entity = $this
->prophesize(User::class);
$entity
->isNew()
->willReturn(TRUE);
$this
->expectException(AccessDeniedHttpException::class);
$this->testClass
->post($entity
->reveal());
}
public function testRegistrationAnonymousOnlyPost() {
$this->currentUser
->isAnonymous()
->willReturn(FALSE);
$this->testClass = new UserRegistrationResource([], 'plugin_id', '', [], $this->logger, $this->userSettings
->reveal(), $this->currentUser
->reveal());
$entity = $this
->prophesize(User::class);
$entity
->isNew()
->willReturn(TRUE);
$this
->expectException(AccessDeniedHttpException::class);
$this->testClass
->post($entity
->reveal());
}
}