为登录django创建测试脚本

Creating Test script for login django

请帮助我。我目前的任务是为登录方法创建一个测试脚本。

这是我正在测试的登录方式...

    class AuthViewModel():
        fixture = [user]
        user_name = 'usera'
        password = '12345678'

        def login_page(self, userName, password, request):
            """
            Login by ID & PWD
            """

            # Get user by name & password
            self.user = authenticate(username=userName, password=password)

            if self.user is not None:
                if self.user.is_active:
                    # Login by Django
                    login(request, self.user)
                else:
                    # User not active
                    self.message = "User is not actived yet"
            else:
                # User not exist
                self.message = "User name or password is incorrect"

这是我做的测试脚本。

def test_login_page(self):
    """Test log in
    """

    actauth = AuthViewModel()
    actauth.actinbox_login(self.user_name, self.password, request)
    self.assertEqual(actauth.message, 'User name or password is incorrect')

这是我的问题,我收到了错误消息

NameError: name 'request' is not defined

如何定义'request'?

您需要创建一个带有 RequestFactory 的请求对象。

The RequestFactory shares the same API as the test client. However, instead of behaving like a browser, the RequestFactory provides a way to generate a request instance that can be used as the first argument to any view. This means you can test a view function the same way as you would test any other function – as a black box, with exactly known inputs, testing for specific outputs.

所以基本上

 factory = RequestFactory()
 request = factory.get('/your/login/page/')
 actauth = AuthViewModel()
 actauth.actinbox_login(self.user_name, self.password, request)
 self.assertEqual(actauth.message, 'User name or password is incorrect')