Skip to content
test_flow.py 189 KiB
Newer Older
Dong Zhuang's avatar
Dong Zhuang committed
            self.assertEqual(len(past_sessions_and_properties), 0)

    def test_get_may_list_existing_sessions(self):
        session_start_rule = self.get_hacked_session_start_rule()

        # create 2 session with different access_rule and grading_rule
        fs1 = self.get_test_flow_session(in_progress=False,
Dong Zhuang's avatar
Dong Zhuang committed
                                         start_time=now() - timedelta(days=3))
Dong Zhuang's avatar
Dong Zhuang committed
        fs2 = self.get_test_flow_session(in_progress=True,
Dong Zhuang's avatar
Dong Zhuang committed
                                         start_time=now() - timedelta(days=2),
                                         completion_time=None)
Dong Zhuang's avatar
Dong Zhuang committed

        access_rule_for_session1 = self.get_hacked_session_access_rule(
Dong Zhuang's avatar
Dong Zhuang committed
            permissions=[fperm.cannot_see_flow_result]
Dong Zhuang's avatar
Dong Zhuang committed
        )

        access_rule_for_session2 = self.get_hacked_session_access_rule(
            permissions=[
Dong Zhuang's avatar
Dong Zhuang committed
                fperm.view,
                fperm.submit_answer,
                fperm.end_session,
                fperm.see_answer_after_submission]
Dong Zhuang's avatar
Dong Zhuang committed
        )

        grading_rule_for_session1 = self.get_hacked_session_grading_rule(
            due=None, max_points=10
        )
        grading_rule_for_session2 = self.get_hacked_session_grading_rule(
            due=now() - timedelta(days=1), max_points=9
        )

        new_session_grading_rule = self.get_hacked_session_grading_rule(
            due=now() + timedelta(hours=2), max_points=8
        )

        self.mock_get_session_start_rule.return_value = session_start_rule

        self.mock_get_session_access_rule.side_effect = [
            access_rule_for_session1, access_rule_for_session2
        ]

        self.mock_get_session_grading_rule.side_effect = [
            grading_rule_for_session1, grading_rule_for_session2,
            new_session_grading_rule
        ]

        with self.temporarily_switch_to_user(self.student_participation.user):
            resp = self.c.get(self.get_view_start_flow_url(self.flow_id))
            self.assertResponseContextEqual(resp, "may_start", True)
            self.assertResponseContextEqual(
                resp, "start_may_decrease_grade", True)
            past_sessions_and_properties = resp.context[
                "past_sessions_and_properties"]
            self.assertEqual(len(past_sessions_and_properties), 2)

            psap_session1, psap_property1 = past_sessions_and_properties[0]
            self.assertEqual(psap_session1, fs1)
            self.assertEqual(psap_property1.may_view, False)
            self.assertEqual(psap_property1.may_modify, False)
            self.assertEqual(psap_property1.due, None)
            self.assertEqual(psap_property1.grade_shown, False)

            psap_session2, psap_property2 = past_sessions_and_properties[1]
            self.assertEqual(psap_session2, fs2)
            self.assertEqual(psap_property2.may_view, True)
            self.assertEqual(psap_property2.may_modify, True)
            self.assertIsNotNone(psap_property2.due)
            self.assertEqual(psap_property2.grade_shown, True)

    def test_get_not_may_list_existing_sessions(self):
        session_start_rule = self.get_hacked_session_start_rule(
            may_start_new_session=False,
            may_list_existing_sessions=False,
        )

        # create 2 session with different access_rule and grading_rule
        self.get_test_flow_session(in_progress=False,
                                   start_time=now() - timedelta(days=3))
        self.get_test_flow_session(in_progress=True,
                                   start_time=now() - timedelta(days=2),
                                   completion_time=None)

        self.mock_get_session_start_rule.return_value = session_start_rule

        self.mock_get_session_grading_rule.return_value = (
            self.get_hacked_session_grading_rule(
                due=now() + timedelta(hours=2), max_points=8))

        with self.temporarily_switch_to_user(self.student_participation.user):
            resp = self.c.get(self.get_view_start_flow_url(self.flow_id))
            self.assertResponseContextEqual(resp, "may_start", False)
            self.assertResponseContextEqual(
                resp, "start_may_decrease_grade", False)

            past_sessions_and_properties = resp.context[
                "past_sessions_and_properties"]

            self.assertEqual(len(past_sessions_and_properties), 0)

        self.assertEqual(self.mock_get_session_grading_rule.call_count, 0)
        self.assertEqual(self.mock_get_session_access_rule.call_count, 0)


class PostStartFlowTest(SingleCourseTestMixin, TestCase):
    # test flow.post_start_flow

    flow_id = QUIZ_FLOW_ID

    def setUp(self):
        super(PostStartFlowTest, self).setUp()

        fake_get_login_exam_ticket = mock.patch("course.flow.get_login_exam_ticket")
        self.mock_get_login_exam_ticket = fake_get_login_exam_ticket.start()
        self.addCleanup(fake_get_login_exam_ticket.stop)

        fake_flow_context = mock.patch("course.flow.FlowContext")
        self.mock_flow_context = fake_flow_context.start()
        self.fctx = mock.MagicMock()
        self.fctx.flow_id = self.flow_id
        self.fctx.flow_desc = dict_to_struct(
            {"title": "test page title", "description_html": "foo bar"})
        self.mock_flow_context.return_value = self.fctx
        self.addCleanup(fake_flow_context.stop)

        fake_get_session_start_rule = mock.patch(
            "course.flow.get_session_start_rule")
        self.mock_get_session_start_rule = fake_get_session_start_rule.start()
        self.addCleanup(fake_get_session_start_rule.stop)

        fake_get_session_access_rule = mock.patch(
            "course.flow.get_session_access_rule")
        self.mock_get_session_access_rule = fake_get_session_access_rule.start()
        self.addCleanup(fake_get_session_access_rule.stop)

        fake_lock_down_if_needed = mock.patch(
            "course.flow.lock_down_if_needed")
        self.mock_lock_down_if_needed = fake_lock_down_if_needed.start()
        self.addCleanup(fake_lock_down_if_needed.stop)

        fake_start_flow = mock.patch("course.flow.start_flow")
        self.mock_start_flow = fake_start_flow.start()
        self.addCleanup(fake_start_flow.stop)

    def get_hacked_session_access_rule(self, **kwargs):
        from course.utils import FlowSessionAccessRule
        defaults = {
            "permissions": [],
        }
        defaults.update(kwargs)
        return FlowSessionAccessRule(**defaults)

    def get_hacked_session_start_rule(self, **kwargs):
        from course.utils import FlowSessionStartRule
        defaults = {
            "tag_session": None,
            "may_start_new_session": True,
            "may_list_existing_sessions": True,
            "default_expiration_mode": None,
        }
        defaults.update(kwargs)
        return FlowSessionStartRule(**defaults)

    def test_cooldown_seconds_worked(self):
        with self.temporarily_switch_to_user(self.student_participation.user):
            self.mock_get_session_start_rule.return_value = \
                self.get_hacked_session_start_rule()

            mock_session = mock.MagicMock()
            mock_session.id = 0
            mock_session.pk = 0
            self.mock_start_flow.return_value = mock_session

            # create an exising session started recently
            factories.FlowSessionFactory(participation=self.student_participation)

            self.start_flow(self.flow_id, ignore_cool_down=False,
                            assume_success=False)
            self.assertEqual(self.mock_start_flow.call_count, 0)
            self.assertEqual(self.mock_get_session_access_rule.call_count, 0)
            self.assertEqual(self.mock_get_login_exam_ticket.call_count, 1)
            self.assertEqual(self.mock_lock_down_if_needed.call_count, 0)

    def test_cooldown_seconds_dued(self):
        with self.temporarily_switch_to_user(self.student_participation.user):
            self.mock_get_session_start_rule.return_value = (
                self.get_hacked_session_start_rule())

            mock_session = mock.MagicMock()
            mock_session.id = 0
            mock_session.pk = 0
            self.mock_start_flow.return_value = mock_session

            # create an exising session started recently
            factories.FlowSessionFactory(
                participation=self.student_participation,
                start_time=now() - timedelta(seconds=11))

            self.start_flow(self.flow_id, ignore_cool_down=False,
                            assume_success=False)
            self.assertEqual(self.mock_start_flow.call_count, 1)
            self.assertEqual(self.mock_get_session_access_rule.call_count, 1)
            self.assertEqual(self.mock_get_login_exam_ticket.call_count, 1)
            self.assertEqual(self.mock_lock_down_if_needed.call_count, 1)

    def test_not_may_start(self):
        with self.temporarily_switch_to_user(self.student_participation.user):
            self.mock_get_session_start_rule.return_value = \
                self.get_hacked_session_start_rule(
                    may_start_new_session=False,
                )
            resp = self.start_flow(self.flow_id, ignore_cool_down=True,
                                   assume_success=False)
            self.assertEqual(resp.status_code, 403)

            self.assertEqual(self.mock_start_flow.call_count, 0)
            self.assertEqual(self.mock_get_session_access_rule.call_count, 0)
            self.assertEqual(self.mock_get_login_exam_ticket.call_count, 1)
            self.assertEqual(self.mock_lock_down_if_needed.call_count, 0)

    def test_start_session_for_anonymous(self):
        self.c.logout()
        self.mock_get_session_start_rule.return_value = \
            self.get_hacked_session_start_rule(
                may_start_new_session=True,
            )

        mock_session = mock.MagicMock()
        mock_session.id = 0
        mock_session.pk = 0
        self.mock_start_flow.return_value = mock_session

        resp = self.start_flow(self.flow_id, ignore_cool_down=True,
                               assume_success=False)
        self.assertEqual(resp.status_code, 302)

        self.assertEqual(self.mock_start_flow.call_count, 1)
        self.assertEqual(self.mock_get_session_access_rule.call_count, 1)
        self.assertEqual(self.mock_get_login_exam_ticket.call_count, 1)
        self.assertEqual(self.mock_lock_down_if_needed.call_count, 1)


Dong Zhuang's avatar
Dong Zhuang committed
3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000
class ViewResumeFlowTest(SingleCourseTestMixin, TestCase):
    # test flow.view_resume_flow
    def test(self):
        fs = factories.FlowSessionFactory(participation=self.student_participation)
        faked_now_datetime = now() + timedelta(days=1)

        with mock.patch(
                "course.flow.get_now_or_fake_time"
        ) as mock_now, mock.patch(
            "course.flow.get_and_check_flow_session"
        ) as mock_check_fs, mock.patch(
            "course.flow.get_login_exam_ticket"
        ) as mock_get_ticket, mock.patch(
            "course.flow.get_session_access_rule"
        ) as mock_get_ac, mock.patch(
            "course.flow.lock_down_if_needed"
        ) as mock_lock_down:
            mock_now.return_value = faked_now_datetime
            mock_check_fs.return_value = fs
            faked_ticket = mock.MagicMock()
            mock_get_ticket.return_value = faked_ticket

            resp = self.c.get(self.get_resume_flow_url(
                course_identifier=self.course.identifier, flow_session_id=fs.pk))

            self.assertRedirects(
                resp, self.get_page_url_by_ordinal(
                    page_ordinal=0, flow_session_id=fs.pk),
                fetch_redirect_response=False)

            self.assertEqual(mock_check_fs.call_count, 1)
            self.assertEqual(mock_get_ticket.call_count, 1)
            self.assertEqual(mock_get_ac.call_count, 1)
            self.assertIn("facilities", mock_get_ac.call_args[1])
            self.assertEqual(mock_get_ac.call_args[1]["login_exam_ticket"],
                             faked_ticket)

            self.assertEqual(mock_lock_down.call_count, 1)


class GetAndCheckFlowSessionTest(SingleCourseTestMixin, TestCase):
    # test flow.get_and_check_flow_session

    def setUp(self):
        super(GetAndCheckFlowSessionTest, self).setUp()
        self.rf = RequestFactory()

    def get_pctx(self, request_user):
        request = self.rf.get(self.get_course_page_url())
        request.user = request_user

        from course.utils import CoursePageContext
        pctx = CoursePageContext(request, self.course.identifier)
        return pctx

    def test_object_does_not_exist(self):
        pctx = self.get_pctx(self.student_participation.user)

        with self.assertRaises(http.Http404):
            flow.get_and_check_flow_session(pctx, flow_session_id=100)

    def test_flow_session_course_not_match(self):
        another_course = factories.CourseFactory(identifier="another-course")
        another_course_fs = factories.FlowSessionFactory(
            participation=factories.ParticipationFactory(course=another_course)
        )

        pctx = self.get_pctx(self.student_participation.user)

        with self.assertRaises(http.Http404):
            flow.get_and_check_flow_session(
                pctx, flow_session_id=another_course_fs.pk)

    def test_anonymous_session(self):
        anonymous_session = factories.FlowSessionFactory(
            course=self.course, participation=None, user=None
        )

        pctx = self.get_pctx(request_user=AnonymousUser())

        self.assertEqual(
            flow.get_and_check_flow_session(
                pctx, flow_session_id=anonymous_session.pk),
            anonymous_session)

    def test_my_session(self):
        my_session = factories.FlowSessionFactory(
            course=self.course, participation=self.student_participation
        )

        pctx = self.get_pctx(request_user=self.student_participation.user)

        self.assertEqual(
            flow.get_and_check_flow_session(
                pctx, flow_session_id=my_session.pk),
            my_session)

    def test_not_my_session_anonymous(self):
        my_session = factories.FlowSessionFactory(
            course=self.course, participation=self.student_participation
        )

        from django.contrib.auth.models import AnonymousUser
        pctx = self.get_pctx(request_user=AnonymousUser())

        with self.assertRaises(PermissionDenied) as cm:
            flow.get_and_check_flow_session(
                pctx, flow_session_id=my_session.pk)
        expected_error_msg = "may not view other people's sessions"
        self.assertIn(expected_error_msg, str(cm.exception))

    def test_view_student_session(self):
        student_session = factories.FlowSessionFactory(
            course=self.course, participation=self.student_participation
        )

        pctx = self.get_pctx(request_user=self.instructor_participation.user)

        self.assertEqual(
            flow.get_and_check_flow_session(
                pctx, flow_session_id=student_session.pk),
            student_session)


class WillReceiveFeedbackTest(unittest.TestCase):
    # test flow.will_receive_feedback
    def test1(self):
        self.assertFalse(flow.will_receive_feedback(frozenset(["abcd", "efg"])))

    def test2(self):
        self.assertFalse(flow.will_receive_feedback(
            frozenset([
                fperm.submit_answer,
                fperm.see_answer_before_submission])))

    def test3(self):
        self.assertTrue(flow.will_receive_feedback(
            frozenset([
                fperm.see_correctness,
                fperm.see_answer_before_submission])))

    def test4(self):
        self.assertTrue(flow.will_receive_feedback(
            frozenset([
                fperm.submit_answer,
                fperm.see_answer_after_submission])))


class MaySendEmailAboutFlowPageTest(unittest.TestCase):
    # test flow.may_send_email_about_flow_page
    def test1(self):
        self.assertFalse(flow.may_send_email_about_flow_page(
            frozenset(["abcd", "efg"])))

    def test2(self):
        self.assertFalse(flow.may_send_email_about_flow_page(
            frozenset([
                fperm.submit_answer,
                fperm.see_answer_before_submission])))

    def test3(self):
        self.assertTrue(flow.may_send_email_about_flow_page(
            frozenset([
                "blahblah",
                fperm.send_email_about_flow_page])))

    def test4(self):
        self.assertTrue(flow.may_send_email_about_flow_page(
            frozenset([
                fperm.send_email_about_flow_page])))


@unittest.skipIf(six.PY2, "PY2 doesn't support subTest")
class GetPageBehaviorTest(unittest.TestCase):
    # test flow.get_page_behavior
    def setUp(self):
        self.page = mock.MagicMock()

    def assertShowCorrectness(self, behavior, perms, show=True):  # noqa
        self.assertEqual(
            behavior.show_correctness, show,
            "behavior.show_correctness unexpected to be %s with %s"
            % (not show, ", ".join(perms)))

    def assertShowAnswer(self, behavior, perms, show=True):  # noqa
        self.assertEqual(behavior.show_answer, show,
                         "behavior.show_answer unexpected to be %s with %s"
                         % (not show, ", ".join(perms)))

    def assertMayChangeAnswer(self, behavior, perms, may_change=True):  # noqa
        self.assertEqual(behavior.may_change_answer, may_change,
                         "behavior.may_change_answer unexpected to be %s with %s"
                         % (not may_change, ", ".join(perms)))

    def get_flow_permissions_list(self, excluded=None):
        if not isinstance(excluded, list):
            excluded = [excluded]
        all_flow_permissions = dict(constants.FLOW_PERMISSION_CHOICES).keys()
        return [fp for fp in all_flow_permissions if fp not in excluded]

    def test_show_correctness1(self):
        # not expects_answer
        self.page.expects_answer.return_value = False

        combinations = [(frozenset([fp]), False) for fp in
                        self.get_flow_permissions_list()]
        combinations.append(([], False))

        params = list(itertools.product([True, False], repeat=5))

        for p in params:
            (session_in_progress, answer_was_graded, generate_grade,
             is_unenrooled_session, viewing_prior_version) = p
            for permissions, show in combinations:
                with self.subTest(
                        permissions=permissions):
                    behavior = flow.get_page_behavior(
                        self.page,
                        permissions=permissions,
                        session_in_progress=session_in_progress,
                        answer_was_graded=answer_was_graded,
                        generates_grade=generate_grade,
                        is_unenrolled_session=is_unenrooled_session,
                        viewing_prior_version=viewing_prior_version,
                    )
                self.assertShowCorrectness(behavior, permissions, show)

    def test_show_correctness2(self):
        # expects_answer, answer_was_graded
        self.page.expects_answer.return_value = True

        combinations = [(frozenset([fp]), False) for fp in
                        self.get_flow_permissions_list(
                            excluded=fperm.see_correctness)]
        combinations.append(([], False))
        combinations.append((frozenset([fperm.see_correctness]), True))

        params = list(itertools.product([True, False], repeat=4))

        for p in params:
            (session_in_progress, generate_grade,
             is_unenrooled_session, viewing_prior_version) = p

            for permissions, show in combinations:
                with self.subTest(permissions=permissions):
                    behavior = flow.get_page_behavior(
                        self.page,
                        permissions=permissions,
                        session_in_progress=session_in_progress,
                        answer_was_graded=True,
                        generates_grade=generate_grade,
                        is_unenrolled_session=is_unenrooled_session,
                        viewing_prior_version=viewing_prior_version,
                    )
                self.assertShowCorrectness(behavior, permissions, show)

    def test_show_correctness3(self):
        # expects_answer, answer was NOT graded
        self.page.expects_answer.return_value = True

        combinations = [(frozenset([fp]), False) for fp in
                        self.get_flow_permissions_list()]
        combinations.append(([], False))

        params = list(itertools.product([True, False], repeat=4))

        for p in params:
            (session_in_progress, generate_grade,
             is_unenrooled_session, viewing_prior_version) = p

            for permissions, show in combinations:
                with self.subTest(permissions=permissions):
                    behavior = flow.get_page_behavior(
                        self.page,
                        permissions=permissions,
                        session_in_progress=session_in_progress,
                        answer_was_graded=False,
                        generates_grade=generate_grade,
                        is_unenrolled_session=is_unenrooled_session,
                        viewing_prior_version=viewing_prior_version,
                    )
                self.assertShowCorrectness(behavior, permissions, show)

    def test_show_answer1(self):
        # not expects_answer
        self.page.expects_answer.return_value = False

        combinations = [(frozenset([fp]), False) for fp in
                        self.get_flow_permissions_list(
                            excluded=[
                                fperm.see_answer_before_submission,
                                fperm.see_answer_after_submission])]
        combinations.append(([], False))
        combinations.append(
            (frozenset([fperm.see_answer_before_submission]), True))
        combinations.append(
            (frozenset([fperm.see_answer_after_submission]), True))
        combinations.append(
            (frozenset([fperm.see_answer_after_submission,
                        fperm.see_answer_before_submission]), True))

        params = list(itertools.product([True, False], repeat=5))

        for p in params:
            (session_in_progress, generate_grade, answer_was_graded,
             is_unenrooled_session, viewing_prior_version) = p

            for permissions, show in combinations:
                with self.subTest(permissions=permissions):
                    behavior = flow.get_page_behavior(
                        self.page,
                        permissions=permissions,
                        session_in_progress=session_in_progress,
                        answer_was_graded=answer_was_graded,
                        generates_grade=generate_grade,
                        is_unenrolled_session=is_unenrooled_session,
                        viewing_prior_version=viewing_prior_version,
                    )
                    self.assertShowAnswer(behavior, permissions, show)

    def test_show_answer2(self):
        # expects_answer, answer was NOT graded
        self.page.expects_answer.return_value = True

        combinations = [(frozenset([fp]), False) for fp in
                        self.get_flow_permissions_list(
                            excluded=[
                                fperm.see_answer_before_submission])]
        combinations.append(([], False))
        combinations.append(
            (frozenset([fperm.see_answer_before_submission]), True))

        params = list(itertools.product([True, False], repeat=4))

        for p in params:
            (session_in_progress, generate_grade,
             is_unenrooled_session, viewing_prior_version) = p

            for permissions, show in combinations:
                with self.subTest(permissions=permissions):
                    behavior = flow.get_page_behavior(
                        self.page,
                        permissions=permissions,
                        session_in_progress=session_in_progress,
                        answer_was_graded=False,
                        generates_grade=generate_grade,
                        is_unenrolled_session=is_unenrooled_session,
                        viewing_prior_version=viewing_prior_version,
                    )
                    self.assertShowAnswer(behavior, permissions, show)

    def test_show_answer3(self):
        # expects_answer, answer was graded, session not in progress

        self.page.expects_answer.return_value = True

        combinations = [(frozenset([fp]), False) for fp in
                        self.get_flow_permissions_list(
                            excluded=[
                                fperm.see_answer_before_submission,
                                fperm.see_answer_after_submission])]
        combinations.append(([], False))

        # when session not in_progress, see_answer_after_submission dominates
        combinations.extend(
            [(frozenset([fp, fperm.see_answer_after_submission]), True)
             for fp in self.get_flow_permissions_list(
                excluded=fperm.see_answer_after_submission)])

        combinations.append(
            (frozenset([fperm.see_answer_before_submission]), True))
        combinations.append(
            (frozenset([fperm.see_answer_after_submission]), True))

        # see_answer_before_submission also dominates
        combinations.extend(
            [(frozenset([fp, fperm.see_answer_before_submission]), True)
             for fp in self.get_flow_permissions_list(
                excluded=fperm.see_answer_before_submission)])

        params = list(itertools.product([True, False], repeat=3))

        for p in params:
            (generate_grade, is_unenrooled_session, viewing_prior_version) = p

            for permissions, show in combinations:
                with self.subTest(permissions=permissions):
                    behavior = flow.get_page_behavior(
                        self.page,
                        permissions=permissions,
                        session_in_progress=False,
                        answer_was_graded=True,
                        generates_grade=generate_grade,
                        is_unenrolled_session=is_unenrooled_session,
                        viewing_prior_version=viewing_prior_version,
                    )
                    self.assertShowAnswer(behavior, permissions, show)

    def test_show_answer4(self):
        # expects_answer, answer was graded, session in progress

        self.page.expects_answer.return_value = True

        combinations = [(frozenset([fp]), False) for fp in
                        self.get_flow_permissions_list(
                            excluded=[
                                fperm.see_answer_before_submission,
                                fperm.see_answer_after_submission])]
        combinations.append(([], False))
        combinations.append(
            (frozenset([fperm.see_answer_before_submission]), True))

        combinations.append(
            (frozenset([fperm.see_answer_after_submission]), True))

        # if see_answer_before_submission dominate not present,
        # change_answer dominates
        combinations.extend(
            [(frozenset([fp, fperm.change_answer]), False) for fp in
             self.get_flow_permissions_list(
                 excluded=fperm.see_answer_before_submission)])

        # see_answer_before_submission dominates
        combinations.extend(
            [(frozenset([fp, fperm.see_answer_before_submission]), True)
             for fp in self.get_flow_permissions_list(
                excluded=fperm.see_answer_before_submission)])

        params = list(itertools.product([True, False], repeat=3))

        for p in params:
            (generate_grade, is_unenrooled_session, viewing_prior_version) = p

            for permissions, show in combinations:
                with self.subTest(permissions=permissions):
                    behavior = flow.get_page_behavior(
                        self.page,
                        permissions=permissions,
                        session_in_progress=True,
                        answer_was_graded=True,
                        generates_grade=generate_grade,
                        is_unenrolled_session=is_unenrooled_session,
                        viewing_prior_version=viewing_prior_version,
                    )
                    self.assertShowAnswer(behavior, permissions, show)

    def test_may_change_answer1(self):
        # viewing_prior_version dominates

        combinations = [(frozenset([fp]), False) for fp in
                        self.get_flow_permissions_list()]

        params = list(itertools.product([True, False], repeat=5))

        for p in params:
            (self.page.expects_answer.return_value,
             session_in_progress, answer_was_graded,
             generates_grade,
             is_unenrooled_session) = p

            for permissions, may_change in combinations:
                with self.subTest(permissions=permissions):
                    behavior = flow.get_page_behavior(
                        self.page,
                        permissions=permissions,
                        session_in_progress=session_in_progress,
                        answer_was_graded=answer_was_graded,
                        generates_grade=generates_grade,
                        is_unenrolled_session=is_unenrooled_session,
                        viewing_prior_version=True,
                    )
                    self.assertMayChangeAnswer(behavior, permissions, may_change)

    def test_may_change_answer2(self):
        # session_in_progress dominates

        combinations = [(frozenset([fp]), False) for fp in
                        self.get_flow_permissions_list()]

        params = list(itertools.product([True, False], repeat=4))

        for p in params:
            (self.page.expects_answer.return_value,
             answer_was_graded, generates_grade,
             is_unenrooled_session) = p

            for permissions, may_change in combinations:
                with self.subTest(permissions=permissions):
                    behavior = flow.get_page_behavior(
                        self.page,
                        permissions=permissions,
                        session_in_progress=False,
                        answer_was_graded=answer_was_graded,
                        generates_grade=generates_grade,
                        is_unenrolled_session=is_unenrooled_session,
                    )
                    self.assertMayChangeAnswer(behavior, permissions, may_change)

    def test_may_change_answer3(self):
        # no submit_answer dominates

        combinations = [(frozenset([fp]), False)
                        for fp in self.get_flow_permissions_list(
                excluded=fperm.submit_answer)]

        params = list(itertools.product([True, False], repeat=5))

        for p in params:
            (self.page.expects_answer.return_value,
             session_in_progress, answer_was_graded,
             generates_grade,
             is_unenrooled_session) = p

            for permissions, may_change in combinations:
                with self.subTest(permissions=permissions):
                    behavior = flow.get_page_behavior(
                        self.page,
                        permissions=permissions,
                        session_in_progress=session_in_progress,
                        answer_was_graded=answer_was_graded,
                        generates_grade=generates_grade,
                        is_unenrolled_session=is_unenrooled_session,
                    )
                    self.assertMayChangeAnswer(behavior, permissions, may_change)

    def test_may_change_answer4(self):
        # not answer_was_graded or (flow_permission.change_answer in permissions)

        combinations = [(frozenset([fp, fperm.submit_answer]), False)
                        for fp in self.get_flow_permissions_list(
                excluded=fperm.change_answer)]

        params = list(itertools.product([True, False], repeat=4))

        for p in params:
            (self.page.expects_answer.return_value,
             session_in_progress, generates_grade, is_unenrooled_session) = p

            for permissions, may_change in combinations:
                with self.subTest(permissions=permissions):
                    behavior = flow.get_page_behavior(
                        self.page,
                        permissions=permissions,
                        session_in_progress=session_in_progress,
                        answer_was_graded=True,
                        generates_grade=generates_grade,
                        is_unenrolled_session=is_unenrooled_session,
                    )
                    self.assertMayChangeAnswer(behavior, permissions, may_change)

    def test_may_change_answer6(self):
        # generates_grade and not is_unenrolled_session or (not generates_grade)

        combinations = [
            (frozenset([fp, fperm.submit_answer, fperm.change_answer]), False)
            for fp in self.get_flow_permissions_list()]

        params = list(itertools.product([True, False], repeat=1))

        for p in params:
            (self.page.expects_answer.return_value) = p

            for permissions, may_change in combinations:
                with self.subTest(permissions=permissions):
                    behavior = flow.get_page_behavior(
                        self.page,
                        permissions=permissions,
                        session_in_progress=True,
                        answer_was_graded=False,
                        generates_grade=True,
                        is_unenrolled_session=True,
                    )
                    self.assertMayChangeAnswer(behavior, permissions, may_change)

    def test_may_change_answer7(self):
        # cases that may_change_answer
        from collections import namedtuple
        Conf = namedtuple(
            "Conf", [
                'extra_fperms',
                'answer_was_graded',
                'generates_grade',
                'is_unenrolled_session',
            ]
        )

        confs = (
            Conf([], False, False, True),
            Conf([], False, False, False),
            Conf([fperm.change_answer], True, False, True),
            Conf([fperm.change_answer], True, False, False),
            Conf([fperm.change_answer], False, False, True),
            Conf([fperm.change_answer], False, False, False),
        )

        params = list(itertools.product([True, False], repeat=1))

        for conf in confs:
            combinations = []
            for fp in self.get_flow_permissions_list():
                fperms = [fp, fperm.submit_answer]
                if conf.extra_fperms:
                    fperms.extend(conf.extra_fperms)

                combinations.append((frozenset(fperms), True))

                for p in params:
                    (self.page.expects_answer.return_value) = p

                for permissions, may_change in combinations:
                    with self.subTest(
                            permissions=permissions,
                            answer_was_graded=conf.answer_was_graded,
                            generates_grade=conf.generates_grade,
                            is_unenrolled_session=conf.is_unenrolled_session):
                        behavior = flow.get_page_behavior(
                            self.page,
                            permissions=permissions,
                            session_in_progress=True,
                            answer_was_graded=conf.answer_was_graded,
                            generates_grade=conf.generates_grade,
                            is_unenrolled_session=conf.is_unenrolled_session,
                        )
                        self.assertMayChangeAnswer(behavior, permissions, may_change)


class AddButtonsToFormTest(unittest.TestCase):
    # test flow.add_buttons_to_form
    def setUp(self):
        super(AddButtonsToFormTest, self).setUp()
        self.flow_session = mock.MagicMock()
        self.fpctx = mock.MagicMock()

        fake_will_receive_feedback = mock.patch("course.flow.will_receive_feedback")
        self.mock_will_receive_feedback = fake_will_receive_feedback.start()
        self.addCleanup(fake_will_receive_feedback.stop)

    def fake_flow_session_page_count(self, count):
        self.flow_session.page_count = count

    def fake_fpctx_page_data_page_ordinal(self, ordinal):
        self.fpctx.page_data.page_ordinal = ordinal

    def get_flow_permissions_list(self, excluded=None):
        if not isinstance(excluded, list):
            excluded = [excluded]
        all_flow_permissions = dict(constants.FLOW_PERMISSION_CHOICES).keys()
        return [fp for fp in all_flow_permissions if fp not in excluded]

    def get_form_submit_inputs(self, form):
        from crispy_forms.layout import Submit
        inputs = [
            (input.name, input.value) for input in form.helper.inputs
            if isinstance(input, Submit)
        ]
        names = list(dict(inputs).keys())
        values = list(dict(inputs).values())
        return names, values

    def test_not_add_save_button(self):
        class MyForm(StyledForm):
            show_save_button = False

        form = MyForm()

        self.mock_will_receive_feedback.return_value = True
        flow.add_buttons_to_form(form, self.fpctx, self.flow_session, frozenset())

        names, values = self.get_form_submit_inputs(form)
        self.assertNotIn("save", names)
        self.assertIn("submit", names)
        self.assertIn("Submit final answer", values)

    def test_add_save_button_by_default(self):
        class MyForm(StyledForm):
            pass

        form = MyForm()

        self.mock_will_receive_feedback.return_value = True
        flow.add_buttons_to_form(form, self.fpctx, self.flow_session, frozenset())

        names, values = self.get_form_submit_inputs(form)
        self.assertIn("save", names)
        self.assertIn("submit", names)
        self.assertIn("Submit final answer", values)

    def test_add_submit_answer_for_feedback_button(self):
        form = StyledForm()

        self.mock_will_receive_feedback.return_value = True
        flow.add_buttons_to_form(
            form, self.fpctx, self.flow_session, frozenset([fperm.change_answer]))

        names, values = self.get_form_submit_inputs(form)
        self.assertIn("submit", names)
        self.assertIn("Submit answer for feedback", values)

    @unittest.skipIf(six.PY2, "PY2 doesn't support subTest")
    def test_not_add_submit_answer_for_feedback_button(self):

        self.mock_will_receive_feedback.return_value = True
        combinations = [(frozenset([fp]), False) for fp in
                        self.get_flow_permissions_list(excluded=fperm.change_answer)]
        combinations.append(([], False))

        form = StyledForm()
        for permissions, show in combinations:
            with self.subTest(
                    permissions=permissions):
                flow.add_buttons_to_form(
                    form, self.fpctx, self.flow_session, permissions)

            names, values = self.get_form_submit_inputs(form)
            self.assertNotIn("Submit answer for feedback", values)

    @unittest.skipIf(six.PY2, "PY2 doesn't support subTest")
    def test_add_save_and_next(self):

        self.mock_will_receive_feedback.return_value = False

        combinations = [(frozenset([fp]), True) for fp in
                        self.get_flow_permissions_list()]
        combinations.append(([], True))

        self.fake_flow_session_page_count(3)
        self.fake_fpctx_page_data_page_ordinal(1)

        form = StyledForm()
        for permissions, show in combinations:
            with self.subTest(
                    permissions=permissions):
                flow.add_buttons_to_form(
                    form, self.fpctx, self.flow_session, permissions)

            names, values = self.get_form_submit_inputs(form)
            self.assertIn("save_and_next", names)
            self.assertNotIn("submit", names)
            self.assertNotIn("save_and_finish", names)

    @unittest.skipIf(six.PY2, "PY2 doesn't support subTest")
    def test_add_save_and_finish(self):

        self.mock_will_receive_feedback.return_value = False

        combinations = [(frozenset([fp]), True) for fp in
                        self.get_flow_permissions_list()]
        combinations.append(([], True))

        self.fake_flow_session_page_count(3)
        self.fake_fpctx_page_data_page_ordinal(2)

        form = StyledForm()
        for permissions, show in combinations:
            with self.subTest(
                    permissions=permissions):
                flow.add_buttons_to_form(
                    form, self.fpctx, self.flow_session, permissions)