Chamilo is a learning management system focused on ease of use and accessibility
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
chamilo-lms/tests/ChamiloTestTrait.php

273 lines
8.2 KiB

<?php
namespace Chamilo\Tests;
use Chamilo\CoreBundle\Entity\AccessUrl;
use Chamilo\CoreBundle\Entity\Course;
use Chamilo\CoreBundle\Entity\Session;
use Chamilo\CoreBundle\Entity\User;
4 years ago
use Chamilo\CoreBundle\Entity\Usergroup;
use Chamilo\CoreBundle\Repository\Node\AccessUrlRepository;
use Chamilo\CoreBundle\Repository\Node\CourseRepository;
use Chamilo\CoreBundle\Repository\Node\UserRepository;
use Chamilo\CoreBundle\Repository\SessionRepository;
use Chamilo\CoreBundle\ServiceHelper\ContainerHelper;
use Chamilo\CourseBundle\Entity\CGroup;
use Doctrine\ORM\EntityManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
Internal: PHPUnit: Unit test tweaks * Follow ExtraFieldValues changes on test After a6857b0c30a0561d5186f61ea58be3663b097507 the method and the property changed, so the test also needs to be updated. * Follow UserGroup::setAuthorId() more strict signature on CourseVoterTest It changed on cda50ef101b99b1b166ee28bf38d3bdc53d4e0e3, so test should follow that. * Mock requests stack on CourseVoterTest * Set required CAttendanceCalendar::blocked from CAttendanceRepositoryTest Structure changed at e5397dfaa260bbbd59b8cf30b8fc3c496dcdb582. * Set CAttendanceSheet::signature from CAttendanceRepositoryTest * Mock assumed request on CDocumentRepositoryTest Also, add a note on the session data retrieval point, so it will be replaced for an injection of a request stack object instead. * Temporarily skip a few 403 checks around CDocumentRepositoryTest Let us bring them back soon, but that may need actual fixes to the codebase, so let us postpone them a bit for later. * Make sure assumed server global key is set for CDocumentRepositoryTest This likely needs to be changed to use the value from the symfony request object instead of from the global variable. * Add request mock on CForumCategoryRepositoryTest Ideally it request is injected there, and then the test mocks the request. * Skip forum auto-removal prevention check on category removal This is now working differently on the implementation, so it should be brought back one the implementation prevents the removal, currently it does not prevent it. * Skip forum auto-removal prevention check on post removal Similar to 52f9e663f551580d8af04ecd84740e744fac46a1, see commit message there. * Unify request mocking for a few tests There is enough repetitions already to justify the generalization. It was tempting to use a different trait, but for convenience just used ChamiloTestTrait. * Add mocked request to a couple more tests Namely CCourseDescriptionRepositoryTest, and CForumThreadRepositoryTest. * Skip on-delete check temporarily Again, source needs changing for on-delete cascade behavior before this check can work again. * Add a mocked request for CGroupRepositoryTest * Skip on delete temporarily Again, cascade delete happening but not expected. * Add a mocked request for CLpRepositoryTest * Add mocked request to CQuizRepositoryTest * Skip course visible check temporarily on CQuizRepositoryTest Not working as expected now, it may be an actual problem. * Add a few mocked requests to CStudentPublicationRepositoryTest * Add mocked request to CSurveyRepositoryTest * Adjust commented lines to comply coding standards * Do not set display order on CAnnouncementRepositoryTest Follow 62eaaeda781b366230a6c8a219699a5c746f659d, where the display order is removed from the entity and now on the related resource node. * Do not set display order on CLinkCategoryRepositoryTest Follow 38c0b77c587a4fb13fe8859f0acfb831c4b1e36d, where display order is removed from CLinkCategory in favor of the related resource node equivalent. * Do not set display order on CGlossaryRepositoryTest idem * Do not set display order on CLinkRepositoryTest idem * Make UserRelUserTest pass again When a user A make a friend request to user B, and then user B accepts the request, a new UserRelUser entity is created first with the requested friend constant, and then updated to the friend constant. Only one row is added, and therefore getFriends() method on user A will return user B, but on user B it will not provide any value. Instead when calling getFriendsWithMe() on user A it will provide no values, but on user B it will return A. Adjusted the test to reflect that. Also, tweaked a bit for easier reading. * Make sure assumed server global key is set for PersonalFileRepositoryTest * Change CToolRepositoryTest to focus differently its testing Do not try to use the API for testing the repository.
2 years ago
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\Session as SymfonySession;
use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\Validator\ValidatorInterface;
Internal: PHPUnit: Unit test tweaks * Follow ExtraFieldValues changes on test After a6857b0c30a0561d5186f61ea58be3663b097507 the method and the property changed, so the test also needs to be updated. * Follow UserGroup::setAuthorId() more strict signature on CourseVoterTest It changed on cda50ef101b99b1b166ee28bf38d3bdc53d4e0e3, so test should follow that. * Mock requests stack on CourseVoterTest * Set required CAttendanceCalendar::blocked from CAttendanceRepositoryTest Structure changed at e5397dfaa260bbbd59b8cf30b8fc3c496dcdb582. * Set CAttendanceSheet::signature from CAttendanceRepositoryTest * Mock assumed request on CDocumentRepositoryTest Also, add a note on the session data retrieval point, so it will be replaced for an injection of a request stack object instead. * Temporarily skip a few 403 checks around CDocumentRepositoryTest Let us bring them back soon, but that may need actual fixes to the codebase, so let us postpone them a bit for later. * Make sure assumed server global key is set for CDocumentRepositoryTest This likely needs to be changed to use the value from the symfony request object instead of from the global variable. * Add request mock on CForumCategoryRepositoryTest Ideally it request is injected there, and then the test mocks the request. * Skip forum auto-removal prevention check on category removal This is now working differently on the implementation, so it should be brought back one the implementation prevents the removal, currently it does not prevent it. * Skip forum auto-removal prevention check on post removal Similar to 52f9e663f551580d8af04ecd84740e744fac46a1, see commit message there. * Unify request mocking for a few tests There is enough repetitions already to justify the generalization. It was tempting to use a different trait, but for convenience just used ChamiloTestTrait. * Add mocked request to a couple more tests Namely CCourseDescriptionRepositoryTest, and CForumThreadRepositoryTest. * Skip on-delete check temporarily Again, source needs changing for on-delete cascade behavior before this check can work again. * Add a mocked request for CGroupRepositoryTest * Skip on delete temporarily Again, cascade delete happening but not expected. * Add a mocked request for CLpRepositoryTest * Add mocked request to CQuizRepositoryTest * Skip course visible check temporarily on CQuizRepositoryTest Not working as expected now, it may be an actual problem. * Add a few mocked requests to CStudentPublicationRepositoryTest * Add mocked request to CSurveyRepositoryTest * Adjust commented lines to comply coding standards * Do not set display order on CAnnouncementRepositoryTest Follow 62eaaeda781b366230a6c8a219699a5c746f659d, where the display order is removed from the entity and now on the related resource node. * Do not set display order on CLinkCategoryRepositoryTest Follow 38c0b77c587a4fb13fe8859f0acfb831c4b1e36d, where display order is removed from CLinkCategory in favor of the related resource node equivalent. * Do not set display order on CGlossaryRepositoryTest idem * Do not set display order on CLinkRepositoryTest idem * Make UserRelUserTest pass again When a user A make a friend request to user B, and then user B accepts the request, a new UserRelUser entity is created first with the requested friend constant, and then updated to the friend constant. Only one row is added, and therefore getFriends() method on user A will return user B, but on user B it will not provide any value. Instead when calling getFriendsWithMe() on user A it will provide no values, but on user B it will return A. Adjusted the test to reflect that. Also, tweaked a bit for easier reading. * Make sure assumed server global key is set for PersonalFileRepositoryTest * Change CToolRepositoryTest to focus differently its testing Do not try to use the API for testing the repository.
2 years ago
trait ChamiloTestTrait
{
public function createUser(string $username, string $password = '', string $email = '', string $role = ''): ?User
{
/** @var UserRepository $repo */
$repo = static::getContainer()->get(UserRepository::class);
$admin = $this->getUser('admin');
if (empty($email)) {
$email = "$username@example.com";
}
if (empty($password)) {
$password = $username;
}
$user = $repo->createUser()
->setLastname($username)
->setFirstname($username)
->setUsername($username)
->setStatus(1)
->setPlainPassword($password)
->setEmail($email)
->setCreator($admin)
->setCurrentUrl($this->getAccessUrl())
;
if (!empty($role)) {
$user->addRole($role);
}
$repo->updateUser($user);
return $user;
}
public function createCourse(string $title): ?Course
{
/* @var CourseRepository $repo */
$repo = static::getContainer()->get(CourseRepository::class);
$course = (new Course())
->setTitle($title)
->addAccessUrl($this->getAccessUrl())
->setCreator($this->getUser('admin'))
->setVisibility(Course::OPEN_PLATFORM)
;
$repo->create($course);
return $course;
}
public function createSession(string $title): ?Session
{
$repo = static::getContainer()->get(SessionRepository::class);
$session = (new Session())
->setTitle($title)
->addGeneralCoach($this->getUser('admin'))
->addAccessUrl($this->getAccessUrl())
;
$repo->update($session);
return $session;
}
public function createGroup(string $title, Course $course): ?CGroup
{
$em = $this->getEntityManager();
$group = (new CGroup())
->setTitle($title)
->setParent($course)
->setCreator($this->getUser('admin'))
->setMaxStudent(100)
;
$em->persist($group);
$em->flush();
return $group;
}
4 years ago
public function createUserGroup(string $title): ?Usergroup
{
$em = $this->getEntityManager();
$creator = $this->createUser('usergroup_creator');
$group = (new Usergroup())
->setTitle($title)
4 years ago
->setDescription('desc')
->setCreator($creator)
->addAccessUrl($this->getAccessUrl())
;
$em->persist($group);
$em->flush();
return $group;
}
/**
* Finds a user registered in the test DB, added by the DataFixtures classes.
*/
public function getUser(string $username): ?User
{
/** @var UserRepository $repo */
$repo = static::getContainer()->get(UserRepository::class);
return $repo->findByUsername($username);
}
public function getAdmin(): User
{
return $this->getUser('admin');
}
public function getCourse($courseId): ?Course
{
$repo = static::getContainer()->get(CourseRepository::class);
return $repo->find($courseId);
}
public function getAccessUrl(string $url = ''): ?AccessUrl
{
if (empty($url)) {
$url = AccessUrl::DEFAULT_ACCESS_URL;
}
/** @var AccessUrlRepository $repo */
$repo = static::getContainer()->get(AccessUrlRepository::class);
return $repo->findOneBy(['url' => $url]);
}
public function assertHasNoEntityViolations($entity)
{
/** @var ConstraintViolationList $errors */
$errors = $this->getViolations($entity);
$message = [];
foreach ($errors as $error) {
$message[] = $error->getPropertyPath().': '.$error->getMessage();
}
$this->assertEquals(0, $errors->count(), implode(', ', $message));
}
public function getUploadedFileArray(): array
{
return [
'tmp_name' => $this->getUploadedFile()->getRealPath(),
'name' => $this->getUploadedFile()->getFilename(),
'type' => $this->getUploadedFile()->getMimeType(),
'size' => $this->getUploadedFile()->getSize(),
'error' => UPLOAD_ERR_OK,
];
}
public function getUploadedFile(): UploadedFile
{
$path = $this->getContainer()->get('kernel')->getProjectDir();
$filePath = $path.'/tests/fixtures/logo.png';
$fileName = basename($filePath);
return new UploadedFile(
$filePath,
$fileName,
'image/png',
);
}
public function getUploadedZipFile(): UploadedFile
{
$path = $this->getContainer()->get('kernel')->getProjectDir();
$filePath = $path.'/tests/fixtures/logo.zip';
$fileName = basename($filePath);
return new UploadedFile(
$filePath,
$fileName,
'image/png',
);
}
public function getViolations($entity)
{
/** @var ContainerHelper $containerHelper */
$containerHelper = static::$kernel->getContainer()->get(ContainerHelper::class);
$validator = $containerHelper->getValidator();
/** @var ConstraintViolationList $errors */
return $validator->validate($entity);
}
public function convertToUTCAndFormat(\DateTime $localTime) : string
{
return $localTime->setTimezone(new \DateTimeZone('UTC'))->format('c');
}
public function getEntityManager(): EntityManager
{
return static::getContainer()->get('doctrine')->getManager();
}
Internal: PHPUnit: Unit test tweaks * Follow ExtraFieldValues changes on test After a6857b0c30a0561d5186f61ea58be3663b097507 the method and the property changed, so the test also needs to be updated. * Follow UserGroup::setAuthorId() more strict signature on CourseVoterTest It changed on cda50ef101b99b1b166ee28bf38d3bdc53d4e0e3, so test should follow that. * Mock requests stack on CourseVoterTest * Set required CAttendanceCalendar::blocked from CAttendanceRepositoryTest Structure changed at e5397dfaa260bbbd59b8cf30b8fc3c496dcdb582. * Set CAttendanceSheet::signature from CAttendanceRepositoryTest * Mock assumed request on CDocumentRepositoryTest Also, add a note on the session data retrieval point, so it will be replaced for an injection of a request stack object instead. * Temporarily skip a few 403 checks around CDocumentRepositoryTest Let us bring them back soon, but that may need actual fixes to the codebase, so let us postpone them a bit for later. * Make sure assumed server global key is set for CDocumentRepositoryTest This likely needs to be changed to use the value from the symfony request object instead of from the global variable. * Add request mock on CForumCategoryRepositoryTest Ideally it request is injected there, and then the test mocks the request. * Skip forum auto-removal prevention check on category removal This is now working differently on the implementation, so it should be brought back one the implementation prevents the removal, currently it does not prevent it. * Skip forum auto-removal prevention check on post removal Similar to 52f9e663f551580d8af04ecd84740e744fac46a1, see commit message there. * Unify request mocking for a few tests There is enough repetitions already to justify the generalization. It was tempting to use a different trait, but for convenience just used ChamiloTestTrait. * Add mocked request to a couple more tests Namely CCourseDescriptionRepositoryTest, and CForumThreadRepositoryTest. * Skip on-delete check temporarily Again, source needs changing for on-delete cascade behavior before this check can work again. * Add a mocked request for CGroupRepositoryTest * Skip on delete temporarily Again, cascade delete happening but not expected. * Add a mocked request for CLpRepositoryTest * Add mocked request to CQuizRepositoryTest * Skip course visible check temporarily on CQuizRepositoryTest Not working as expected now, it may be an actual problem. * Add a few mocked requests to CStudentPublicationRepositoryTest * Add mocked request to CSurveyRepositoryTest * Adjust commented lines to comply coding standards * Do not set display order on CAnnouncementRepositoryTest Follow 62eaaeda781b366230a6c8a219699a5c746f659d, where the display order is removed from the entity and now on the related resource node. * Do not set display order on CLinkCategoryRepositoryTest Follow 38c0b77c587a4fb13fe8859f0acfb831c4b1e36d, where display order is removed from CLinkCategory in favor of the related resource node equivalent. * Do not set display order on CGlossaryRepositoryTest idem * Do not set display order on CLinkRepositoryTest idem * Make UserRelUserTest pass again When a user A make a friend request to user B, and then user B accepts the request, a new UserRelUser entity is created first with the requested friend constant, and then updated to the friend constant. Only one row is added, and therefore getFriends() method on user A will return user B, but on user B it will not provide any value. Instead when calling getFriendsWithMe() on user A it will provide no values, but on user B it will return A. Adjusted the test to reflect that. Also, tweaked a bit for easier reading. * Make sure assumed server global key is set for PersonalFileRepositoryTest * Change CToolRepositoryTest to focus differently its testing Do not try to use the API for testing the repository.
2 years ago
/**
* Helper to mock a request stack with a given current request.
*
* Builds a request based on parameters, and adds it to the returned
* request stack.
*
* @param array $data
* A map where keys can be the following:
* - <request_parameter>: A parameter following symfony http foundation
* Request constructor.
* - 'session': and array with session data to set.
*
* @see \Symfony\Component\HttpFoundation\Request::__construct()
*/
public function getMockedRequestStack(array $data = []) : RequestStack
{
$request_keys = ['query', 'request', 'attributes', 'cookies', 'files', 'server', 'content'];
$request_parameters = [];
foreach ($request_keys as $request_key) {
$request_parameter_default = ($request_key == 'content') ? null : [];
$request_parameter = !empty($data[$request_key]) ? $data[$request_key] : $request_parameter_default;
$request_parameters[] = $request_parameter;
}
$request = new Request();
call_user_func_array(array($request, 'initialize'), $request_parameters);
if (!empty($data['session'])) {
$session = new SymfonySession(new MockFileSessionStorage);
foreach ($data['session'] as $session_key => $session_value) {
$session->set($session_key, $session_value);
}
$request->setSession($session);
}
$request_stack = $this->createMock(RequestStack::class);
$request_stack
->method('getCurrentRequest')
->willReturn($request)
;
return $request_stack;
}
}