Skip to content
test_utils.py 73.1 KiB
Newer Older
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
            fake_login_exam_ticket
        )

    def test_not_passing_eval_participation_tags_conditions(self):
        self.mock_get_flow_rules.return_value = [mock.MagicMock()]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = False
        result = self.get_result()
        self.assertRuleEqual(self.fallback_rule, result)

    def test_not_passing_not_for_rollover_and_if_in_facility(self):
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"if_in_facility": "f1"})]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result(facilities=frozenset(["f2"]))
        self.assertRuleEqual(self.fallback_rule, result)

    def test_not_passing_not_for_rollover_and_if_has_in_progress_session(self):
        factories.FlowSessionFactory(
            participation=self.student_participation, flow_id=self.flow_id)
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"if_in_facility": "f1",
                            "if_has_in_progress_session": 2})]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result(facilities=frozenset(["f1", "f2"]))
        self.assertRuleEqual(self.fallback_rule, result)

    def test_not_passing_not_for_rollover_and_if_has_session_tagged(self):
        factories.FlowSessionFactory(
            participation=self.student_participation, flow_id=self.flow_id,
            in_progress=True)
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"if_has_in_progress_session": 1,
                            "if_has_session_tagged": "atag1"})]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result()
        self.assertRuleEqual(self.fallback_rule, result)

    def test_not_passing_not_for_rollover_and_if_has_fewer_sessions_than(self):
        factories.FlowSessionFactory(
            participation=self.student_participation, flow_id=self.flow_id,
            access_rules_tag="atag1"
        )
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"if_has_session_tagged": "atag1",
                            "if_has_fewer_sessions_than": 1})]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result()
        self.assertRuleEqual(self.fallback_rule, result)

    def test_not_passing_not_for_rollover_and_if_has_fewer_tagged_sessions_than(self):  # noqa
        factories.FlowSessionFactory.create_batch(size=2,
            participation=self.student_participation, flow_id=self.flow_id,
            access_rules_tag="atag1")
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"if_has_fewer_sessions_than": 3,
                            "if_has_fewer_tagged_sessions_than": 1})]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result()
        self.assertRuleEqual(self.fallback_rule, result)

    def test_passing_not_for_rollover_and_if_has_fewer_tagged_sessions_than(self):  # noqa
        factories.FlowSessionFactory.create_batch(size=2,
            participation=self.student_participation, flow_id=self.flow_id,
            access_rules_tag="atag1")
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"if_has_fewer_tagged_sessions_than": 3})]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result()
        self.assertRuleEqual(
            result,
            {"tag_session": None,
            "may_start_new_session": True,
            "may_list_existing_sessions": True,
            "default_expiration_mode": None}
        )

    def test_passing_not_for_rollover(self):
        factories.FlowSessionFactory.create_batch(size=2,
            participation=self.student_participation, flow_id=self.flow_id)
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({})]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result()
        self.assertRuleEqual(
            result,
            {"tag_session": None,
            "may_start_new_session": True,
            "may_list_existing_sessions": True,
            "default_expiration_mode": None}
        )

    def test_passing_for_rollover(self):
        factories.FlowSessionFactory.create_batch(size=2,
            participation=self.student_participation, flow_id=self.flow_id)
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({})]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result(for_rollover=True)
        self.assertRuleEqual(
            result,
            {"tag_session": None,
            "may_start_new_session": True,
            "may_list_existing_sessions": True,
            "default_expiration_mode": None}
        )

    def test_get_expected_rule(self):
        tag_session = mock.MagicMock()
        default_expiration_mode = mock.MagicMock()
        may_start_new_session = mock.MagicMock()
        may_list_existing_sessions = mock.MagicMock()
        self.mock_get_flow_rules.return_value = [
            dict_to_struct(
                {"tag_session": tag_session,
                 "default_expiration_mode": default_expiration_mode,
                 "may_start_new_session": may_start_new_session,
                 "may_list_existing_sessions": may_list_existing_sessions
                 })]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True

        # simplified
        result = self.get_result(for_rollover=True)
        self.assertRuleEqual(
            result,
            {"tag_session": tag_session,
             "may_start_new_session": may_start_new_session,
             "may_list_existing_sessions": may_list_existing_sessions,
             "default_expiration_mode": default_expiration_mode}
        )


class GetSessionAccessRuleTest(GetSessionRuleMixin, SingleCourseTestMixin, TestCase):
    # test utils.get_session_access_rule
    call_func = utils.get_session_access_rule
    rule_klass = utils.FlowSessionAccessRule

    fallback_rule = utils.FlowSessionAccessRule(permissions=frozenset())
    default_permissions = [fperm.view]

    @property
    def default_kwargs(self):
        return {
            "session": self.fs1,
            "flow_desc": mock.MagicMock(),
            "now_datetime": self.now,
            "facilities": None,
            "login_exam_ticket": None,
        }

    @classmethod
    def setUpTestData(cls):  # noqa
        super(GetSessionAccessRuleTest, cls).setUpTestData()

        cls.now = now() - timedelta(days=1)

        start_time = cls.now - timedelta(minutes=60)

        cls.ta_participation.time_factor = 1.1
        cls.ta_participation.save()

        cls.fs1 = factories.FlowSessionFactory(
            participation=cls.student_participation, in_progress=False,
            expiration_mode=constants.flow_session_expiration_mode.end,
            start_time=start_time
        )
        cls.fs2 = factories.FlowSessionFactory(
            participation=cls.ta_participation, in_progress=True,
            expiration_mode=constants.flow_session_expiration_mode.roll_over,
            start_time=start_time
        )
        cls.fs3 = factories.FlowSessionFactory(
            course=cls.course,
            participation=None, in_progress=True, user=None,
            expiration_mode=constants.flow_session_expiration_mode.roll_over,
            start_time=start_time
        )

    def get_result(self, **extra_kwargs):
        kwargs = self.get_updated_kwargs(**extra_kwargs)
        return utils.get_session_access_rule(**kwargs)

    def get_default_rule(self, **kwargs):
        defaults = {
            "permissions": self.default_permissions[:],
            "message": None,
        }
        defaults.update(kwargs)
        return utils.FlowSessionAccessRule(**defaults)

    def test_no_rules(self):
        self.mock_get_flow_rules.return_value = []
        result = self.get_result()
        self.assertRuleEqual(self.fallback_rule, result)

        # make sure get_flow_rules is called with expected default_rules_desc
        self.assertEqual(self.mock_get_flow_rules.call_count, 1)
        self.assertIn("default_rules_desc", self.mock_get_flow_rules.call_args[1])

        default_rules_desc = (
            self.mock_get_flow_rules.call_args[1]["default_rules_desc"])
        self.assertEqual(
            default_rules_desc[0].permissions, self.default_permissions)

    def test_not_passing_eval_generic_conditions(self):
        self.mock_get_flow_rules.return_value = [mock.MagicMock()]
        self.mock_eval_generic_conditions.return_value = False

        fake_login_exam_ticket = mock.MagicMock()
        result = self.get_result(login_exam_ticket=fake_login_exam_ticket)
        self.assertRuleEqual(self.fallback_rule, result)

        # make sure _eval_generic_conditions is called with expected
        # login_exam_ticket
        self.assertEqual(self.mock_eval_generic_conditions.call_count, 1)
        self.assertIn("login_exam_ticket",
                      self.mock_eval_generic_conditions.call_args[1])

        self.assertEqual(
            self.mock_eval_generic_conditions.call_args[1]["login_exam_ticket"],
            fake_login_exam_ticket
        )

    def test_not_passing_eval_participation_tags_conditions(self):
        self.mock_get_flow_rules.return_value = [mock.MagicMock()]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = False
        result = self.get_result()
        self.assertRuleEqual(self.fallback_rule, result)

    def test_not_passing_eval_generic_session_conditions(self):
        self.mock_get_flow_rules.return_value = [mock.MagicMock()]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        self.mock_eval_generic_session_conditions.return_value = False
        result = self.get_result()
        self.assertRuleEqual(self.fallback_rule, result)

    def test_not_passing_if_in_facility(self):
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"if_in_facility": "f1",
                            "permissions": mock.MagicMock()
                            })]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result(facilities=frozenset(["f2"]))
        self.assertRuleEqual(self.fallback_rule, result)

    def test_not_passing_if_in_progress(self):
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"if_in_facility": "f1",
                            "if_in_progress": True,
                            "permissions": mock.MagicMock()
                            })]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result(facilities=frozenset(["f1", "f2"]))
        self.assertRuleEqual(self.fallback_rule, result)

    def test_not_passing_if_expiration_mode(self):
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"if_in_progress": True,
                            "if_expiration_mode":
                                constants.flow_session_expiration_mode.end,
                            "permissions": mock.MagicMock()
                            })]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result(session=self.fs2)
        self.assertRuleEqual(self.fallback_rule, result)

    def test_not_passing_if_session_duration_shorter_than_minutes(self):
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"if_expiration_mode":
                                constants.flow_session_expiration_mode.end,
                            "if_session_duration_shorter_than_minutes": 59,
                            "permissions": mock.MagicMock()
                            })]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result()
        self.assertRuleEqual(self.fallback_rule, result)

    def test_not_passing_if_session_duration_shorter_than_minutes_anonymous(self):
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"if_session_duration_shorter_than_minutes": 59,
                            "permissions": mock.MagicMock()
                            })]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result(session=self.fs3)
        self.assertRuleEqual(self.fallback_rule, result)

    def test_passed_session_duration_shorter_than_minutes(self):
        faked_permissions = frozenset([mock.MagicMock()])
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"if_session_duration_shorter_than_minutes": 59,
                            "permissions": faked_permissions})]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result(session=self.fs2)
        self.assertRuleEqual(
            result,
            {"message": None,
             "permissions": faked_permissions})

    def test_with_above_not_considiered(self):
        faked_permissions = frozenset([mock.MagicMock()])
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"permissions": faked_permissions})]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result(session=self.fs2)
        self.assertRuleEqual(
            result,
            {"message": None,
             "permissions": faked_permissions})

    def test_deal_with_deprecated_modify(self):
        faked_permission = mock.MagicMock()
        self.mock_get_flow_rules.return_value = [
            dict_to_struct(
                {"permissions": frozenset(["modify", faked_permission])})]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result(session=self.fs2)

        self.assertRuleEqual(
            result,
            {"message": None,
             "permissions": frozenset(
                 [fperm.submit_answer, fperm.end_session, faked_permission])})

    def test_deal_with_deprecated_see_answer(self):
        faked_permission = mock.MagicMock()
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({
                "permissions": frozenset([
                    "see_answer", faked_permission])})]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result(session=self.fs2)
        self.assertRuleEqual(
            result,
            {"message": None,
             "permissions": frozenset(
                 [faked_permission, fperm.see_answer_after_submission])})

    def test_removing_access_permissions_for_non_in_progress_sessions(self):
        faked_permission = mock.MagicMock()
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({
                "permissions": frozenset([
                    "modify", faked_permission])})]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result()
        self.assertRuleEqual(
            result,
            {"message": None,
             "permissions": frozenset(
                 [faked_permission])})

        self.mock_get_flow_rules.return_value = [
            dict_to_struct({
                "permissions": frozenset([
                    "end_session", faked_permission])})]
        self.mock_eval_generic_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = True
        result = self.get_result()
        self.assertRuleEqual(
            result,
            {"message": None,
             "permissions": frozenset(
                 [faked_permission])})


class GetSessionGradingRuleTest(GetSessionRuleMixin,
                                SingleCourseTestMixin, TestCase):
    # test utils.get_session_grading_rule
    call_func = utils.get_session_grading_rule
    rule_klass = utils.FlowSessionGradingRule

    no_g_rule_exception_msg = (
        "grading rule determination was unable to find a grading rule")

    fallback_rule = None
    default_rule = {"generates_grade": False}

    @property
    def default_kwargs(self):
        return {
            "session": self.fs1,
            "flow_desc": mock.MagicMock(),
            "now_datetime": self.now,
        }

    @classmethod
    def setUpTestData(cls):  # noqa
        super(GetSessionGradingRuleTest, cls).setUpTestData()

        cls.now = now() - timedelta(days=1)

        start_time = cls.now - timedelta(minutes=60)

        cls.fs1 = factories.FlowSessionFactory(
            participation=cls.student_participation, in_progress=False,
            expiration_mode=constants.flow_session_expiration_mode.end,
            start_time=start_time, completion_time=cls.now
        )
        cls.fs2 = factories.FlowSessionFactory(
            participation=cls.ta_participation, in_progress=True,
            expiration_mode=constants.flow_session_expiration_mode.roll_over,
            start_time=start_time
        )
        cls.fs3 = factories.FlowSessionFactory(
            course=cls.course,
            participation=None, in_progress=True, user=None,
            expiration_mode=constants.flow_session_expiration_mode.roll_over,
            start_time=start_time, completion_time=cls.now
        )

    def get_result(self, **extra_kwargs):
        kwargs = self.get_updated_kwargs(**extra_kwargs)
        return utils.get_session_grading_rule(**kwargs)

    def get_default_rule(self, **kwargs):
        defaults = {
            "grade_identifier": "la_quiz",
            "grade_aggregation_strategy":
                constants.grade_aggregation_strategy.use_latest,
            "due": None,
            "generates_grade": True,
            "description": None,
            "credit_percent": 100,
            "use_last_activity_as_completion_time": False,
            "max_points": None,
            "max_points_enforced_cap": None,
            "bonus_points": 0
        }
        defaults.update(kwargs)
        return utils.FlowSessionGradingRule(**defaults)

    def test_no_rules(self):
        self.mock_get_flow_rules.return_value = []

        with self.assertRaises(RuntimeError) as cm:
            self.get_result()
        self.assertIn(self.no_g_rule_exception_msg, str(cm.exception))

        # make sure get_flow_rules is called with expected default_rules_desc
        self.assertEqual(self.mock_get_flow_rules.call_count, 1)
        self.assertIn("default_rules_desc", self.mock_get_flow_rules.call_args[1])

        default_rules_desc = (
            self.mock_get_flow_rules.call_args[1]["default_rules_desc"])
        self.assertFalse(default_rules_desc[0].generates_grade)

    def test_skip_if_has_role(self):
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"if_has_role": ["instructor", "ta"]})]

        with self.assertRaises(RuntimeError) as cm:
            self.get_result()
        self.assertIn(self.no_g_rule_exception_msg, str(cm.exception))

    def test_passed_if_has_role(self):
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"if_has_role": ["instructor", "ta"]}),
            dict_to_struct({"if_has_role": ["instructor", "ta", "student"]})]

        result = self.get_result(flow_desc=self.get_hacked_flow_desc())
        self.assertRuleEqual(result, self.get_default_rule())

    def test_not_passing_eval_generic_session_conditions(self):
        self.mock_get_flow_rules.return_value = [dict_to_struct({})]
        self.mock_eval_generic_session_conditions.return_value = False
        self.mock_eval_participation_tags_conditions.return_value = True
        with self.assertRaises(RuntimeError) as cm:
            self.get_result(flow_desc=self.get_hacked_flow_desc())
        self.assertIn(self.no_g_rule_exception_msg, str(cm.exception))

    def test_not_passing_eval_participation_tags_conditions(self):
        self.mock_get_flow_rules.return_value = [dict_to_struct({})]
        self.mock_eval_generic_session_conditions.return_value = True
        self.mock_eval_participation_tags_conditions.return_value = False
        with self.assertRaises(RuntimeError) as cm:
            self.get_result(flow_desc=self.get_hacked_flow_desc())
        self.assertIn(self.no_g_rule_exception_msg, str(cm.exception))

    def test_if_completed_before_skipped(self):
        self.mock_get_flow_rules.return_value = [dict_to_struct({
            "if_completed_before": "my_test_event 1"
        })]
        with self.assertRaises(RuntimeError) as cm:
            self.get_result(flow_desc=self.get_hacked_flow_desc())
        self.assertIn(self.no_g_rule_exception_msg, str(cm.exception))

    def test_if_completed_before_in_progress_session_skipped(self):
        self.mock_get_flow_rules.return_value = [dict_to_struct({
            "if_completed_before": "my_test_event 1"
        })]
        with self.assertRaises(RuntimeError) as cm:
            self.get_result(
                session=self.fs2,
                flow_desc=self.get_hacked_flow_desc())
        self.assertIn(self.no_g_rule_exception_msg, str(cm.exception))

    def test_if_completed_before_passed_not_using_last_activity(self):
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({"if_completed_before": "my_test_event 1"}),
            dict_to_struct({"if_completed_before": "my_test_event 2"}),
        ]
        result = self.get_result(flow_desc=self.get_hacked_flow_desc())
        self.assertRuleEqual(result, self.get_default_rule())

    def test_if_completed_before_using_last_activity_with_last_activity_none_skipped(self):  # noqa
        self.mock_get_flow_rules.return_value = [
            dict_to_struct(
                {"if_completed_before": "my_test_event 1",
                 "use_last_activity_as_completion_time": True
                 }),
        ]
        with self.assertRaises(RuntimeError) as cm:
            self.get_result(flow_desc=self.get_hacked_flow_desc())
        self.assertIn(self.no_g_rule_exception_msg, str(cm.exception))

    def test_if_completed_before_using_last_activity_exist_but_skipped(self):
        # create last_activity
        page_data = factories.FlowPageDataFactory(flow_session=self.fs1)
        factories.FlowPageVisitFactory(
            page_data=page_data,
            visit_time=my_test_event_1_time + timedelta(hours=1),
            answer={"answer": "hi"})

        self.mock_get_flow_rules.return_value = [
            dict_to_struct(
                {"if_completed_before": "my_test_event 1",
                 "use_last_activity_as_completion_time": True
                 }),
        ]
        with self.assertRaises(RuntimeError) as cm:
            self.get_result(flow_desc=self.get_hacked_flow_desc())
        self.assertIn(self.no_g_rule_exception_msg, str(cm.exception))

    def test_if_completed_before_using_last_activity_exist_passed(self):
        # create last_activity
        page_data = factories.FlowPageDataFactory(flow_session=self.fs1)
        factories.FlowPageVisitFactory(
            page_data=page_data,
            visit_time=my_test_event_1_time - timedelta(hours=1),
            answer={"answer": "hi"})

        self.mock_get_flow_rules.return_value = [
            dict_to_struct(
                {"if_completed_before": "my_test_event 1",
                 "use_last_activity_as_completion_time": True
                 }),
        ]
        result = self.get_result(flow_desc=self.get_hacked_flow_desc())
        self.assertRuleEqual(
            result, self.get_default_rule(
                use_last_activity_as_completion_time=True))

    def test_params_in_passed_to_result(self):
        # rule params
        mock_bonus_points = mock.MagicMock()
        mock_max_points = mock.MagicMock()
        mock_max_points_enforced_cap = mock.MagicMock()

        mock_generates_grade = mock.MagicMock()
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({
                "generates_grade": mock_generates_grade,
                "bonus_poinsts": mock_bonus_points,
                "max_points": mock_max_points,
                "max_points_enforced_cap": mock_max_points_enforced_cap,
                "due": "my_mock_event_time"
            })]

        # flow_desc_params
        mock_flow_desc_grade_identifier = mock.MagicMock()
        mock_flow_desc_grade_aggregation_strategy = mock.MagicMock()

        result = self.get_result(flow_desc=self.get_hacked_flow_desc(
            rules=dict_to_struct({
                "grade_identifier": mock_flow_desc_grade_identifier,
                "grade_aggregation_strategy":
                    mock_flow_desc_grade_aggregation_strategy})))

        self.assertRuleEqual(result, self.get_default_rule(
            max_points=mock_max_points,
            max_points_enforced_cap=mock_max_points_enforced_cap,
            generates_grade=mock_generates_grade,
            grade_identifier=mock_flow_desc_grade_identifier,
            grade_aggregation_strategy=mock_flow_desc_grade_aggregation_strategy,
            due=my_mock_event_time
        ))

    def test_no_flow_desc_rule(self):
        self.mock_get_flow_rules.return_value = [
            dict_to_struct({})]

        result = self.get_result(
            flow_desc=self.get_hacked_flow_desc(del_rules=True))
        self.assertRuleEqual(result, self.get_default_rule(
            grade_identifier=None,
            grade_aggregation_strategy=None,
            bonus_points=0,
            max_points=None,
            max_points_enforced_cap=None,
        ))


Dong Zhuang's avatar
Dong Zhuang committed
class CoursePageContextTest(SingleCourseTestMixin, MockAddMessageMixing, TestCase):
    # test utils.CoursePageContext (for cases not covered by other tests)

    def setUp(self):
        super(CoursePageContextTest, self).setUp()
        rf = RequestFactory()
        self.request = rf.get(self.get_course_page_url())

    def test_preview_commit_sha(self):
        # commit_sha of https://github.com/inducer/relate-sample/pull/11
        commit_sha = "ec41a2de73a99e6022060518cb5c5c162b88cdf5"
        self.ta_participation.preview_git_commit_sha = commit_sha
        self.ta_participation.save()
        self.request.user = self.ta_participation.user
        pctx = utils.CoursePageContext(self.request, self.course.identifier)

        self.assertEqual(
            pctx.course_commit_sha,
            commit_sha.encode())

Dong Zhuang's avatar
Dong Zhuang committed
        self.assertAddMessageCallCount(0)

    def test_invalid_preview_commit_sha(self):
        commit_sha = "invalid_commit_sha"
        self.ta_participation.preview_git_commit_sha = commit_sha
        self.ta_participation.save()
        self.request.user = self.ta_participation.user
        pctx = utils.CoursePageContext(self.request, self.course.identifier)

        self.assertEqual(
            pctx.course_commit_sha,
            self.course.active_git_commit_sha.encode())

Dong Zhuang's avatar
Dong Zhuang committed
        self.assertAddMessageCallCount(1)
        expected_error_msg = (
                "Preview revision '%s' does not exist--"
                "showing active course content instead." % commit_sha)

Dong Zhuang's avatar
Dong Zhuang committed
        self.assertAddMessageCalledWith(expected_error_msg)

    def test_role_identifiers(self):
        self.request.user = self.ta_participation.user
        pctx = utils.CoursePageContext(self.request, self.course.identifier)
        self.assertEqual(pctx.role_identifiers(), ['ta'])

        with mock.patch(
                "course.enrollment.get_participation_role_identifiers"
        ) as mock_get_prole_identifiers:
            self.assertEqual(pctx.role_identifiers(), ['ta'])

            # This is to ensure _role_identifiers_cache is working
            self.assertEqual(mock_get_prole_identifiers.call_count, 0)

    def test_error_when_nestedly_use_pctx_as_context_manager(self):
        self.request.user = self.ta_participation.user
        pctx = utils.CoursePageContext(self.request, self.course.identifier)

        with self.assertRaises(RuntimeError) as cm:
            with pctx:
                with pctx:
                    pass

        expected_error_msg = (
            "Nested use of 'course_view' as context manager "
            "is not allowed.")

        self.assertIn(expected_error_msg, str(cm.exception))


class FlowContextTest(unittest.TestCase):
    # test utils.FlowContext (for cases not covered by other tests)
    def test_404(self):
        repo = mock.MagicMock()
        course = mock.MagicMock()
        flow_id = "some_id"
        participation = mock.MagicMock()

        with mock.patch(
                "course.utils.get_course_commit_sha"), mock.patch(
                "course.utils.get_flow_desc") as mock_get_flow_desc:
            from django.core.exceptions import ObjectDoesNotExist
            mock_get_flow_desc.side_effect = ObjectDoesNotExist

            from django import http
            with self.assertRaises(http.Http404):
                utils.FlowContext(repo, course, flow_id, participation)


class ParticipationPermissionWrapperTest(SingleCourseTestMixin, TestCase):
    # test utils.ParticipationPermissionWrapper (for cases not covered
    # by other tests)

    def setUp(self):
        super(ParticipationPermissionWrapperTest, self).setUp()
        rf = RequestFactory()
        request = rf.get(self.get_course_page_url())
        request.user = self.ta_participation.user
        self.pctx = utils.CoursePageContext(request, self.course.identifier)

    def test_get_invalid_permission(self):
        ppwraper = utils.ParticipationPermissionWrapper(self.pctx)
        invalid_perm = "invalid_perm"
        with self.assertRaises(ValueError) as cm:
            ppwraper[invalid_perm]

        expected_error_msg = (
            "permission name '%s' not valid" % invalid_perm)

        self.assertIn(expected_error_msg, str(cm.exception))

    def test_not_iterale(self):
        ppwraper = utils.ParticipationPermissionWrapper(self.pctx)
        with self.assertRaises(TypeError) as cm:
            iter(ppwraper)

        expected_error_msg = (
            "ParticipationPermissionWrapper is not iterable.")

        self.assertIn(expected_error_msg, str(cm.exception))


class GetCodemirrorWidgetTest(unittest.TestCase):
    # test utils.get_codemirror_widget (for cases not covered by other tests)
    def setUp(self):
        self.language_mode = "python"
        fake_code_mirror_textarea = mock.patch("codemirror.CodeMirrorTextarea")
        self.mock_code_mirror_textarea = fake_code_mirror_textarea.start()
        self.addCleanup(fake_code_mirror_textarea.stop)

    def test_interaction_mode_vim(self):
        interaction_mode = "vim"
        utils.get_codemirror_widget(
            self.language_mode, interaction_mode=interaction_mode)

        addon_js = self.mock_code_mirror_textarea.call_args[1]["addon_js"]
        self.assertIn("../keymap/vim", addon_js)

        config = self.mock_code_mirror_textarea.call_args[1]["config"]
        self.assertEqual(config["vimMode"], True)

    def test_interaction_mode_emacs(self):
        interaction_mode = "emacs"
        utils.get_codemirror_widget(
            self.language_mode, interaction_mode=interaction_mode)

        addon_js = self.mock_code_mirror_textarea.call_args[1]["addon_js"]
        self.assertIn("../keymap/emacs", addon_js)

        config = self.mock_code_mirror_textarea.call_args[1]["config"]
        self.assertEqual(config["keyMap"], "emacs")

    def test_interaction_mode_sublime(self):
        interaction_mode = "sublime"
        utils.get_codemirror_widget(
            self.language_mode, interaction_mode=interaction_mode)

        addon_js = self.mock_code_mirror_textarea.call_args[1]["addon_js"]
        self.assertIn("../keymap/sublime", addon_js)

        config = self.mock_code_mirror_textarea.call_args[1]["config"]
        self.assertEqual(config["keyMap"], "sublime")

    def test_interaction_mode_other(self):
        # just ensure no errors
        interaction_mode = "other"
        utils.get_codemirror_widget(
            self.language_mode, interaction_mode=interaction_mode)

    def test_update_config(self):
        interaction_mode = "vim"
        utils.get_codemirror_widget(
            self.language_mode, interaction_mode=interaction_mode,
            config={"foo": "bar"})

        addon_js = self.mock_code_mirror_textarea.call_args[1]["addon_js"]
        self.assertIn("../keymap/vim", addon_js)

        config = self.mock_code_mirror_textarea.call_args[1]["config"]
        self.assertEqual(config["vimMode"], True)
        self.assertEqual(config["foo"], "bar")


class WillUseMaskedProfileForEmailTest(SingleCourseTestMixin, TestCase):
    # test utils.will_use_masked_profile_for_email
    def test_no_recipient_email(self):
        self.assertFalse(utils.will_use_masked_profile_for_email(None))
        self.assertFalse(utils.will_use_masked_profile_for_email([]))

    def test_check_single_email(self):
        self.assertFalse(
            utils.will_use_masked_profile_for_email(
                "foo@bar.com"))
        self.assertFalse(
            utils.will_use_masked_profile_for_email(
                ["foo@bar.com"]))

    def test_any(self):
        from course.models import ParticipationPermission
        from course.constants import participation_permission as pperm

        pp = ParticipationPermission(
            participation=self.ta_participation,
            permission=pperm.view_participant_masked_profile)
        pp.save()
        self.assertTrue(
            utils.will_use_masked_profile_for_email(
                self.ta_participation.user.email))

        self.assertFalse(
            utils.will_use_masked_profile_for_email(
                self.instructor_participation.user.email))

        # any participation in the list have that permission, then True
        self.assertTrue(
            utils.will_use_masked_profile_for_email(
                [self.ta_participation.user.email,
                 self.instructor_participation.user.email]))


class GetFacilitiesConfigTest(unittest.TestCase):
    # utils.get_facilities_config (for cases not covered by other tests)
    def test_none(self):
        with override_settings():
            del settings.RELATE_FACILITIES
            self.assertIsNone(utils.get_facilities_config())

        with override_settings(RELATE_FACILITIES=None):
            self.assertIsNone(utils.get_facilities_config())


class FlowPageContextTest(SingleCourseQuizPageTestMixin, TestCase):

    flow_id = QUIZ_FLOW_ID

    def test_flow_page_context_uri_without_requests(self):
        with self.temporarily_switch_to_user(self.student_participation.user):
            self.start_flow(self.flow_id)
            from course.models import FlowSession
            flow_session = FlowSession.objects.first()

            from course.utils import FlowPageContext
            with self.get_course_page_context(
                    self.student_participation.user) as pctx:
                fpctx = FlowPageContext(
                    repo=pctx.repo,
                    course=self.course,
                    flow_id=self.flow_id,
                    page_ordinal=1,
                    participation=self.student_participation,
                    flow_session=flow_session
                )
        self.assertIsNone(fpctx.page_context.page_uri)

# vim: foldmethod=marker