deftest_main_no_users(self): """Ensure the main route behaves correctly when no users have been added to the database.""" response = self.client.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'All Users', response.data) self.assertIn(b'<p>No users!</p>', response.data)
$ docker-compose -f docker-compose-dev.yml run users python manage.py test
让我们更新路由并从数据库获取所有用户,而且发送到模板,开始测试:
deftest_main_with_users(self): """Ensure the main route behaves correctly when users have been added to the database.""" add_user('michael', 'michael@mherman.org') add_user('fletcher', 'fletcher@notreal.com') with self.client: response = self.client.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'All Users', response.data) self.assertNotIn(b'<p>No users!</p>', response.data) self.assertIn(b'michael', response.data) self.assertIn(b'fletcher', response.data)
deftest_main_add_user(self): """Ensure a new user can be added to the database.""" with self.client: response = self.client.post( '/', data=dict(username='michael', email='michael@sonotreal.com'), follow_redirects=True ) self.assertEqual(response.status_code, 200) self.assertIn(b'All Users', response.data) self.assertNotIn(b'<p>No users!</p>', response.data) self.assertIn(b'michael', response.data)