from plone import api as plone_api
from ploneintranet.userprofile.content.userprofile import IUserProfile
from ploneintranet.userprofile.tests.base import BaseTestCase
from Products.CMFCore.indexing import processQueue
from z3c.form.interfaces import IValidator
from zope.component import getMultiAdapter
from zope.interface import Invalid


class TestValidators(BaseTestCase):
    """Test validators."""

    def test_username_is_unique(self):
        """Test that username is unique amongst users."""
        params = {
            "username": "johndoe",
            "first_name": "John",
            "last_name": "Doe",
            "email": "johndoe@example.com",
            "password": "secret",
            "confirm_password": "secret",
        }
        profile = plone_api.content.create(
            container=self.profiles,
            type="ploneintranet.userprofile.userprofile",
            id="johndoe",
            **params,
        )
        plone_api.content.transition(profile, "approve")
        processQueue()

        # janedoe is not used
        validator = getMultiAdapter(
            (profile, self.request, None, IUserProfile["username"], None), IValidator
        )
        self.assertIsNone(validator.validate("janedoe"))

        # if context is the user that has this value as username, do not raise
        self.assertIsNone(validator.validate("johndoe"))

        # if context is another user, raise Invalid
        validator.context = self.profiles
        with self.assertRaises(Invalid):
            validator.validate("johndoe")
