Skip to content
test_views.py 98 KiB
Newer Older
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
            excs.filter(
                kind=constants.flow_rule_kind.grading).count(), 1)
        description = excs[0].rule.get("description")
        self.assertIsNotNone(description)
        self.assertIn("89.1%", description)

        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith("Exception granted to ", reset=True)

    def test_grading_rule_generates_grade(self):
        # not generates_grade
        self.post_grant_exception_stage_3_view(
            data=self.get_default_post_data(
                # untick generates_grade
                create_grading_exception=True))

        self.assertEqual(self.mock_validate_session_grading_rule.call_count, 1)
        self.mock_validate_session_grading_rule.reset_mock()

        excs = models.FlowRuleException.objects.all()
        self.assertEqual(excs.count(), 1)
        self.assertEqual(
            excs.filter(
                kind=constants.flow_rule_kind.grading).count(), 1)
        generates_grade = excs[0].rule.get("generates_grade")
        self.assertFalse(generates_grade)

        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith("Exception granted to ", reset=True)

        # second, generates_grade
        self.post_grant_exception_stage_3_view(
            data=self.get_default_post_data(
                create_grading_exception=True, generates_grade=True))

        self.assertEqual(self.mock_validate_session_grading_rule.call_count, 1)

        excs = models.FlowRuleException.objects.all()
        self.assertEqual(excs.count(), 2)
        self.assertEqual(
            excs.filter(
                kind=constants.flow_rule_kind.grading).count(), 2)
        generates_grade = excs[1].rule.get("generates_grade")
        self.assertTrue(generates_grade)

        self.assertAddMessageCallCount(1)
        self.assertAddMessageCalledWith("Exception granted to ", reset=True)

    @unittest.skipIf(six.PY2, "PY2 doesn't support subTest")
    def test_grading_rule_item_set(self):
        from random import random
        items = ["credit_percent", "bonus_points", "max_points",
                 "max_points_enforced_cap"]
        for item in items:
            value = random() * 100
            with self.subTest(item=item):
                data = self.get_default_post_data(
                    create_grading_exception=True)
                data[item] = value

                resp = self.post_grant_exception_stage_3_view(data=data)
                self.assertRedirects(resp, self.get_grant_exception_url(),
                                     fetch_redirect_response=False)

                self.assertEqual(
                    self.mock_validate_session_grading_rule.call_count, 1)
                self.mock_validate_session_grading_rule.reset_mock()

                rule = models.FlowRuleException.objects.last().rule
                self.assertEqual(rule[item], value)
                for other_item in items:
                    if other_item != item:
                        self.assertEqual(rule.get(other_item), None)

    def test_create_grading_exception_restrict_to_same_tag(self):
        # restrict_to_same_tag, while session access_rules_tag is none
        flow_desc_access_rule_tags = ["fdesc_tag1", "fdesc_tag2"]
        hacked_flow_desc = self.get_hacked_flow_desc_with_access_rule_tags(
            flow_desc_access_rule_tags)

        with mock.patch("course.content.get_flow_desc") as mock_get_flow_desc:
            mock_get_flow_desc.return_value = hacked_flow_desc

            resp = self.post_grant_exception_stage_3_view(
                data=self.get_default_post_data(
                    create_grading_exception=True,
                    set_access_rules_tag=[flow_desc_access_rule_tags[1]],
                    restrict_to_same_tag=True
                ))

            self.assertFormErrorLoose(resp, None)
            self.assertRedirects(
                resp, self.get_grant_exception_url(),
                fetch_redirect_response=False)

            self.assertEqual(models.FlowRuleException.objects.count(), 1)
            self.assertEqual(
                models.FlowRuleException.objects.filter(
                    kind=constants.flow_rule_kind.grading).count(), 1)

            # the session had the same tag as in the grading rule
            self.fs.refresh_from_db()
            self.assertEqual(
                self.fs.access_rules_tag, flow_desc_access_rule_tags[1])

            exc_rule = models.FlowRuleException.objects.last().rule
            self.assertEqual(
                exc_rule.get("if_has_tag"), flow_desc_access_rule_tags[1])

    # }}}

    def test_form_invalid(self):
        with mock.patch(
                "course.views.ExceptionStage3Form.is_valid") as mock_is_valid:
            mock_is_valid.return_value = False
            resp = self.post_grant_exception_stage_3_view(
                data=self.get_default_post_data())
            self.assertEqual(resp.status_code, 200)

            self.assertEqual(models.FlowRuleException.objects.count(), 0)
            self.assertEqual(self.mock_validate_session_access_rule.call_count, 0)
            self.assertEqual(self.mock_validate_session_grading_rule.call_count, 0)


# {{{ test views.monitor_task

PYTRACEBACK = """\
Traceback (most recent call last):
  File "foo.py", line 2, in foofunc
    don't matter
  File "bar.py", line 3, in barfunc
    don't matter
Doesn't matter: really!\
"""


class MonitorTaskTest(SingleCourseTestMixin, TestCase):
    # test views.monitor_task
    def mock_task(self, name, state, result, traceback=None):
        return {
            'id': uuid(), 'name': name, 'state': state,
            'result': result, 'traceback': traceback,
        }

    def save_result(self, app, task):
        traceback = task.get('traceback') or 'Some traceback'
        state = task['state']
        if state == states.SUCCESS:
            app.backend.mark_as_done(task['id'], task['result'])
        elif state == states.RETRY:
            app.backend.mark_as_retry(
                task['id'], task['result'], traceback=traceback,
            )
        elif state == states.FAILURE:
            app.backend.mark_as_failure(
                task['id'], task['result'], traceback=traceback)
        elif state == states.REVOKED:
            app.backend.mark_as_revoked(
                task_id=task['id'], reason="blabla", state=state)
        elif state == states.STARTED:
            app.backend.mark_as_started(task['id'], **task['result'])
        else:
            app.backend.store_result(
                task['id'], task['result'], state,
            )

    def get_monitor_url(self, task_id):
        from django.urls import reverse
        return reverse("relate-monitor_task", kwargs={"task_id": task_id})

    def get_monitor_view(self, task_id):
        return self.c.get(self.get_monitor_url(task_id))

    def test_user_not_authenticated(self):
        message = "This is good!"
        task = self.mock_task('task', states.SUCCESS, {"message": message})
        self.save_result(app, task)
        with self.temporarily_switch_to_user(None):
            resp = self.get_monitor_view(task['id'])
        self.assertEqual(resp.status_code, 302)

    def test_state_success(self):
        message = "This is good!"
        task = self.mock_task('task', states.SUCCESS, {"message": message})
        self.save_result(app, task)
        resp = self.get_monitor_view(task['id'])
        self.assertEqual(resp.status_code, 200)
        self.assertResponseContextEqual(resp, "state", task['state'])
        self.assertResponseContextEqual(resp, "progress_statement", message)
        self.assertResponseContextIsNone(resp, "progress_percent")
        self.assertResponseContextIsNone(resp, "traceback")

    def test_state_success_result_not_dict(self):
        task = self.mock_task('task', states.SUCCESS, "This is good!")
        self.save_result(app, task)
        resp = self.get_monitor_view(task['id'])
        self.assertEqual(resp.status_code, 200)
        self.assertResponseContextEqual(resp, "state", task['state'])
        self.assertResponseContextIsNone(resp, "progress_percent")
        self.assertResponseContextIsNone(resp, "progress_statement")
        self.assertResponseContextIsNone(resp, "traceback")

    def test_state_success_result_contains_no_message(self):
        task = self.mock_task('task', states.SUCCESS, {"log": "This is good!"})
        self.save_result(app, task)
        resp = self.get_monitor_view(task['id'])
        self.assertEqual(resp.status_code, 200)
        self.assertResponseContextEqual(resp, "state", task['state'])
        self.assertResponseContextIsNone(resp, "progress_percent")
        self.assertResponseContextIsNone(resp, "progress_statement")
        self.assertResponseContextIsNone(resp, "traceback")

    def test_state_progress(self):
        task = self.mock_task("progressing", "PROGRESS",
                         {'current': 20, 'total': 40})
        self.save_result(app, task)
        resp = self.get_monitor_view(task['id'])
        self.assertEqual(resp.status_code, 200)
        self.assertResponseContextEqual(resp, "state", task['state'])
        self.assertResponseContextEqual(resp, "progress_percent", 50)
        self.assertResponseContextEqual(
            resp, "progress_statement", "20 out of 40 items processed.")
        self.assertResponseContextIsNone(resp, "traceback")

    def test_state_progress_total_zero(self):
        task = self.mock_task("progressing", "PROGRESS",
                         {'current': 0, 'total': 0})
        self.save_result(app, task)
        resp = self.get_monitor_view(task['id'])
        self.assertEqual(resp.status_code, 200)
        self.assertResponseContextEqual(resp, "state", task['state'])
        self.assertResponseContextIsNone(resp, "progress_percent")
        self.assertResponseContextEqual(
            resp, "progress_statement", "0 out of 0 items processed.")
        self.assertResponseContextIsNone(resp, "traceback")

    def test_state_failure(self):
        self.instructor_participation.user.is_staff = True
        self.instructor_participation.user.save()
        task = self.mock_task("failure", states.FAILURE,
                              KeyError("foo"),
                              PYTRACEBACK)
        self.save_result(app, task)
        with self.temporarily_switch_to_user(self.superuser):
            resp = self.get_monitor_view(task['id'])
        self.assertEqual(resp.status_code, 200)
        self.assertResponseContextEqual(resp, "state", task['state'])
        self.assertResponseContextIsNone(resp, "progress_percent")
        self.assertResponseContextIsNone(resp, "progress_statement")
        self.assertResponseContextEqual(resp, "traceback", PYTRACEBACK)

    def test_state_failure_request_user_not_staff(self):
        task = self.mock_task("failure", states.FAILURE,
                              KeyError("foo"),
                              PYTRACEBACK)
        self.save_result(app, task)
        resp = self.get_monitor_view(task['id'])

        self.assertEqual(resp.status_code, 200)
        self.assertResponseContextEqual(resp, "state", task['state'])
        self.assertResponseContextIsNone(resp, "progress_percent")
        self.assertResponseContextIsNone(resp, "progress_statement")
        self.assertResponseContextIsNone(resp, "traceback")

    def test_pending(self):
        state = states.PENDING
        task = self.mock_task("task", state,
                              {'current': 20, 'total': 40})
        self.save_result(app, task)
        resp = self.get_monitor_view(task['id'])
        self.assertEqual(resp.status_code, 200)
        self.assertResponseContextEqual(resp, "state", state)
        self.assertResponseContextIsNone(resp, "progress_percent")
        self.assertResponseContextIsNone(resp, "progress_statement")
        self.assertResponseContextIsNone(resp, "traceback")

    def test_received(self):
        state = states.RECEIVED
        task = self.mock_task("task", state,
                              {'current': 20, 'total': 40})
        self.save_result(app, task)
        resp = self.get_monitor_view(task['id'])
        self.assertEqual(resp.status_code, 200)
        self.assertResponseContextEqual(resp, "state", state)
        self.assertResponseContextIsNone(resp, "progress_percent")
        self.assertResponseContextIsNone(resp, "progress_statement")
        self.assertResponseContextIsNone(resp, "traceback")

    def test_started(self):
        state = states.STARTED
        task = self.mock_task("task", state,
                              {'foo': "foo", 'bar': "bar"})
        self.save_result(app, task)
        resp = self.get_monitor_view(task['id'])
        self.assertEqual(resp.status_code, 200)
        self.assertResponseContextEqual(resp, "state", state)
        self.assertResponseContextIsNone(resp, "progress_percent")
        self.assertResponseContextIsNone(resp, "progress_statement")
        self.assertResponseContextIsNone(resp, "traceback")

    def test_retry(self):
        state = states.RETRY
        task = self.mock_task("task", state,
                              KeyError())
        self.save_result(app, task)
        resp = self.get_monitor_view(task['id'])
        self.assertEqual(resp.status_code, 200)
        self.assertResponseContextEqual(resp, "state", state)
        self.assertResponseContextIsNone(resp, "progress_percent")
        self.assertResponseContextIsNone(resp, "progress_statement")
        self.assertResponseContextIsNone(resp, "traceback")

    def test_revoked(self):
        state = states.REVOKED
        task = self.mock_task("task", state, {})
        self.save_result(app, task)
        resp = self.get_monitor_view(task['id'])
        self.assertEqual(resp.status_code, 200)
        self.assertResponseContextEqual(resp, "state", state)
        self.assertResponseContextIsNone(resp, "progress_percent")
        self.assertResponseContextIsNone(resp, "progress_statement")
        self.assertResponseContextIsNone(resp, "traceback")

# }}}

Dong Zhuang's avatar
Dong Zhuang committed
# vim: fdm=marker