Client Test (15)

In Django, the django.test.Client class acts as a virtual web browser, allowing test views to programmatically interact with Django applications.
The Django.test.Client class can do the following:
1. Simulate "GET" and "POST" requests, observe the response results, from HTTP (headers, status code) to page content.
2. Check the redirect chain (if any), and check the URL and status code at each step.
3. Use a template context that includes specific values ​​to test that a request is rendered by a django template.

1. Enter Django shell mode and use setup_test_environment() to initialize the test environment before testing.

write picture description here
Test the index view. The Client class provides get() and post() methods to simulate GET/POST requests. The "/index/" path is requested through get(), which is the login page, and the status code returned by printing HTTP is 200, indicating that the request is successful.

2. Test the home page, open the ../FirstApp/tests.py file, and write the test case for the index view.

from django.test import TestCase
from FirstApp.models import Event, Guest
from django.contrib.auth.models import User

# Create your tests here.
# class ModelTest(TestCase):

    # def setUp(self):
    #   Event.objects.create(id=1,name='tom1',status=True,limit=2000,
    #       address='beijing',start_time='2017-04-19 20:00:01')
    #   Guest.objects.create(id=1,event_id=1,realname='tom2',
    #       phone='13500001111',email='[email protected]',sign=False)

    # def test_event_models(self):
    #   result=Event.objects.get(name='tom1')
    #   self.assertEqual(result.address, "beijing")
    #   self.assertTrue(result.status)

    # def test_guest_models(self):
    #   result=Guest.objects.get(phone='13500001111') 
    #   self.assertEqual(result.realname,"tom2")
    #   self.assertFalse(result.sign)

class IndexPagetest(TestCase):
    """测试index登陆首页"""
    def test_index_page_renders_index_template(self):
        '''测试index视图'''
        response = self.client.get('/index/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'index.html')

Although the Django.test.Client class is not imported here, the method of the Django.test.Client class is still called by self.client, and the "/index/" path is requested through the client.get() method. status_code Get the status code returned by HTTP, and use assertEqual() to assert whether the status code is 200. assertTemplateUsed() asserts whether the server responded with the given index.html template.

3. To test the login action, open the ../FirstApp/tests.py file to write the test case for the login action.

from django.contrib.auth.models import User
........
class LoginActionTest(TestCase):
    """测试登陆动作"""
    def setUp(self):
        User.objects.create_user('admin','[email protected]', 'admin123456')

    def test_add_admin(self):
        '''测试添加用户'''
        user = User.objects.get(username='admin')
        self.assertEqual(user.username, "admin")
        self.assertEqual(user.email, "[email protected]")

    def test_login_action_username_password_null(self):
        '''用户密码为空'''
        test_data = {'username':'','password':''}
        response = self.client.post('/login_action/', data = test_data)
        self.assertEqual(response.status_code, 200)
        self.assertIn(b"username or password error!", response.content)

    def test_login_action_username_password_error(self):
        '''用户名密码错误'''
        test_data = {'username':'abc', 'password':'123'}
        response = self.client.post('/login_action/', data=test_data)
        self.assertEqual(response.status_code, 200)
        self.assertIn(b"username or password error!", response.content)

    def test_login_action_success(self):
        '''测试登陆成功'''
        test_data ={'username':'admin', 'password':'admin123456'}
        response = self.client.post('/login_action/', data = test_data)
        self.assertEqual(response.status_code, 302)

In setUp() initialization, call User.objects.create_user() to create login user data. test_add_admin() is used to test whether the added user data is correct. In other test cases, request the "/login_action/" path to test the login function through the post() method. test_data defines user parameters {'username':'admin','password':'admin123456'}. The assertIn() method asserts whether the returned HTML page contains the "username or password error!" prompt string. The reason why the status code returned by HTTP is 302 is that when the user logs in successfully, the user jumps to the "/event_manage/" path through HttpResponseRedirect(), which is a redirection, so the HTTP return code after successful login is 302.

4. To test the conference management, open the ../FirstApp/tests.py file and add a trial case for the conference management view.

from FirstApp.models import Event, Guest
.......
class EventManageTest(TestCase):
    '''发布会管理'''

    def setUp(self):
        User.objects.create_user('admin', '[email protected]', 'admin123456')
        Event.objects.create(name='xiaomi5',limit=2000,address='beijing',
            status=1,start_time='2018-4-22 14:00:00')
        self.login_user = {'username':'admin', 'password':'admin123456'}

    def test_event_manage_success(self):
        '''测试发布会:xiaomi5'''
        response=self.client.post('/login_action/', data=self.login_user)
        response=self.client.post('/event_manage/')
        self.assertEqual(response.status_code, 200)
        self.assertIn(b"xiaomi5", response.content)
        self.assertIn(b"beijing", response.content)

    def test_event_manage_search_success(self):
        '''测试发布会搜索'''
        response = self.client.post('/login_action/', data=self.login_user)
        response = self.client.post('/search_name/', {"name":"xiaomi5"})
        self.assertEqual(response.status_code, 200)
        self.assertIn(b"xiaomi5", response.content)
        self.assertIn(b"beijing", response.content)

Since the two view functions of the conference management event_manage and the conference name search search_name are modified by @login_required, if you want to test these two functions, you must first log in successfully, and you need to construct the data of the logged in user. So you will see the login function called at the beginning of each use case.

The guest management test, the user check-in test, etc. are all the same as those described above, and will not be described in detail.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324643252&siteId=291194637