为登录(out)用户显示不同的内容。 Django测试

时间:2018-04-16 12:22:10

标签: django

我正在关注django教程,additional ideas如何测试我的代码。

  

也许应该允许登录的管理员用户查看未发布的内容   问题,但不是普通访客。再说一遍:无论需要什么   添加到软件中以实现此目的应该伴随着   测试,...

如何创建测试以检查登录的用户是否可以看到没有选择但没有登录的问题?

class QuestionsAndChoices(TestCase):
    def test_user_can_see_question_without_choices(self):
        """
        A Question without choices should be displayed only for logged in Users
        """
        #first make an empty question to use as a test
        empty_question = create_question(question_text='Empty question', days=-1)

        #so we can create choice but in this case we don't need it
        #answer_for_question = past_question.choice_set.create(choice_text='Answer for "Question"', votes=0)

        #create a response object to simulate someone using the site
        response = self.client.get(reverse('polls:index'))

        #if user logged in output should contain the question without choices
        self.assertQuerysetEqual(response.context['latest_question_list'], []) #returns empty querylist

1 个答案:

答案 0 :(得分:0)

在测试类的setUp方法中,您可以创建用户。

class QuestionsAndChoices(TestCase):

    def setUp(self):
        self.user = User.objects.create_user(
            username='user', password='top_secret')

然后在您的测试方法中,您可以使用force_login来记录用户,然后使用self.client.get()并像往常一样进行断言。

class QuestionsAndChoices(TestCase):
    def test_user_can_see_question_without_choices(self):
        ...
        self.client.force_login(self.user)

        #create a response object to simulate someone using the site
        response = self.client.get(reverse('polls:index'))

        #if user logged in output should contain the question without choices
        ...