Python django.core.management.CommandError() Examples

The following are 30 code examples of django.core.management.CommandError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.management , or try the search function .
Example #1
Source File: test_backpopulate_course_type.py    From course-discovery with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_invalid_args(self):
        partner_code = '--partner={}'.format(self.partner.short_code)
        course_arg = '--course={}'.format(self.course.uuid)

        with self.assertRaises(CommandError) as cm:
            self.call_command(partner_code)  # no courses listed
        self.assertEqual(cm.exception.args[0], 'No courses found. Did you specify an argument?')

        with self.assertRaises(CommandError) as cm:
            self.call_command(course_arg)  # no partner
        self.assertEqual(cm.exception.args[0], 'You must specify --partner')

        with self.assertRaises(CommandError) as cm:
            self.call_command('--partner=NotAPartner', course_arg)
        self.assertEqual(cm.exception.args[0], 'No courses found. Did you specify an argument?')

        with self.assertRaises(CommandError) as cm:
            self.call_command('--allow-for=NotACourseType:audit', partner_code, course_arg)
        self.assertEqual(cm.exception.args[0], 'Supplied Course Type slug [NotACourseType] does not exist.')

        with self.assertRaises(CommandError) as cm:
            self.call_command('--allow-for=verified-audit:NotACourseRunType', partner_code, course_arg)
        self.assertEqual(cm.exception.args[0], 'Supplied Course Run Type slug [NotACourseRunType] does not exist.') 
Example #2
Source File: city_sdk.py    From linkedevents with MIT License 6 votes vote down vote up
def authenticate(self):
        """
        Authenticate, CitySDK uses session based username/password auth
        """
        username = settings.CITYSDK_API_SETTINGS['USERNAME']
        password = settings.CITYSDK_API_SETTINGS['PASSWORD']
        session_response = requests.get(
            '%sauth?username=%s&password=%s' %
            (BASE_API_URL, username, password))
        if session_response.status_code == 200:
            self.session_cookies = session_response.cookies
            print("Authentication successful with response: %s"
                  % session_response.text)
        else:
            raise CommandError(
                "Authentication failed with credentials %s:%s" % (
                    (username, password)
                )) 
Example #3
Source File: check_anonymizers.py    From django-anonymizer with MIT License 6 votes vote down vote up
def handle_app_config(self, app_config, **options):
        anonymizers = get_anonymizers(app_config)
        models = set()
        errors = []
        for klass in anonymizers:
            models.add(klass.model)
            instance = klass()
            try:
                instance.validate()
            except ValueError as e:
                errors.append(unicode(e))

        for model in app_config.get_models():
            if model._meta.abstract or model._meta.proxy:
                continue

            if model not in models:
                errors.append(u'need anonymizer for %s' % model)

        if errors:
            raise CommandError('%d errors\n%s' % (len(errors), '\n'.join(errors)))
        return 0 
Example #4
Source File: create_org.py    From ocl_web with Mozilla Public License 2.0 6 votes vote down vote up
def handle(self, *args, **options):

        self.importer.get_args(args, options)

        self.short_name = options['short_name']
        self.full_name = options['full_name']
        self.company_name = options['company_name']
        self.website = options['website']
        self.location = options['location']

        if self.short_name is None and self.importer.filename is None:
            raise CommandError('--short_name or --csv is required.')

        self.importer.connect()

        if self.importer.filename:
            self.handle_file()
        else:
            self.create_org(self.short_name, self.full_name,
                            self.website, self.company_name, self.location) 
Example #5
Source File: sync-from-pdns.py    From desec-stack with MIT License 6 votes vote down vote up
def handle(self, *args, **options):
        domains = Domain.objects.all()

        if options['domain-name']:
            domains = domains.filter(name__in=options['domain-name'])
            domain_names = domains.values_list('name', flat=True)

            for domain_name in options['domain-name']:
                if domain_name not in domain_names:
                    raise CommandError('{} is not a known domain'.format(domain_name))

        for domain in domains:
            self.stdout.write('%s ...' % domain.name, ending='')
            try:
                self._sync_domain(domain)
                self.stdout.write(' synced')
            except Exception as e:
                self.stdout.write(' failed')
                msg = 'Error while processing {}: {}'.format(domain.name, e)
                raise CommandError(msg) 
Example #6
Source File: test_db.py    From casepro with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_clean(self):
        """
        Creates a clean database
        """
        self._log("Generating database...\n")

        try:
            has_data = Org.objects.exists()
        except Exception:  # pragma: no cover
            raise CommandError("Run migrate command first to create database tables")
        if has_data:
            raise CommandError("Can't clean database over non-empty database. Did you mean to use --resume?")

        # this is a new database so clear out redis
        self._log("Clearing out Redis cache... ")
        r = get_redis_connection()
        r.flushdb()
        self._log(self.style.SUCCESS("OK") + "\n")

        superuser = User.objects.create_superuser("root", "root@nyaruka.com", USER_PASSWORD)

        orgs = self.create_orgs(superuser, ORGS, GROUPS, FIELDS, PARTNERS, USER_PASSWORD)
        self.create_contacts(orgs, 100)

        return orgs 
Example #7
Source File: base.py    From DeerU with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, stdout=None, stderr=None, no_color=False):
        super().__init__(stdout, stderr, no_color)

        # 检测目录位置
        if self.NEED_PROJECT:
            settings_path = os.path.join(os.getcwd(), 'deeru')
            settings_py = os.path.join(settings_path, 'settings.py')

            if not os.path.exists(settings_py):
                raise CommandError('该命令需要在工程目录下运行')

        self.error = self.stderr.write

        info_out = OutputWrapper(sys.stdout)
        info_out.style_func = self.style.WARNING
        self.info = info_out.write

        success_out = OutputWrapper(sys.stdout)
        success_out.style_func = self.style.SUCCESS
        self.success = success_out.write 
Example #8
Source File: test_commands.py    From openwisp-ipam with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_export_subnet_command(self):
        subnet = self._create_subnet(subnet='10.0.0.0/24', name='Sample Subnet')
        self._create_ipaddress(
            ip_address='10.0.0.1', subnet=subnet, description='Testing'
        )
        self._create_ipaddress(
            ip_address='10.0.0.2', subnet=subnet, description='Testing'
        )
        self._create_ipaddress(ip_address='10.0.0.3', subnet=subnet)
        self._create_ipaddress(ip_address='10.0.0.4', subnet=subnet)
        out = StringIO()
        call_command('export_subnet', '10.0.0.0/24', stdout=out)
        self.assertIn('Successfully exported 10.0.0.0/24', out.getvalue())
        with self.assertRaises(CommandError):
            call_command('export_subnet', '11.0.0.0./24')
        with self.assertRaises(CommandError):
            call_command('export_subnet', '11.0.0.0/24') 
Example #9
Source File: purge_queue.py    From zulip with Apache License 2.0 6 votes vote down vote up
def handle(self, *args: Any, **options: str) -> None:
        def purge_queue(queue_name: str) -> None:
            queue = SimpleQueueClient()
            queue.ensure_queue(queue_name, lambda: None)
            queue.channel.queue_purge(queue_name)

        if options['all']:
            for queue_name in get_active_worker_queues():
                purge_queue(queue_name)
            print("All queues purged")
        elif not options['queue_name']:
            raise CommandError("Missing queue_name argument!")
        else:
            queue_name = options['queue_name']
            if not (queue_name in get_active_worker_queues() or
                    queue_name.startswith("notify_tornado")):
                raise CommandError(f"Unknown queue {queue_name}")

            print(f"Purging queue {queue_name}")
            purge_queue(queue_name)

        print("Done") 
Example #10
Source File: test_commands.py    From django-freeradius with GNU General Public License v3.0 6 votes vote down vote up
def test_batch_add_users_command(self):
        self.assertEqual(self.radius_batch_model.objects.all().count(), 0)
        path = self._get_path('static/test_batch.csv')
        options = dict(file=path, expiration='28-01-2018', name='test')
        self._call_command('batch_add_users', **options)
        self.assertEqual(self.radius_batch_model.objects.all().count(), 1)
        radiusbatch = self.radius_batch_model.objects.first()
        self.assertEqual(get_user_model().objects.all().count(), 3)
        self.assertEqual(radiusbatch.expiration_date.strftime('%d-%m-%y'), '28-01-18')
        path = self._get_path('static/test_batch_new.csv')
        options = dict(file=path, name='test1')
        self._call_command('batch_add_users', **options)
        self.assertEqual(self.radius_batch_model.objects.all().count(), 2)
        self.assertEqual(get_user_model().objects.all().count(), 6)
        invalid_csv_path = self._get_path('static/test_batch_invalid.csv')
        with self.assertRaises(CommandError):
            options = dict(file='doesnotexist.csv', name='test3')
            self._call_command('batch_add_users', **options)
        with self.assertRaises(SystemExit):
            options = dict(file=invalid_csv_path, name='test4')
            self._call_command('batch_add_users', **options) 
Example #11
Source File: syncnextcloudreleases.py    From appstore with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        oldest_supported = options.get('oldest_supported')
        token = settings.GITHUB_API_TOKEN
        base_url = settings.GITHUB_API_BASE_URL
        client = GitHubClient(base_url, token)

        try:
            releases = get_supported_releases(client, oldest_supported)
        except requests.HTTPError as e:
            raise CommandError('Could not get releases: ' + str(e))

        if options['print']:
            for release in releases:
                self.stdout.write(release)
        else:
            sync_releases(releases) 
Example #12
Source File: batch_add_users.py    From django-freeradius with GNU General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        try:
            csvfile = open(options['file'], 'rt')
        except IOError:
            raise CommandError('File does not exist')
        expiration_date = options['expiration']
        if expiration_date:
            expiration_date = datetime.strptime(expiration_date, '%d-%m-%Y')
        batch = self._create_batch(**options)
        batch.expiration_date = expiration_date
        batch.save()
        batch.csvfile.save(csvfile.name.split('/')[-1], File(csvfile))
        csvfile.seek(0)
        try:
            batch.csvfile_upload(csvfile, options['password_length'])
        except ValidationError:
            batch.delete()
            self.stdout.write('Error in uploading users from the file')
            sys.exit(1)
        self.stdout.write('Added a batch of users from a csv file')
        csvfile.close() 
Example #13
Source File: test_create_sites_and_partners.py    From course-discovery with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_missing_required_arguments(self):
        """
        Verify CommandError is raised when required arguments are missing.
        """

        # If a required argument is not specified the system should raise a CommandError
        with self.assertRaises(CommandError):
            call_command(
                "create_sites_and_partners",
                "--dns-name", self.dns_name,
            )

        with self.assertRaises(CommandError):
            call_command(
                "create_sites_and_partners",
                "--theme-path", self.theme_path,
            ) 
Example #14
Source File: test_api.py    From course-discovery with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_ingest_fails(self, alt_course, alt_currency, alt_mode, product_class, raises):
        """ Verify the proper warnings are logged when data objects are not present. """
        self.mock_courses_api()
        self.mock_products_api(
            alt_course=alt_course,
            alt_currency=alt_currency,
            alt_mode=alt_mode,
            product_class=product_class
        )
        with mock.patch(LOGGER_PATH) as mock_logger:
            if raises:
                with self.assertRaises(CommandError):
                    self.loader.ingest()
            else:
                self.loader.ingest()
            msg = self.compose_warning_log(alt_course, alt_currency, alt_mode, product_class)
            mock_logger.warning.assert_any_call(msg) 
Example #15
Source File: api.py    From course-discovery with GNU Affero General Public License v3.0 6 votes vote down vote up
def ingest(self):
        attempt_count = 0

        while (attempt_count == 0 or
               (self.processing_failure_occurred and attempt_count < EcommerceApiDataLoader.LOADER_MAX_RETRY)):
            attempt_count += 1
            if self.processing_failure_occurred and attempt_count > 1:  # pragma: no cover
                logger.info('Processing failure occurred attempting {attempt_count} of {max}...'.format(
                    attempt_count=attempt_count,
                    max=EcommerceApiDataLoader.LOADER_MAX_RETRY
                ))

            logger.info('Refreshing ecommerce data from %s...', self.partner.ecommerce_api_url)
            self._load_ecommerce_data()

            if self.processing_failure_occurred:  # pragma: no cover
                logger.warning('Processing failure occurred caused by an exception on at least on of the threads, '
                               'blocking deletes.')
                if attempt_count >= EcommerceApiDataLoader.LOADER_MAX_RETRY:
                    raise CommandError('Max retries exceeded and Ecommerce Data Loader failed to successfully load')
            else:
                self._delete_entitlements() 
Example #16
Source File: publish_live_course_runs.py    From course-discovery with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        failed = False
        now = datetime.datetime.now(pytz.UTC)
        course_runs = CourseRun.objects.filter(status=CourseRunStatus.Reviewed, go_live_date__lte=now)

        for course_run in course_runs:
            logger.info(_('Publishing course run {key}').format(key=course_run.key))

            try:
                course_run.publish()
            except Exception:  # pylint: disable=broad-except
                logger.exception(_('Failed to publish {key}').format(key=course_run.key))
                failed = True
            else:
                logger.info(_('Successfully published {key}').format(key=course_run.key))

        if failed:
            raise CommandError(_('One or more course runs failed to publish.')) 
Example #17
Source File: dbparams.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def handle(self, *args, **options):
        alias = options["alias"]

        try:
            settings_dict = connections[alias].settings_dict
        except ConnectionDoesNotExist:
            raise CommandError("Connection '{}' does not exist".format(alias))

        connection = connections[alias]
        if connection.vendor != "mysql":
            raise CommandError("{} is not a MySQL database connection".format(alias))

        show_mysql = options["mysql"]
        show_dsn = options["dsn"]
        if show_mysql and show_dsn:
            raise CommandError("Pass only one of --mysql and --dsn")
        elif not show_mysql and not show_dsn:
            show_mysql = True

        if show_mysql:
            self.output_for_mysql(settings_dict)
        elif show_dsn:
            self.output_for_dsn(settings_dict) 
Example #18
Source File: test_publish_live_course_runs.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_exception_does_not_stop_publishing(self, mock_publish):
        CourseRunFactory(status=CourseRunStatus.Reviewed, go_live_date=self.past)
        CourseRunFactory(status=CourseRunStatus.Reviewed, go_live_date=self.past)

        mock_publish.side_effect = [Exception, None]
        with self.assertRaises(CommandError):
            self.handle()

        self.assertEqual(mock_publish.call_count, 2) 
Example #19
Source File: test_unpublish_inactive_runs.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_exception_does_not_stop_command(self, mock_unpublish):
        CourseRunFactory(status=CourseRunStatus.Published)
        CourseRunFactory(status=CourseRunStatus.Published)

        mock_unpublish.side_effect = [UnpublishError, None]
        with self.assertRaises(CommandError):
            self.handle()

        self.assertEqual(mock_unpublish.call_count, 2) 
Example #20
Source File: test_delete_person_dups.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_args(self):
        partner_code = '--partner-code={}'.format(self.partner.short_code)
        uuid_arg = '{}:{}'.format(self.person.uuid, self.target.uuid)

        with self.assertRaises(CommandError) as cm:
            self.call_command(partner_code)  # no uuid
        self.assertEqual(cm.exception.args[0], 'You must specify at least one person')

        with self.assertRaises(CommandError) as cm:
            self.call_command(uuid_arg)  # no partner
        self.assertEqual(cm.exception.args[0], 'You must specify --partner-code')

        with self.assertRaises(Partner.DoesNotExist):
            self.call_command('--partner=NotAPartner', uuid_arg)

        with self.assertRaises(CommandError) as cm:
            self.call_command(partner_code, 'a')
        self.assertEqual(cm.exception.args[0], 'Malformed argument "a", should be in form of UUID:TARGET_UUID')

        with self.assertRaises(CommandError) as cm:
            self.call_command(partner_code, 'a:a')
        self.assertEqual(cm.exception.args[0], 'Malformed argument "a:a", UUIDs cannot be equal')

        with self.assertRaises(ValidationError):
            self.call_command(partner_code, 'a:b')

        with self.assertRaises(Person.DoesNotExist):
            self.call_command(partner_code, '00000000-0000-0000-0000-000000000000:00000000-0000-0000-0000-000000000001') 
Example #21
Source File: test_refresh_course_metadata.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_refresh_course_metadata_with_loader_exception(self):
        """ Verify execution continues if an individual data loader fails. """
        logger_target = 'course_discovery.apps.course_metadata.management.commands.refresh_course_metadata.logger'
        with mock.patch(logger_target) as mock_logger:
            with self.assertRaisesMessage(CommandError, 'One or more of the data loaders above failed.'):
                call_command('refresh_course_metadata')

            loader_classes = (
                CoursesApiDataLoader,
                EcommerceApiDataLoader,
                ProgramsApiDataLoader,
                AnalyticsAPIDataLoader,
            )
            expected_calls = [mock.call('%s failed!', loader_class.__name__) for loader_class in loader_classes]
            mock_logger.exception.assert_has_calls(expected_calls) 
Example #22
Source File: test_add_tag_to_courses.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def testMissingArgument(self):
        with self.assertRaises(CommandError):
            call_command('add_tag_to_courses', "tag0") 
Example #23
Source File: test_backfill_course_run_slugs_to_courses.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_missing_arguments(self):
        with self.assertRaises(CommandError):
            call_command('backfill_course_run_slugs_to_courses') 
Example #24
Source File: test_refresh_course_metadata.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_deletes_orphans(self, mock_delete_orphans):
        """ Verify execution culls any orphans left behind. """
        # Don't bother setting anything up - we expect to delete orphans on success or failure
        with self.assertRaisesMessage(CommandError, 'One or more of the data loaders above failed.'):
            call_command('refresh_course_metadata')

        self.assertEqual(mock_delete_orphans.call_count, 2)
        self.assertEqual({x[0][0] for x in mock_delete_orphans.call_args_list}, {Image, Video}) 
Example #25
Source File: remove_redirects_from_courses.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def handle(self, *args, **options):
        # using mutually exclusive argument groups in management commands is only supported in Django 2.2
        # so use XOR to check manually
        if not bool(options['args_from_database']) ^ (bool(options['url_paths']) ^ bool(options['remove_all'])):
            raise CommandError(_('Invalid arguments'))
        options_dict = options
        if options_dict['args_from_database']:
            options_dict = self.get_args_from_database()
        if options_dict['url_paths']:
            self.remove_redirects(options_dict['url_paths'])
            return
        if options_dict['remove_all']:
            self.remove_all_redirects() 
Example #26
Source File: test_commands.py    From credentials with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_facebook_configuration(self):
        """ Verify the Facebook app ID is required to enable Facebook sharing. """
        kwargs = {'enable_facebook_sharing': True}

        with self.assertRaisesMessage(CommandError, 'A Facebook app ID must be supplied to enable Facebook sharing'):
            self._call_command(site_domain=self.site.domain, site_name=self.site.name, **kwargs)

        kwargs['facebook_app_id'] = self.faker.word()
        self._call_command(site_domain=self.site.domain, site_name=self.site.name, **kwargs)

        site_configuration = self.site.siteconfiguration
        site_configuration.refresh_from_db()
        self.assertTrue(site_configuration.enable_facebook_sharing)
        self.assertEqual(site_configuration.facebook_app_id, kwargs['facebook_app_id']) 
Example #27
Source File: test_api.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_seat_types_for_course_type(self):
        self.mock_courses_api()

        # Assign CourseType and CourseRunType values, which will conflict with the attempted verified seat type
        course_run = CourseRun.objects.get(key='verified/course/run')
        course_run.type = CourseRunType.objects.get(slug=CourseRunType.PROFESSIONAL)
        course_run.save()
        course = course_run.course
        course.type = CourseType.objects.get(slug=CourseType.PROFESSIONAL)
        course.save()

        self.mock_products_api(alt_course=str(course.uuid))

        with mock.patch(LOGGER_PATH) as mock_logger:
            with self.assertRaises(CommandError):
                self.loader.ingest()
            mock_logger.warning.assert_any_call(
                'Seat type verified is not compatible with course type professional for course {uuid}'.format(
                    uuid=course.uuid
                )
            )
            mock_logger.warning.assert_any_call(
                'Seat type verified is not compatible with course run type professional for course run {key}'.format(
                    key=course_run.key,
                )
            )

        course.refresh_from_db()
        course_run.refresh_from_db()
        self.assertEqual(course.entitlements.count(), 0)
        self.assertEqual(course_run.seats.count(), 0) 
Example #28
Source File: test_commands.py    From credentials with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_missing_arguments(self, command_args):
        """ Verify CommandError is raised when required arguments are missing """
        with self.assertRaises(CommandError):
            call_command(self.COMMAND_NAME, *command_args) 
Example #29
Source File: import_mappings.py    From ocl_web with Mozilla Public License 2.0 5 votes vote down vote up
def handle(self, *args, **options):

        if len(args) != 1:
            raise CommandError('mapping input text file is required.')

        username = options['username']

        if username is None:
            raise CommandError('--username is required.')

        self.ORG_ID = options['org_id']
        if self.ORG_ID is None:
            raise CommandError('--org_id is required.')

        self.SOURCE_ID = options['source_id']
        if self.SOURCE_ID is None:
            raise CommandError('--source_id is required.')

        input_file = args[0]
        if not os.path.exists(input_file):
            raise CommandError('Could not find input file %s' % input_file)

        try:
            self.input = open(input_file, 'rb')
            # get total record count
            self.total = sum(1 for line in self.input)
            self.input.seek(0)
        except IOError:
            raise CommandError('Could not open input file %s' % input_file)

        self.load_user(username)
        self.login()

        self.load_mappings() 
Example #30
Source File: process_queue.py    From django-eb-sqs with MIT License 5 votes vote down vote up
def handle(self, *args, **options):
        if not options['queue_names']:
            raise CommandError('Queue names (--queues) not specified')

        queue_names = [queue_name.rstrip() for queue_name in options['queue_names'].split(',')]

        WorkerService().process_queues(queue_names)