Search code examples
dockersymfonyvalidationassertapi-platform.com

Symfony NotBlank constraint allow blank string


I'm working with Symfony5 and ApiPlatform with phpunit for the tests

I'm running tests on field validation.

My issue comes from the fact that I want to restrain the user's possiblity to enter a blank string in a property named name as follow :

/**
 * @ApiResource(
 *     attributes={
 *          "normalization_context"={"groups"={"cons:read", "cons:list"}},
 *          "denormalization_context"={"groups"={"cons:write"}}
 *     },
 *     collectionOperations={
 *          "get"={
 *              "mehtod"="GET",
 *              "normalization_context"={"groups"={"cons:list"}},
 *          },
 *          "post"={
 *              "method"="POST"
 *              "normalizationContext"={"groups"={"cons:write"}},
 *              "validationGroups"={"create"}
 *          }
 *     }
 * )
 * @ORM\Entity(repositoryClass=ConsultationTypeRepository::class)
 */
class ClassName
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @Groups({"cons:read", "cons:list", "some:read", "thing:read"})
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=false)
     * @Groups({"cons:read", "cons:write", "cons:list", "some:read", "thing:read", "availability:read"})
     * @Assert\NotBlank (
     *     groups={"create"},
     *     message="Le nom ne peut pas être vide."
     * )
     * @Assert\Length(
     *     max = 255,
     *     maxMessage = "Le nom ne peut pas excéder 255 charactères",
     *     allowEmptyString = false
     * )
     * @Assert\Regex(
     *     pattern="/\d/",
     *     match=false,
     *     message="Le nom ne peut pas contenir de nombre"
     * )
     */
    private $name;

Here is my test :

public function testRoleAdminCanNotPostConsultationWithBlankName(): void
    {
        $body = '{ "name": ""}';
        $res = $this->buildPostPutRequest(
            Actions::POST,
            self::TYPE_CONSULTATION_ROUTE,
            $body,
            self::ADMIN_CREDENTIALS
        );
        $this->assertResponseStatusCodeSame(400);
    }

Now I receive a 201 instead of the expected 400.

While other tests concerning the regex or the length of the string return 400 as expected.

I don't understand why the NotBlank() seem to not trigger on this test.

Any idea ?


Solution

  • I think this is because you've declared your post operations attributes using camel case instead of snake case. Camel case must be used at the top-level of the ApiResource annotation only.

    Currently, you've only declared the method of your operation. This is useless here.

    • normalizationContext => normalization_context
    • validationGroups => validation_groups

    Also you've declared a mehtod property instead of method within you GET operation.