lundi 5 avril 2021

How can I mock a abastract class or interface in Python using - testing with pytest

I create an interface to provide email validation for my controller

class EmailValidatorInterface(ABC):
    """ Interface to EmailValidator use case """

    @abstractmethod
    def is_valid(self, email: str) -> bool:
        """ Specific case """

        raise Exception("Should implement method: is_valid")

That is my controller implementation

class SignUpController(RouteInterface):
    def __init__(self, emailValidator: EmailValidatorInterface):
        self.emailValidator = emailValidator

    def route(self, http_request: Type[HttpRequest]) -> HttpResponse:

How can I create a mock for my EmailValidator? I'm trying to use mock.patch but I don't how to initialize the mock

Look at my test

def test_should_return_400_if_invalid_param_is_provided():

    with mock.patch('EmailValidatorStub') as MockEmailValidator:
        MockEmailValidator.return_value.is_valid.return_value = False

    sut = SignUpController(EmailValidatorStub())
    attributes = {
        "name": faker.word(),
        "login": faker.word(),
        "email": "any_email",
        "email_confirmation": "any_email@mail.com",
        "password": "any_password",
        "password_confirmation": "any_password"
    }

    request = HttpRequest(body=attributes)
    httpResponse = sut.route(request)
    assert httpResponse.status_code == 500



Aucun commentaire:

Enregistrer un commentaire