简体   繁体   English

如何使用 Pytest-mock 测试输出

[英]How to use Pytest-mock for testing the output

I use below code to test if account is registered successfully.我使用下面的代码来测试帐户是否注册成功。

@pytest.fixture(scope="function")
def ctrl():
    view = RegisterUI()
    return RegisterController(view)

def test_canCreateAccount(ctrl, mocker):
    mocker.patch('ctrl.view.getEmail', return_value ='hello@gmail.com')
    mocker.patch('ctrl.view.getPassword1', return_value='1234567')
    mocker.patch('ctrl.view.getPassword2', return_value='1234567')
    mocker.patch('ctrl.view.getSecKey', return_value='dog')
    account = ctrl.createAccount()
    assert account.email == 'hello@gmail.com'

However, it show an error:但是,它显示一个错误:

    def test_canCreateAccount(ctrl, mocker):
>       mocker.patch('ctrl.view.getEmail', return_value ='hello@gmail.com')

Sub2_Account_Register.py:131: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\..\..\AppData\Roaming\Python\Python37\site-packages\pytest_mock.py:158: in __call__
    return self._start_patch(self.mock_module.patch, *args, **kwargs)
..\..\..\AppData\Roaming\Python\Python37\site-packages\pytest_mock.py:138: in _start_patch
    mocked = p.start()
..\..\..\AppData\Local\Programs\Python\Python37\lib\unittest\mock.py:1399: in start
    result = self.__enter__()
..\..\..\AppData\Local\Programs\Python\Python37\lib\unittest\mock.py:1252: in __enter__
    self.target = self.getter()
..\..\..\AppData\Local\Programs\Python\Python37\lib\unittest\mock.py:1422: in <lambda>
    getter = lambda: _importer(target)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

target = 'ctrl.view'

    def _importer(target):
        components = target.split('.')
        import_path = components.pop(0)
>       thing = __import__(import_path)
E       ModuleNotFoundError: No module named 'ctrl'

..\..\..\AppData\Local\Programs\Python\Python37\lib\unittest\mock.py:1105: ModuleNotFoundError

So how to fix it ?那么如何修复呢? Also, how to test if the message "Account was registerd successfully" was called ?另外,如何测试消息“帐户注册成功”是否被调用?

A member told me that I can use pytest-mock to mock displaymessage() function to check whether it was called or not and check what argument it was called with if called.一个成员告诉我,我可以使用 pytest-mock 来模拟 displaymessage() 函数来检查它是否被调用,并检查它被调用的参数是什么。 However, I don't know how to do that.但是,我不知道该怎么做。 How to implement it correctly ?如何正确实施?

This is my code:这是我的代码:


class CreateAccountFailed(Exception):
    pass


class PassNotValid(CreateAccountFailed):
    pass


class PassNotMatch(CreateAccountFailed):
    pass


class EmailNotOK(CreateAccountFailed):
    pass


class RegisterUI:

    def getEmail(self):
        return input("Please type an your email:")

    def getPassword1(self):
        return input("Please type a password:")

    def getPassword2(self):
        return input("Please confirm your password:")

    def getSecKey(self):
        return input("Please type your security keyword:")

    def printMessage(self, message):
        print(message)


class RegisterController:
    def __init__(self, view):
        self.view = view

    def displaymessage(self, message):
        self.view.printMessage(message)

    def ValidateEmail(self, email):
        email_obj = Email(email)
        return email_obj.isValidEmail() and not accounts.isDuplicate(email)

    def ValidatePassword(self, password):
        return Password.isValidPassword(password)

    def CheckPasswordMatch(self, password1, password2):
        return Password.isMatch(password1, password2)

    def makeAccount(self, email, password, seckey):
        return Account(Email(email), Password(password), seckey)

    def askForValidEmail(self):
        for x in range(0, 3):
            email = self.view.getEmail()
            if self.ValidateEmail(email):
                return email
            else:
                self.displaymessage("Email was invalid or a duplicate, please try again")
        raise EmailNotOK

    def askForValidPassword(self):
        while 1:
            password1 = self.view.getPassword1()
            password2 = self.view.getPassword2()
            if not Password.isMatch(password1, password2):
                self.displaymessage("The passwords do not match")
            elif not Password.isValidPassword(password1):
                self.displaymessage("The password is invalid")
            else:
                return password1

    def createAccount(self):
        email = self.askForValidEmail()
        password = self.askForValidPassword()
        account = self.makeAccount(email, password, self.view.getSecKey())
        self.displaymessage("Account was registerd successfully")
        return account


class Register(Option):
    def execute(self):
        view = RegisterUI()
        controller_one = RegisterController(view)
        controller_one.createAccount()

It's hard to see exactly what you're trying to do, but you need to give mocker the path to a function that it can mock out.很难确切地看到您正在尝试做什么,但是您需要为mocker提供它可以模拟的函数的路径。 I'm not sure what module your code is in, but it looks like it might be Sub2_Account_Register .我不确定您的代码在哪个模块中,但看起来可能是Sub2_Account_Register If so, I think you want to mock something like this:如果是这样,我想你想嘲笑这样的事情:

@pytest.fixture(scope="function")
def ctrl():
    view = RegisterUI()
    return RegisterController(view)

def test_canCreateAccount(ctrl, mocker):
    mocker.patch('Sub2_Account_Register.RegisterUI.getEmail', return_value ='hello@gmail.com')
    mocker.patch('Sub2_Account_Register.RegisterUI.getPassword1', return_value='1234567')
    mocker.patch('Sub2_Account_Register.RegisterUI.getPassword2', return_value='1234567')
    mocker.patch('Sub2_Account_Register.RegisterUI.getSecKey', return_value='dog')
    account = ctrl.createAccount()
    assert account.email == 'hello@gmail.com'

If that doesn't help, I suggest you trim down the code in your question to a minimal example .如果这没有帮助,我建议您将问题中的代码缩减为最小示例 That will make it easier for other users to reproduce your problem and suggest a solution.这将使其他用户更容易重现您的问题并提出解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM