From 71f00a55b073752a793cbf7a9dcd08528db9e805 Mon Sep 17 00:00:00 2001 From: alezconsultant Date: Wed, 11 Nov 2026 23:05:37 +0400 Subject: [PATCH] feat: copy content tags and competency criteria on course rerun rerun_course now calls copy_course_tags_and_criteria() before it marks the rerun as succeeded. The function copies the source run's content tags to the new run as editable tags and then copies its competency criteria, in one transaction. A failure reaches the existing rerun failure handling, which marks the rerun as failed and deletes the cloned course. A taxonomy that is not enabled for the new run's organization is left out, together with its criteria, and a warning is logged. The catalog CourseRun row for the new run is created when it is missing, because criteria groups reference it and the publish handler may not have created it. Related to https://github.com/openedx/openedx-core/issues/694 Co-Authored-By: Claude Fable 5.2 --- cms/djangoapps/contentstore/tasks.py | 4 +- .../contentstore/tests/test_tasks.py | 146 ++++++++++- .../core/djangoapps/content_tagging/api.py | 90 +++++++ .../content_tagging/tests/test_api.py | 229 +++++++++++++++++- 4 files changed, 462 insertions(+), 7 deletions(-) diff --git a/cms/djangoapps/contentstore/tasks.py b/cms/djangoapps/contentstore/tasks.py index cd267be89af7..f3a1a16869b9 100644 --- a/cms/djangoapps/contentstore/tasks.py +++ b/cms/djangoapps/contentstore/tasks.py @@ -71,7 +71,7 @@ from common.djangoapps.util.monitoring import monitor_import_failure from openedx.core.djangoapps.content.learning_sequences.api import key_supports_outlines from openedx.core.djangoapps.content_libraries import api as v2contentlib_api -from openedx.core.djangoapps.content_tagging.api import make_copied_tags_editable +from openedx.core.djangoapps.content_tagging.api import copy_course_tags_and_criteria, make_copied_tags_editable from openedx.core.djangoapps.course_apps.toggles import exams_ida_enabled from openedx.core.djangoapps.discussions.config.waffle import ENABLE_NEW_STRUCTURE_DISCUSSIONS from openedx.core.djangoapps.discussions.models import DiscussionsConfiguration, Provider @@ -186,6 +186,8 @@ def rerun_course(source_course_key_string, destination_course_key_string, user_i # set initial permissions for the user to access the course. initialize_permissions(destination_course_key, User.objects.get(id=user_id)) + copy_course_tags_and_criteria(source_course_key, destination_course_key) + # update state: Succeeded CourseRerunState.objects.succeeded(course_key=destination_course_key) diff --git a/cms/djangoapps/contentstore/tests/test_tasks.py b/cms/djangoapps/contentstore/tests/test_tasks.py index 1f8f0348a11c..c74f40bb5a42 100644 --- a/cms/djangoapps/contentstore/tests/test_tasks.py +++ b/cms/djangoapps/contentstore/tests/test_tasks.py @@ -18,20 +18,27 @@ from edx_toggles.toggles.testutils import override_waffle_flag from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locator import CourseLocator +from openedx_catalog.api import create_course_run_for_modulestore_course_with +from openedx_catalog.models_api import CourseRun +from openedx_learning.api import associate_competency_criterion, create_competency_taxonomy +from openedx_learning.models_api import CompetencyCriteriaGroup, CompetencyCriterion, RuleType +from openedx_tagging.rules import ObjectTagPermissionItem from organizations.models import OrganizationCourse from organizations.tests.factories import OrganizationFactory from user_tasks.models import UserTaskArtifact, UserTaskStatus from cms.djangoapps.contentstore.tests.test_libraries import LibraryTestCase from cms.djangoapps.contentstore.tests.utils import CourseTestCase +from common.djangoapps.course_action_state.managers import CourseRerunUIStateManager from common.djangoapps.course_action_state.models import CourseRerunState from common.djangoapps.student.tests.factories import UserFactory +from openedx.core.djangoapps.content_tagging import api as tagging_api from openedx.core.djangoapps.course_apps.toggles import EXAMS_IDA from openedx.core.djangoapps.discussions.config.waffle import ENABLE_NEW_STRUCTURE_DISCUSSIONS from openedx.core.djangoapps.discussions.models import DiscussionsConfiguration, Provider from openedx.core.djangoapps.embargo.models import Country, CountryAccessRule, RestrictedCourse from xmodule.modulestore import ModuleStoreEnum -from xmodule.modulestore.django import modulestore # pylint: disable=wrong-import-order +from xmodule.modulestore.django import SignalHandler, modulestore # pylint: disable=wrong-import-order from xmodule.modulestore.tests.django_utils import TEST_DATA_SPLIT_MODULESTORE, ModuleStoreTestCase from xmodule.modulestore.tests.factories import ( # pylint: disable=wrong-import-order BlockFactory, @@ -151,9 +158,59 @@ class RerunCourseTaskTestCase(CourseTestCase): # pylint: disable=missing-class- MODULESTORE = TEST_DATA_SPLIT_MODULESTORE - def _rerun_course(self, old_course_key, new_course_key): - CourseRerunState.objects.initiated(old_course_key, new_course_key, self.user, 'Test Re-run') - rerun_course(str(old_course_key), str(new_course_key), self.user.id) + def _rerun_course(self, old_course_key, new_course_key, user=None): + user = user or self.user + CourseRerunState.objects.initiated(old_course_key, new_course_key, user, 'Test Re-run') + rerun_course(str(old_course_key), str(new_course_key), user.id) + + def _tag_course_and_add_criterion(self, org=None): + """ + Tag the course, give a new problem a competency criterion, and return the problem's key. + + With `org`, the taxonomies are enabled for that organization only, otherwise for all. + """ + problem = BlockFactory.create( + parent=BlockFactory.create( + parent=BlockFactory.create(parent=self.course, category="sequential"), category="vertical", + ), + category="problem", + ) + problem_key = self.course.id.make_usage_key("problem", problem.location.block_id) + plain_taxonomy = tagging_api.create_taxonomy(name="Plain") + competency_taxonomy = create_competency_taxonomy(name="Competencies") + for taxonomy in (plain_taxonomy, competency_taxonomy): + if org: + tagging_api.set_taxonomy_orgs(taxonomy, orgs=[org]) + else: + tagging_api.set_taxonomy_orgs(taxonomy, all_orgs=True) + tagging_api.add_tag_to_taxonomy(taxonomy=plain_taxonomy, tag="Alpha") + competency = tagging_api.add_tag_to_taxonomy(taxonomy=competency_taxonomy, tag="Writing") + tagging_api.tag_object(object_id=str(self.course.id), taxonomy=plain_taxonomy, tags=["Alpha"]) + create_course_run_for_modulestore_course_with(self.course.id, title=self.course.display_name) + associate_competency_criterion( + competency.id, + str(problem_key), + rule_type_override=RuleType.GRADE, + rule_payload_override={"op": "gte", "value": 0.8, "scale": "percent"}, + ) + return problem_key + + def _assert_rerun_state(self, new_course_key, state): + """Assert the rerun of `new_course_key` is in `state`.""" + assert CourseRerunState.objects.find_first(course_key=new_course_key).state == state + + def _assert_one_copy(self, new_course_key, problem_key): + """Assert the new run has one copy of the course's tags and of `problem_key`'s tags and criterion.""" + new_problem_key = str(problem_key.map_into_course(new_course_key)) + assert [tag.value for tag in tagging_api.get_object_tags(str(new_course_key))] == ["Alpha"] + assert [tag.value for tag in tagging_api.get_object_tags(new_problem_key)] == ["Writing"] + assert CompetencyCriteriaGroup.objects.filter(course__course_key=new_course_key).count() == 1 + assert CompetencyCriterion.objects.filter(object_tag__object_id=new_problem_key).count() == 1 + + def _assert_nothing_copied(self, new_course_key): + """Assert the new run has no tags and no criteria.""" + assert not tagging_api.get_all_object_tags(new_course_key)[0] + assert not CompetencyCriteriaGroup.objects.filter(course__course_key=new_course_key).exists() def test_success(self): """ The task should clone the OrganizationCourse and RestrictedCourse data. """ @@ -210,6 +267,7 @@ def test_success_different_org(self): organization = OrganizationFactory(short_name=old_course_key.org) OrganizationCourse.objects.create(course_id=old_course_id, organization=organization) + self._tag_course_and_add_criterion(org=organization) # Run the task! self._rerun_course(old_course_key, new_course_key) @@ -218,6 +276,86 @@ def test_success_different_org(self): self.assertEqual(OrganizationCourse.objects.count(), 2) # noqa: PT009 OrganizationCourse.objects.get(course_id=new_course_id, organization__short_name='neworg') + # The source taxonomies are not enabled for the new org, so nothing is copied and the rerun still succeeds. + self._assert_rerun_state(new_course_key, CourseRerunUIStateManager.State.SUCCEEDED) + self._assert_nothing_copied(new_course_key) + + def test_rerun_copies_tags_and_criteria(self): + problem_key = self._tag_course_and_add_criterion() + new_course_key = CourseLocator(org=self.course.id.org, course=self.course.id.course, run='rerun') + + self._rerun_course(self.course.id, new_course_key) + + self._assert_rerun_state(new_course_key, CourseRerunUIStateManager.State.SUCCEEDED) + self._assert_one_copy(new_course_key, problem_key) + + def test_rerun_by_user_without_tagging_permission_copies_everything(self): + problem_key = self._tag_course_and_add_criterion() + new_course_key = CourseLocator(org=self.course.id.org, course=self.course.id.course, run='rerun') + author = UserFactory() + competency_taxonomy = tagging_api.get_object_tags(str(problem_key))[0].taxonomy + permission_item = ObjectTagPermissionItem(taxonomy=competency_taxonomy, object_id=str(self.course.id)) + assert not author.has_perm("oel_tagging.can_tag_object", permission_item) + + self._rerun_course(self.course.id, new_course_key, user=author) + + self._assert_rerun_state(new_course_key, CourseRerunUIStateManager.State.SUCCEEDED) + self._assert_one_copy(new_course_key, problem_key) + + def _fail_criteria_copy(self): + """Patch the criteria copy, which runs after the tags are written, to raise.""" + return patch( + 'openedx.core.djangoapps.content_tagging.api.copy_competency_criteria_for_course_rerun', + side_effect=Exception('criteria copy failed'), + ) + + def test_rerun_copy_failure_fails_and_deletes_course(self): + self._tag_course_and_add_criterion() + new_course_key = CourseLocator(org=self.course.id.org, course=self.course.id.course, run='rerun') + + with self._fail_criteria_copy() as criteria_copy: + self._rerun_course(self.course.id, new_course_key) + + criteria_copy.assert_called_once() + + self._assert_rerun_state(new_course_key, CourseRerunUIStateManager.State.FAILED) + assert modulestore().get_course(new_course_key) is None + self._assert_nothing_copied(new_course_key) + + def test_rerun_retry_after_failure_has_one_copy(self): + problem_key = self._tag_course_and_add_criterion() + new_course_key = CourseLocator(org=self.course.id.org, course=self.course.id.course, run='rerun') + with self._fail_criteria_copy(): + self._rerun_course(self.course.id, new_course_key) + self._assert_rerun_state(new_course_key, CourseRerunUIStateManager.State.FAILED) + self._assert_nothing_copied(new_course_key) + + self._rerun_course(self.course.id, new_course_key) + + self._assert_rerun_state(new_course_key, CourseRerunUIStateManager.State.SUCCEEDED) + self._assert_one_copy(new_course_key, problem_key) + + def test_rerun_retry_after_late_failure_has_one_copy(self): + problem_key = self._tag_course_and_add_criterion() + new_course_key = CourseLocator(org=self.course.id.org, course=self.course.id.course, run='rerun') + new_problem_key = str(problem_key.map_into_course(new_course_key)) + # Deleting the failed run's course sends course_deleted, whose receiver removes the destination CourseRun. + with SignalHandler.course_deleted.for_state(is_enabled=True), \ + patch('edxval.api.copy_course_videos', side_effect=Exception('video copy failed')): + self._rerun_course(self.course.id, new_course_key) + self._assert_rerun_state(new_course_key, CourseRerunUIStateManager.State.FAILED) + # The tags committed before the failure and outlive the CourseRun, so the retry meets them. + assert not CourseRun.objects.filter(course_key=new_course_key).exists() + assert not CompetencyCriteriaGroup.objects.filter(course__course_key=new_course_key).exists() + assert not CompetencyCriterion.objects.filter(object_tag__object_id=new_problem_key).exists() + assert [tag.value for tag in tagging_api.get_object_tags(str(new_course_key))] == ["Alpha"] + assert [tag.value for tag in tagging_api.get_object_tags(new_problem_key)] == ["Writing"] + + self._rerun_course(self.course.id, new_course_key) + + self._assert_rerun_state(new_course_key, CourseRerunUIStateManager.State.SUCCEEDED) + self._assert_one_copy(new_course_key, problem_key) + @override_settings(CONTENTSTORE=TEST_DATA_CONTENTSTORE) class RegisterExamsTaskTestCase(CourseTestCase): # pylint: disable=missing-class-docstring diff --git a/openedx/core/djangoapps/content_tagging/api.py b/openedx/core/djangoapps/content_tagging/api.py index ecfd04a91d86..2c4318bd1463 100644 --- a/openedx/core/djangoapps/content_tagging/api.py +++ b/openedx/core/djangoapps/content_tagging/api.py @@ -5,26 +5,36 @@ import csv import io +import logging from itertools import groupby from typing import Iterator # noqa: UP035 import openedx_tagging.api as oel_tagging +from django.conf import settings from django.core.exceptions import ValidationError +from django.db import transaction from django.db.models import Exists, OuterRef, Q, QuerySet from django.utils.timezone import now from opaque_keys.edx.keys import CollectionKey, ContainerKey, CourseKey, UsageKey from opaque_keys.edx.locator import LibraryLocatorV2 +from openedx_catalog import api as catalog_api +from openedx_catalog.models_api import CourseRun from openedx_events.content_authoring.data import ContentObjectChangedData, ContentObjectData from openedx_events.content_authoring.signals import CONTENT_OBJECT_ASSOCIATIONS_CHANGED, CONTENT_OBJECT_TAGS_CHANGED +from openedx_learning.api import copy_competency_criteria_for_course_rerun from openedx_tagging.models import ObjectTag, Taxonomy from openedx_tagging.models.utils import TAGS_CSV_SEPARATOR from organizations.models import Organization +from xmodule.modulestore.django import modulestore + from .helpers.objecttag_export_helpers import build_object_tree_with_objecttags, iterate_with_level from .models import TaxonomyOrg from .types import ContentKey, TagValuesByObjectIdDict, TagValuesByTaxonomyIdDict, TaxonomyDict from .utils import check_taxonomy_context_key_org, get_content_key_from_string, get_context_key_from_key +log = logging.getLogger(__name__) + class InvalidOrgException(ValidationError): """ @@ -394,6 +404,86 @@ def copy_object_tags( pass +def copy_course_tags_and_criteria(source_course_key: CourseKey, destination_course_key: CourseKey) -> None: + """ + Copy the source course run's tags, as editable tags, and its competency criteria onto the destination run. + + Taxonomies not enabled for the destination org are skipped, along with their criteria. + It also creates the destination run's catalog CourseRun when the source run has one and the destination does not. + """ + with transaction.atomic(): + all_object_tags, taxonomies = get_all_object_tags(source_course_key, prefetch_orgs=True) + skipped_taxonomy_ids = _get_skipped_taxonomy_ids(taxonomies, source_course_key, destination_course_key) + + for object_id, tags_by_taxonomy_id in all_object_tags.items(): + destination_object_id = _map_object_id_into_course(object_id, source_course_key, destination_course_key) + if destination_object_id is None: + continue + for taxonomy_id, tag_values in tags_by_taxonomy_id.items(): + if taxonomy_id not in skipped_taxonomy_ids: + tag_object(destination_object_id, taxonomies[taxonomy_id], tag_values) + + _create_destination_course_run_if_missing(source_course_key, destination_course_key) + copy_competency_criteria_for_course_rerun( + source_course_key, destination_course_key, skipped_taxonomy_ids=skipped_taxonomy_ids, + ) + + +def _get_skipped_taxonomy_ids( + taxonomies: TaxonomyDict, source_course_key: CourseKey, destination_course_key: CourseKey, +) -> set[int]: + """ + Return the ids of the taxonomies not enabled for the destination run's org, logging a warning for each. + """ + skipped_taxonomy_ids = set() + for taxonomy_id, taxonomy in taxonomies.items(): + if not check_taxonomy_context_key_org(taxonomy, destination_course_key): + skipped_taxonomy_ids.add(taxonomy_id) + log.warning( + 'Not copying tags or criteria of taxonomy "%s" from %s to %s: ' + 'it is not enabled for the destination organization.', + taxonomy.name, source_course_key, destination_course_key, + ) + return skipped_taxonomy_ids + + +def _map_object_id_into_course( + object_id: str, source_course_key: CourseKey, destination_course_key: CourseKey, +) -> str | None: + """ + Return the destination run's id for the source run's course or block, or None for another course's block. + """ + if object_id == str(source_course_key): + return str(destination_course_key) + usage_key = UsageKey.from_string(object_id) + # get_all_object_tags() matches by prefix, so it can return blocks of a course whose key extends ours. + if usage_key.course_key != source_course_key: + return None + return str(usage_key.map_into_course(destination_course_key)) + + +def _create_destination_course_run_if_missing(source_course_key: CourseKey, destination_course_key: CourseKey) -> None: + """ + Create the destination run's CourseRun from the cloned course when the source run has one and it does not. + """ + try: + catalog_api.get_course_run(source_course_key) + except CourseRun.DoesNotExist: + return + try: + catalog_api.get_course_run(destination_course_key) + except CourseRun.DoesNotExist: + # The course publish handler creates this row when it has run. + course = modulestore().get_course(destination_course_key) + language_codes = {code for code, _name in settings.ALL_LANGUAGES} + catalog_api.create_course_run_for_modulestore_course_with( + course_key=destination_course_key, + # The catalog rejects a title longer than its column and a language outside ALL_LANGUAGES. + title=course.display_name[:CourseRun._meta.get_field("title").max_length], + language_short=course.language if course.language in language_codes else None, + ) + + def tag_object( object_id: str, taxonomy: Taxonomy, diff --git a/openedx/core/djangoapps/content_tagging/tests/test_api.py b/openedx/core/djangoapps/content_tagging/tests/test_api.py index ea97706a9d1d..577f4346ab4d 100644 --- a/openedx/core/djangoapps/content_tagging/tests/test_api.py +++ b/openedx/core/djangoapps/content_tagging/tests/test_api.py @@ -2,16 +2,24 @@ import io import os import tempfile +from unittest.mock import patch import ddt import pytest from django.test.testcases import TestCase from fs.osfs import OSFS from opaque_keys.edx.keys import CourseKey, UsageKey -from opaque_keys.edx.locator import LibraryCollectionLocator, LibraryContainerLocator, LibraryLocatorV2 -from openedx_tagging.models import ObjectTag +from opaque_keys.edx.locator import CourseLocator, LibraryCollectionLocator, LibraryContainerLocator, LibraryLocatorV2 +from openedx_catalog.api import create_course_run_for_modulestore_course_with, get_course_run +from openedx_catalog.models_api import CourseRun +from openedx_learning.api import associate_competency_criterion, create_competency_taxonomy +from openedx_learning.models_api import CompetencyCriteriaGroup, CompetencyCriterion, RuleType +from openedx_tagging.models import ObjectTag, Tag, Taxonomy from organizations.models import Organization +from xmodule.modulestore.tests.django_utils import TEST_DATA_SPLIT_MODULESTORE, ModuleStoreTestCase +from xmodule.modulestore.tests.factories import BlockFactory, CourseFactory + from .. import api from ..utils import rules_cache from .test_objecttag_export_helpers import TaggedCourseMixin, TestGetAllObjectTagsMixin @@ -530,3 +538,220 @@ def test_import_tags_invalid_taxonomy(self) -> None: assert object_tag.value == 'Tag 1.11' assert object_tag.taxonomy is None assert object_tag.export_id == '1-taxonomy-1-1' + + +@ddt.ddt +class TestCopyCourseTagsAndCriteria(ModuleStoreTestCase): + """ + Tests for copy_course_tags_and_criteria(). + """ + MODULESTORE = TEST_DATA_SPLIT_MODULESTORE + + def setUp(self): + super().setUp() + self.org_a = Organization.objects.create(name="Organization A", short_name="orgA") + Organization.objects.create(name="Organization B", short_name="orgB") + + self.taxonomy = api.create_taxonomy(name="Plain") + api.set_taxonomy_orgs(self.taxonomy, all_orgs=True) + api.add_tag_to_taxonomy(taxonomy=self.taxonomy, tag="Alpha") + api.add_tag_to_taxonomy(taxonomy=self.taxonomy, tag="Beta") + + self.org_a_taxonomy = api.create_taxonomy(name="Org A only", orgs=[self.org_a]) + api.add_tag_to_taxonomy(taxonomy=self.org_a_taxonomy, tag="Gamma") + + self.competency_taxonomy = create_competency_taxonomy(name="Competencies") + api.set_taxonomy_orgs(self.competency_taxonomy, all_orgs=True) + self.competency = api.add_tag_to_taxonomy(taxonomy=self.competency_taxonomy, tag="Writing") + + self.course = CourseFactory.create(org="orgA", number="course", run="run1", display_name="Source Course") + sequential = BlockFactory.create(parent=self.course, category="sequential") + vertical = BlockFactory.create(parent=sequential, category="vertical") + problem = BlockFactory.create(parent=vertical, category="problem") + self.source_key = self.course.id + self.sequential_key = self.source_key.make_usage_key("sequential", sequential.location.block_id) + self.problem_key = self.source_key.make_usage_key("problem", problem.location.block_id) + self.destination_key = CourseLocator(org="orgA", course="course", run="run2") + + rules_cache.clear() + + def _clone(self, destination_key, display_name="Rerun Course", **fields): + """Clone the source course to `destination_key`, as a rerun does.""" + self.store.clone_course( + self.source_key, destination_key, self.user.id, fields={"display_name": display_name, **fields}, + ) + + def _tag(self, object_key, taxonomy, values): + """Tag `object_key` with `values` from `taxonomy`.""" + api.tag_object(object_id=str(object_key), taxonomy=taxonomy, tags=values) + + def _values(self, object_key, taxonomy): + """Return the tag values `object_key` has from `taxonomy`.""" + return [tag.value for tag in api.get_object_tags(str(object_key), taxonomy_id=taxonomy.id)] + + def _in_destination(self, usage_key, destination_key=None): + """Return `usage_key` mapped into the destination course.""" + return usage_key.map_into_course(destination_key or self.destination_key) + + def _add_criterion(self): + """Give the source run a catalog row and a criterion for the problem, which tags it with the competency.""" + create_course_run_for_modulestore_course_with(self.source_key, title="Source Course") + associate_competency_criterion( + self.competency.id, + str(self.problem_key), + rule_type_override=RuleType.GRADE, + rule_payload_override={"op": "gte", "value": 0.8, "scale": "percent"}, + ) + + @ddt.data( + ("competency_taxonomy", ["Writing"]), + ("taxonomy", ["Alpha", "Beta"]), + ) + @ddt.unpack + def test_copies_course_and_block_tags(self, taxonomy_name, block_values): + taxonomy = getattr(self, taxonomy_name) + self._tag(self.source_key, taxonomy, block_values[:1]) + self._tag(self.sequential_key, taxonomy, block_values) + self._clone(self.destination_key) + tag_count, taxonomy_count = Tag.objects.count(), Taxonomy.objects.count() + + api.copy_course_tags_and_criteria(self.source_key, self.destination_key) + + assert self._values(self.destination_key, taxonomy) == block_values[:1] + assert self._values(self._in_destination(self.sequential_key), taxonomy) == block_values + assert (Tag.objects.count(), Taxonomy.objects.count()) == (tag_count, taxonomy_count) + + def test_copied_tags_are_editable(self): + self._tag(self.source_key, self.taxonomy, ["Alpha"]) + self._tag(self.sequential_key, self.taxonomy, ["Beta"]) + self._clone(self.destination_key) + + api.copy_course_tags_and_criteria(self.source_key, self.destination_key) + + copied = ObjectTag.objects.filter( + object_id__in=[str(self.destination_key), str(self._in_destination(self.sequential_key))], + ) + assert copied.count() == 2 + assert not copied.filter(is_copied=True).exists() + + destination_sequential_key = self._in_destination(self.sequential_key) + self._tag(destination_sequential_key, self.taxonomy, ["Alpha"]) + self._tag(self.destination_key, self.taxonomy, []) + assert self._values(self.sequential_key, self.taxonomy) == ["Beta"] + assert self._values(self.source_key, self.taxonomy) == ["Alpha"] + + self._tag(self.sequential_key, self.taxonomy, []) + assert self._values(destination_sequential_key, self.taxonomy) == ["Alpha"] + + def test_source_tags_unchanged(self): + self._tag(self.source_key, self.taxonomy, ["Alpha"]) + self._tag(self.sequential_key, self.taxonomy, ["Alpha", "Beta"]) + self._add_criterion() + source_tags = list(ObjectTag.objects.order_by("id").values()) + self._clone(self.destination_key) + + api.copy_course_tags_and_criteria(self.source_key, self.destination_key) + + assert list(ObjectTag.objects.filter(id__in=[tag["id"] for tag in source_tags]).order_by("id").values()) == ( + source_tags + ) + + def test_ignores_tags_of_course_with_prefixed_key(self): + # "run10" starts with "run1", so get_all_object_tags() also returns this course's block tags. + prefixed_key = CourseLocator(org="orgA", course="course", run="run10") + other_block_key = prefixed_key.make_usage_key("problem", "other_problem") + self._tag(other_block_key, self.taxonomy, ["Alpha"]) + self._clone(self.destination_key) + + api.copy_course_tags_and_criteria(self.source_key, self.destination_key) + + assert not api.get_all_object_tags(self.destination_key)[0] + + def test_skips_taxonomy_not_enabled_for_destination_org(self): + destination_key = CourseLocator(org="orgB", course="course", run="run2") + self._tag(self.source_key, self.org_a_taxonomy, ["Gamma"]) + self._tag(self.sequential_key, self.org_a_taxonomy, ["Gamma"]) + self._tag(self.sequential_key, self.taxonomy, ["Alpha"]) + self._add_criterion() + api.set_taxonomy_orgs(self.competency_taxonomy, orgs=[self.org_a]) + rules_cache.clear() + self._clone(destination_key) + + with self.assertLogs(api.log, level="WARNING") as logs: + api.copy_course_tags_and_criteria(self.source_key, destination_key) + + assert len(logs.records) == 2 + for taxonomy in (self.org_a_taxonomy, self.competency_taxonomy): + assert sum( + taxonomy.name in message and str(self.source_key) in message and str(destination_key) in message + for message in logs.output + ) == 1 + assert self._values(destination_key, self.org_a_taxonomy) == [] + assert self._values(self._in_destination(self.sequential_key, destination_key), self.org_a_taxonomy) == [] + assert self._values(self._in_destination(self.problem_key, destination_key), self.competency_taxonomy) == [] + assert self._values(self._in_destination(self.sequential_key, destination_key), self.taxonomy) == ["Alpha"] + assert not CompetencyCriteriaGroup.objects.filter(course__course_key=destination_key).exists() + + def test_copies_criteria_onto_destination_run(self): + self._add_criterion() + self._clone(self.destination_key) + + api.copy_course_tags_and_criteria(self.source_key, self.destination_key) + + course_level_group = CompetencyCriteriaGroup.objects.get(course__course_key=self.destination_key) + assert course_level_group.tag == self.competency + criterion = CompetencyCriterion.objects.get(group__parent=course_level_group) + assert criterion.object_tag.object_id == str(self._in_destination(self.problem_key)) + assert self._values(self._in_destination(self.problem_key), self.competency_taxonomy) == ["Writing"] + + def test_creates_destination_course_run_when_missing(self): + create_course_run_for_modulestore_course_with(self.source_key, title="Source Course") + self._clone(self.destination_key, display_name="Rerun Course") + assert not CourseRun.objects.filter(course_key=self.destination_key).exists() + + api.copy_course_tags_and_criteria(self.source_key, self.destination_key) + + assert get_course_run(self.destination_key).title == "Rerun Course" + + def test_destination_course_run_title_is_cut_to_the_column_length(self): + create_course_run_for_modulestore_course_with(self.source_key, title="Source Course") + self._clone(self.destination_key, display_name="x" * 300) + + api.copy_course_tags_and_criteria(self.source_key, self.destination_key) + + assert get_course_run(self.destination_key).title == "x" * 255 + + @ddt.data(("fr", "fr"), ("not-a-language", "en")) + @ddt.unpack + def test_destination_catalog_course_language(self, course_language, expected_language): + # A new course number, so the copy also creates the catalog course, which is what stores the language. + destination_key = CourseLocator(org="orgA", course="course2", run="run1") + create_course_run_for_modulestore_course_with(self.source_key, title="Source Course") + self._clone(destination_key, language=course_language) + + api.copy_course_tags_and_criteria(self.source_key, destination_key) + + assert get_course_run(destination_key).catalog_course.language_short == expected_language + + def test_course_without_tags_or_criteria_succeeds(self): + self._clone(self.destination_key) + assert not CourseRun.objects.filter(course_key=self.source_key).exists() + + api.copy_course_tags_and_criteria(self.source_key, self.destination_key) + + assert not api.get_all_object_tags(self.destination_key)[0] + assert not CompetencyCriteriaGroup.objects.filter(course__course_key=self.destination_key).exists() + assert not CourseRun.objects.filter(course_key=self.destination_key).exists() + + def test_criteria_failure_rolls_back_tags(self): + self._tag(self.source_key, self.taxonomy, ["Alpha"]) + self._tag(self.sequential_key, self.taxonomy, ["Beta"]) + self._add_criterion() + self._clone(self.destination_key) + + with patch.object(api, "copy_competency_criteria_for_course_rerun", side_effect=ObjectTag.DoesNotExist): + with pytest.raises(ObjectTag.DoesNotExist): + api.copy_course_tags_and_criteria(self.source_key, self.destination_key) + + assert not api.get_all_object_tags(self.destination_key)[0] + assert not CourseRun.objects.filter(course_key=self.destination_key).exists()