Пример #1
0
    def test_export_as_csv_defaults(self):
        """
        Test export_as_csv with default values: export all model fields, output headers.
        """
        fields = ["code", "name", "description"]
        collection = [
            DummyFactory(code=1, name="dummy 1"),
            DummyFactory(code=2, name="dummy 2"),
            DummyFactory(code=3, name="dummy 3",
                         description="new description"),
        ]

        export_as_csv = export_as_csv_action()

        expected_rows = [
            fields,
            [1, "dummy 1", "description"],
            [2, "dummy 2", "description"],
            [3, "dummy 3", "new description"],
        ]

        export_as_csv(self.model_admin_mock, mock.Mock(), collection)

        self.response_mock.assert_called_once_with(content_type="text/csv")

        self._assert_correct_csv(self.output_stream, expected_rows)
Пример #2
0
class EnterpriseCustomerAdmin(DjangoObjectActions, SimpleHistoryAdmin):
    """
    Django admin model for EnterpriseCustomer.
    """

    form = EnterpriseCustomerForm
    list_display = ("name", "uuid", "site", "active", "logo",
                    "identity_provider")

    list_filter = ("active", )
    search_fields = (
        "name",
        "uuid",
    )
    inlines = [
        EnterpriseCustomerBrandingConfigurationInline,
    ]

    EXPORT_AS_CSV_FIELDS = [
        "name", "active", "site", "uuid", "identity_provider"
    ]

    actions = [export_as_csv_action("CSV Export", fields=EXPORT_AS_CSV_FIELDS)]

    change_actions = ("manage_learners", )

    @staticmethod
    def logo(instance):
        """
        Instance is EnterpriseCustomer.
        """
        if instance.branding_configuration:
            return instance.branding_configuration.logo
        return None

    def manage_learners(self, request, obj):  # pylint: disable=unused-argument
        """
        Object tool handler method - redirects to "Manage Learners" view
        """
        # url names coming from get_urls are prefixed with 'admin' namespace
        manage_learners_url = reverse("admin:" + UrlNames.MANAGE_LEARNERS,
                                      args=(obj.uuid, ))
        return HttpResponseRedirect(manage_learners_url)

    manage_learners.label = "Manage Learners"
    manage_learners.short_description = "Allows managing learners for this Enterprise Customer"

    def get_urls(self):
        """
        Returns the additional urls used by the custom object tools.
        """
        customer_urls = [
            url(r"^([^/]+)/manage_learners$",
                self.admin_site.admin_view(
                    EnterpriseCustomerManageLearnersView.as_view()),
                name=UrlNames.MANAGE_LEARNERS)
        ]
        return customer_urls + super(EnterpriseCustomerAdmin, self).get_urls()
Пример #3
0
    def test_export_as_csv_actual_model(self):
        """
        Tests export_as_csv as it is used in EnterpriseCustomer admin.
        """
        fields = EnterpriseCustomerAdmin.EXPORT_AS_CSV_FIELDS
        collection = [
            EnterpriseCustomerFactory(),
            EnterpriseCustomerFactory(),
            EnterpriseCustomerFactory(),
        ]

        expected_rows = [fields
                         ] + [[getattr(customer, field) for field in fields]
                              for customer in collection]

        export_as_csv = export_as_csv_action("CSV Export", fields=fields)
        export_as_csv(self.model_admin_mock, mock.Mock(), collection)
        self._assert_correct_csv(self.output_stream, expected_rows)
Пример #4
0
    def test_export_as_csv_no_header(self):
        """
        Test export_as_csv - no header.3
        """
        fields = ["code", "name"]
        collection = [
            DummyFactory(code=1, name="dummy 1"),
            DummyFactory(code=2, name="dummy 2"),
        ]

        export_as_csv = export_as_csv_action(fields=fields, header=False)

        expected_rows = [
            [1, "dummy 1"],
            [2, "dummy 2"],
        ]

        export_as_csv(self.model_admin_mock, mock.Mock(), collection)
        self._assert_correct_csv(self.output_stream, expected_rows)
Пример #5
0
    def test_export_as_csv_some_fields(self):
        """
        Test export_as_csv with customized fields: export some model fields, output headers.
        """
        fields = ["code", "name"]
        collection = [
            DummyFactory(code=1, name="dummy 1"),
            DummyFactory(code=2, name="dummy 2"),
        ]

        export_as_csv = export_as_csv_action(fields=fields)

        expected_rows = [
            fields,
            [1, "dummy 1"],
            [2, "dummy 2"],
        ]

        export_as_csv(self.model_admin_mock, mock.Mock(), collection)
        self._assert_correct_csv(self.output_stream, expected_rows)
Пример #6
0
    def test_export_as_csv_callable_fields(self):
        """
        Test export_as_csv - some fields are callables.
        """
        expected_fields = ["code", "name", "greeting"]
        collection = [
            DummyFactory(code=1, name="dummy 1"),
            DummyFactory(code=2, name="dummy 2"),
        ]

        self.model_admin_mock.model._meta.fields.append(self._make_field("greeting"))
        export_as_csv = export_as_csv_action(fields=expected_fields)

        expected_rows = [
            expected_fields,
            [1, "dummy 1", "Hi, dummy 1"],
            [2, "dummy 2", "Hi, dummy 2"],
        ]

        export_as_csv(self.model_admin_mock, mock.Mock(), collection)
        self._assert_correct_csv(self.output_stream, expected_rows)
Пример #7
0
    def test_export_as_csv_special(self):
        """
        Test export_as_csv - test special case handling.

        Special cases are None and empty string values - they are substituted by [markers] for slightly better
        appearance.
        """
        fields = ["code", "name"]
        collection = [
            DummyFactory(code=1, name=None),
            DummyFactory(code=2, name=""),
            DummyFactory(code=0, name="QWERTY"),
        ]

        export_as_csv = export_as_csv_action(fields=fields)
        expected_rows = [
            fields,
            [1, "[Not Set]"],
            [2, "[Empty]"],
            [0, "QWERTY"],
        ]

        export_as_csv(self.model_admin_mock, mock.Mock(), collection)
        self._assert_correct_csv(self.output_stream, expected_rows)
Пример #8
0
class EnterpriseCustomerAdmin(DjangoObjectActions, SimpleHistoryAdmin):
    """
    Django admin model for EnterpriseCustomer.
    """
    list_display = (
        'name',
        'slug',
        'customer_type',
        'site',
        'country',
        'active',
        'has_logo',
        'enable_dsc',
        'has_identity_provider',
        'uuid',
    )

    list_filter = ('active', )
    ordering = ('name', )
    search_fields = (
        'name',
        'uuid',
    )
    inlines = [
        EnterpriseCustomerBrandingConfigurationInline,
        EnterpriseCustomerIdentityProviderInline,
        EnterpriseCustomerCatalogInline,
        PendingEnterpriseCustomerAdminUserInline,
    ]

    EXPORT_AS_CSV_FIELDS = [
        'name', 'active', 'site', 'uuid', 'identity_provider'
    ]

    actions = [
        export_as_csv_action('CSV Export', fields=EXPORT_AS_CSV_FIELDS),
    ]

    change_actions = ('manage_learners',
                      'manage_learners_data_sharing_consent',
                      'transmit_courses_metadata')

    form = EnterpriseCustomerAdminForm

    class Meta:
        model = EnterpriseCustomer

    def change_view(self, request, object_id, form_url='', extra_context=None):
        catalog_uuid = EnterpriseCustomerCatalogAdminForm.get_catalog_preview_uuid(
            request.POST)
        if catalog_uuid:
            catalog_content_metadata_url = \
                EnterpriseCatalogApiClient.get_content_metadata_url(catalog_uuid)
            return HttpResponseRedirect(catalog_content_metadata_url)
        return super(EnterpriseCustomerAdmin,
                     self).change_view(request,
                                       object_id,
                                       form_url,
                                       extra_context=extra_context)

    def get_form(self, request, obj=None, change=False, **kwargs):
        """
        Retrieve the appropriate form to use, saving the request user
        into the form for use in loading catalog details
        """
        form = super(EnterpriseCustomerAdmin,
                     self).get_form(request, obj, change, **kwargs)
        form.user = request.user
        return form

    def enable_dsc(self, instance):
        """
        Return True if data sharing consent is enabled for EnterpriseCustomer.

        Arguments:
            instance (enterprise.models.EnterpriseCustomer): `EnterpriseCustomer` model instance
        """
        return instance.enable_data_sharing_consent

    enable_dsc.boolean = True
    enable_dsc.short_description = u'Enable DSC'

    def has_logo(self, instance):
        """
        Return True if EnterpriseCustomer has a logo.

        Arguments:
            instance (enterprise.models.EnterpriseCustomer): `EnterpriseCustomer` model instance
        """
        has_logo = False
        if hasattr(instance, 'branding_configuration'
                   ) and instance.branding_configuration.logo:
            has_logo = True

        return has_logo

    has_logo.boolean = True
    has_logo.short_description = u'Logo'

    def has_identity_provider(self, instance):
        """
        Return True if EnterpriseCustomer has related identity provider.

        Arguments:
            instance (enterprise.models.EnterpriseCustomer): `EnterpriseCustomer` model instance
        """
        return hasattr(instance, 'enterprise_customer_identity_provider')

    has_identity_provider.boolean = True
    has_identity_provider.short_description = u'Identity provider'

    def manage_learners_data_sharing_consent(self, request, obj):  # pylint: disable=unused-argument
        """
        Object tool handler method - redirects to "Clear Learners Data Sharing Consent" view
        """
        # url names coming from get_urls are prefixed with 'admin' namespace
        return HttpResponseRedirect(
            reverse("admin:" + UrlNames.MANAGE_LEARNERS_DSC,
                    args=(obj.uuid, )))

    manage_learners_data_sharing_consent.label = "Clear Data Sharing Consent"
    manage_learners_data_sharing_consent.short_description = "Clear Data Sharing Consent for a Learner."

    def manage_learners(self, request, obj):  # pylint: disable=unused-argument
        """
        Object tool handler method - redirects to "Manage Learners" view
        """
        # url names coming from get_urls are prefixed with 'admin' namespace
        manage_learners_url = reverse("admin:" + UrlNames.MANAGE_LEARNERS,
                                      args=(obj.uuid, ))
        return HttpResponseRedirect(manage_learners_url)

    manage_learners.label = "Manage Learners"
    manage_learners.short_description = "Allows managing learners for this Enterprise Customer"

    def transmit_courses_metadata(self, request, obj):  # pylint: disable=unused-argument
        """
        Object tool handler method - redirects to `Transmit Courses Metadata` view.
        """
        # url names coming from get_urls are prefixed with 'admin' namespace
        transmit_courses_metadata_url = reverse(
            'admin:' + UrlNames.TRANSMIT_COURSES_METADATA, args=(obj.uuid, ))
        return HttpResponseRedirect(transmit_courses_metadata_url)

    transmit_courses_metadata.label = 'Transmit Courses Metadata'
    transmit_courses_metadata.short_description = 'Transmit courses metadata for this Enterprise Customer'

    def get_urls(self):
        """
        Returns the additional urls used by the custom object tools.
        """
        customer_urls = [
            url(r"^([^/]+)/manage_learners$",
                self.admin_site.admin_view(
                    EnterpriseCustomerManageLearnersView.as_view()),
                name=UrlNames.MANAGE_LEARNERS),
            url(r"^([^/]+)/clear_learners_data_sharing_consent",
                self.admin_site.admin_view(
                    EnterpriseCustomerManageLearnerDataSharingConsentView.
                    as_view()),
                name=UrlNames.MANAGE_LEARNERS_DSC),
            url(r"^([^/]+)/transmit_courses_metadata",
                self.admin_site.admin_view(
                    EnterpriseCustomerTransmitCoursesView.as_view()),
                name=UrlNames.TRANSMIT_COURSES_METADATA)
        ]
        return customer_urls + super(EnterpriseCustomerAdmin, self).get_urls()
Пример #9
0
class EnterpriseCustomerAdmin(DjangoObjectActions, SimpleHistoryAdmin):
    """
    Django admin model for EnterpriseCustomer.
    """

    list_display = ("name", "uuid", "site", "active", "logo",
                    "identity_provider", "enterprise_catalog")

    list_filter = ("active", )
    search_fields = (
        "name",
        "uuid",
    )
    inlines = [
        EnterpriseCustomerBrandingConfigurationInline,
        EnterpriseCustomerIdentityProviderInline
    ]

    EXPORT_AS_CSV_FIELDS = [
        "name", "active", "site", "uuid", "identity_provider", "catalog"
    ]

    actions = [
        export_as_csv_action("CSV Export", fields=EXPORT_AS_CSV_FIELDS),
        get_clear_catalog_id_action()
    ]

    change_actions = ("manage_learners", )

    form = EnterpriseCustomerAdminForm

    class Meta(object):
        model = EnterpriseCustomer

    def get_form(self, request, obj=None, **kwargs):
        """
        Retrieve the appropriate form to use, saving the request user
        into the form for use in loading catalog details
        """
        form = super(EnterpriseCustomerAdmin,
                     self).get_form(request, obj, **kwargs)
        form.user = request.user
        return form

    @staticmethod
    def logo(instance):
        """
        Instance is EnterpriseCustomer.
        """
        if instance.branding_configuration:
            return instance.branding_configuration.logo
        return None

    @staticmethod
    def identity_provider(instance):
        """
        Instance is EnterpriseCustomer.

        Return identity provider name to display in enterprise customer list admin view, and if identity provider name
        is not available then return identity provider id.
        """
        ec_idp = instance.enterprise_customer_identity_provider
        return ec_idp and ec_idp.provider_name or ec_idp.provider_id

    def enterprise_catalog(self, instance):
        """
        Enterprise catalog id with a link to catalog details page.

        Arguments:
            instance (enterprise.models.EnterpriseCustomer): `EnterpriseCustomer` model instance

        Returns:
            catalog id with catalog details link to display in enterprise customer list view.
        """
        # Return None if EnterpriseCustomer does not have an associated catalog.
        if not instance.catalog:
            return None

        catalog_url = get_catalog_admin_url(instance.catalog)
        return "{catalog_id}: <a href='{catalog_url}' target='_blank'>View catalog details.</a>".format(
            catalog_id=instance.catalog,
            catalog_url=catalog_url,
        )

    # Allow html tags in enterprise_catalog column,
    # we need to set it true so that anchor tag is not escaped.
    enterprise_catalog.allow_tags = True

    def manage_learners(self, request, obj):  # pylint: disable=unused-argument
        """
        Object tool handler method - redirects to "Manage Learners" view
        """
        # url names coming from get_urls are prefixed with 'admin' namespace
        manage_learners_url = reverse("admin:" + UrlNames.MANAGE_LEARNERS,
                                      args=(obj.uuid, ))
        return HttpResponseRedirect(manage_learners_url)

    manage_learners.label = "Manage Learners"
    manage_learners.short_description = "Allows managing learners for this Enterprise Customer"

    def get_urls(self):
        """
        Returns the additional urls used by the custom object tools.
        """
        customer_urls = [
            url(r"^([^/]+)/manage_learners$",
                self.admin_site.admin_view(
                    EnterpriseCustomerManageLearnersView.as_view()),
                name=UrlNames.MANAGE_LEARNERS)
        ]
        return customer_urls + super(EnterpriseCustomerAdmin, self).get_urls()