當前位置: 首頁>>代碼示例>>Python>>正文


Python six.StringIO方法代碼示例

本文整理匯總了Python中django.utils.six.StringIO方法的典型用法代碼示例。如果您正苦於以下問題:Python six.StringIO方法的具體用法?Python six.StringIO怎麽用?Python six.StringIO使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.utils.six的用法示例。


在下文中一共展示了six.StringIO方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: webhook_pull

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import StringIO [as 別名]
def webhook_pull(request, remote='origin'):
    if request.method == 'POST':
        try:
            log = Git().pull(remote)
            s = StringIO()
            call_command('sync_waliki', stdout=s)
            s.seek(0)
            r = {'pull': log, 'sync': s.read()}
            status_code = 200
        except Exception as e:
            r = {'error': text_type(e)}
            status_code = 500
        return HttpResponse(json.dumps(r), status=status_code,
                            content_type="application/json")

    return HttpResponse("POST to %s" % reverse("waliki_webhook_pull", args=(remote,))) 
開發者ID:mgaitan,項目名稱:waliki,代碼行數:18,代碼來源:views.py

示例2: test_dump_latest

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import StringIO [as 別名]
def test_dump_latest(self):
        out = StringIO()
        management.call_command("dump_latest", stdout=out)
        self.assertIn("Dumping 0 events", out.getvalue())

        ev = utils.create_event()
        management.call_command("dump_latest", stdout=out)
        self.assertIn("Dumping 1 events", out.getvalue())

        with open("out.json", "r") as f:
            data = f.read()
        out = json.loads(data)
        count = 0
        for entry in out:
            if entry["model"] == "ci.event":
                self.assertEqual(ev.pk, entry["pk"])
                count = 1
        self.assertEqual(count, 1) 
開發者ID:idaholab,項目名稱:civet,代碼行數:20,代碼來源:test_commands.py

示例3: test_user_access

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import StringIO [as 別名]
def test_user_access(self, mock_get):
        out = StringIO()
        mock_get.return_value = utils.Response(status_code=404)
        with self.assertRaises(CommandError):
            management.call_command("user_access", stdout=out)
        with self.assertRaises(models.GitUser.DoesNotExist):
            management.call_command("user_access", "--master", "nobody", stdout=out)
        with self.assertRaises(CommandError):
            management.call_command("user_access", "--master", self.owner.name, stdout=out)

        out = StringIO()
        management.call_command("user_access", "--master", self.build_user.name, stdout=out)

        repo1 = {'name': 'repo1', 'owner': {'login': 'owner'} }
        repo2 = {'name': 'repo2', 'owner': {'login': 'owner'} }
        mock_get.side_effect = [utils.Response([repo1]), utils.Response([repo2])]

        out = StringIO()
        management.call_command("user_access", "--master", self.build_user.name, "--user", "owner", stdout=out) 
開發者ID:idaholab,項目名稱:civet,代碼行數:21,代碼來源:test_commands.py

示例4: test_deletion_fails

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import StringIO [as 別名]
def test_deletion_fails(self):
        """
        Verify '-y' skips confirmation and errors are logged
        """
        out = StringIO()
        err = StringIO()
        call_command('delete_archived', '-y', '3', stdout=out, stderr=err)
        self.assertTrue('Found 1 archived instances older than 3 months' in out.getvalue())

        self.assertTrue('Deleting old.example.com' in out.getvalue())
        self.assertTrue('Deleting new.example.com' not in out.getvalue())
        self.assertTrue('Deleting newer.example.com' not in out.getvalue())

        self.assertTrue('Failed to delete Instance' in out.getvalue())
        self.assertTrue('Failed to delete Instance' in err.getvalue())
        self.assertTrue('Traceback' in out.getvalue())
        self.assertTrue('Deleted 0 archived instances older than 3 months' in out.getvalue()) 
開發者ID:open-craft,項目名稱:opencraft,代碼行數:19,代碼來源:test_delete_archived.py

示例5: test_ref_without_instance

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import StringIO [as 別名]
def test_ref_without_instance(self, mock_delete, mock_ref_delete):
        """
        Verify deletion proceeds when an InstanceReference does not point to
        an OpenEdxInstance.
        """
        # Create instanceless InstanceReference
        ref = InstanceReference.objects.create(
            name='Instanceless', instance_id=999, instance_type_id=13, is_archived=True)
        ref.modified -= timedelta(days=365)
        ref.save(update_modified=False)

        # Run command
        out = StringIO()
        call_command('delete_archived', '10', stdout=out)

        # Check only the InstanceReference queryset gets deleted
        self.assertTrue('Found 1 archived instances older than 10 months' in out.getvalue())
        self.assertTrue('Instanceless: No instance associated' in out.getvalue())
        self.assertTrue('Deleted 1 archived instances older than 10 months' in out.getvalue())
        self.assertEqual(mock_delete.call_count, 0)
        self.assertEqual(mock_ref_delete.call_count, 1) 
開發者ID:open-craft,項目名稱:opencraft,代碼行數:23,代碼來源:test_delete_archived.py

示例6: test_migrate

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import StringIO [as 別名]
def test_migrate(self, mock_spawn_appserver):
        """
        Verify that the command correctly migrate an instance to use external databases.
        """
        try:
            OpenEdXInstance.objects.create(
                sub_domain='test_migrate', use_ephemeral_databases=True, name='test_migrate instance')
            with LogCapture() as captured_logs:
                call_command(
                    'migrate_ephemeral',
                    stdout=StringIO(),
                )
                # Verify the logs
                actual = set(l[2] for l in captured_logs.actual())
                expected = {
                    'Found "1" instances using ephemeral databases',
                    'Migrated and started provisioning a new app server for test_migrate instance',
                }
                self.assertTrue(expected <= actual)

            self.assertTrue(mock_spawn_appserver.called)
        except TypeError:
            # Field already removed from database
            pass 
開發者ID:open-craft,項目名稱:opencraft,代碼行數:26,代碼來源:test_migrate_ephemeral.py

示例7: test_consul_skip_update

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import StringIO [as 別名]
def test_consul_skip_update(self):
        """
        Tests the management command with skipping metadata update option.

        :param purge_consul_metadata: purge_consul_metadata method mock
        """
        out = StringIO()

        # Archive the instances
        instances = [OpenEdXInstanceFactory.create() for _ in range(10)]
        for instance in instances:
            instance.ref.is_archived = True
            instance.ref.save()

        # Add some garbage data to consul
        bad_prefix = settings.CONSUL_PREFIX.format(ocim=settings.OCIM_ID, instance=333)
        self.client.kv.put(bad_prefix, json.dumps({'key1': 'value1', 'key2': 'value2'}).encode('utf-8'))

        call_command('update_metadata', skip_update=True, stdout=out)
        objects_count = OpenEdXInstance.objects.count()

        self.assertIn('Cleaning metadata for {} archived instances...'.format(objects_count + 1), out.getvalue())
        self.assertIn('Successfully cleaned archived instances\' metadata', out.getvalue())
        self.assertNotIn('Updating {} instances\' metadata'.format(objects_count + 1), out.getvalue()) 
開發者ID:open-craft,項目名稱:opencraft,代碼行數:26,代碼來源:test_update_metadata.py

示例8: test_archiving_instances_by_file

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import StringIO [as 別名]
def test_archiving_instances_by_file(self, filename, expected_archived_count,
                                         mock_deprovision_rabbitmq, *mock):
        """
        Test archiving instances from domains listed in a file.
        """
        instances = self.create_test_instances('ABCDEFGH')

        out = StringIO()
        fp = get_fixture_filepath(os.path.join('management', filename))
        with open(fp, 'r') as f:
            domains = [line.strip() for line in f.readlines()]
        call_command('archive_instances', '--file=%s' % fp, stdout=out)
        self.assertRegex(
            out.getvalue(),
            r'.*Archived {archived_count} instances \(from {domains_count} domains\).'.format(
                archived_count=expected_archived_count, domains_count=len(domains)
            )
        )
        for domain in domains:
            instance = instances[domain]['instance']
            instance.refresh_from_db()
            self.assertTrue(instance.ref.is_archived)
        self.assertEqual(mock_deprovision_rabbitmq.call_count, expected_archived_count) 
開發者ID:open-craft,項目名稱:opencraft,代碼行數:25,代碼來源:test_archive_instances.py

示例9: test_archive_exception_handling

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import StringIO [as 別名]
def test_archive_exception_handling(self, mock_disable_monitoring, *mock):
        """
        Verify that if an instance fails to be archived, the other instances are still being archived.
        """
        instances = self.create_test_instances('ABCD')
        domains = instances.keys()

        # mock instance.disable_monitoring() method to raise exception for the first instance
        mock_disable_monitoring.side_effect = [Exception('disable_monitoring'), None, None, None]

        out = StringIO()
        call_command(
            'archive_instances',
            '--domains=%s' % ','.join(domains),
            stdout=out
        )
        self.assertRegex(out.getvalue(), r'.*Archived 3 instances \(from 4 domains\).')
        self.assertRegex(out.getvalue(), r'.*Failed to archive A.example.com.')
        self.assertEqual(
            OpenEdXInstance.objects.filter(internal_lms_domain__in=domains, ref_set__is_archived=True).count(),
            3
        ) 
開發者ID:open-craft,項目名稱:opencraft,代碼行數:24,代碼來源:test_archive_instances.py

示例10: create_journals

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import StringIO [as 別名]
def create_journals():
    """
    Creates a set of dummy journals for testing
    :return: a 2-tuple of two journals
    """
    update_xsl_files()
    journal_one = journal_models.Journal(code="TST", domain="testserver")
    journal_one.save()

    journal_two = journal_models.Journal(code="TSA", domain="journal2.localhost")
    journal_two.save()

    out = StringIO()
    sys.stdout = out

    call_command('load_default_settings', stdout=out)

    journal_one.name = 'Journal One'
    journal_two.name = 'Journal Two'

    return journal_one, journal_two 
開發者ID:BirkbeckCTP,項目名稱:janeway,代碼行數:23,代碼來源:helpers.py

示例11: validate

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import StringIO [as 別名]
def validate(self, app=None, display_num_errors=False):
        """
        Validates the given app, raising CommandError for any errors.

        If app is None, then this will validate all installed apps.

        """
        from django.core.management.validation import get_validation_errors
        s = StringIO()
        num_errors = get_validation_errors(s, app)
        if num_errors:
            s.seek(0)
            error_text = s.read()
            raise CommandError("One or more models did not validate:\n%s" % error_text)
        if display_num_errors:
            self.stdout.write("%s error%s found" % (num_errors, num_errors != 1 and 's' or '')) 
開發者ID:blackye,項目名稱:luscan-devel,代碼行數:18,代碼來源:base.py

示例12: test_with_commit

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import StringIO [as 別名]
def test_with_commit(self):
        """ Verify the command, when called with the commit flag, deletes baskets with orders. """
        # Verify we have baskets with orders
        self.assertEqual(Basket.objects.filter(order__isnull=False).count(), len(self.orders + self.invoiced_orders))

        # Verify we have invoiced baskets
        self.assertEqual(Basket.objects.filter(invoice__isnull=False).count(), len(self.invoiced_baskets))

        # Call the command with the commit flag
        out = StringIO()
        call_command(self.command, commit=True, stderr=out)

        # Verify baskets with orders deleted, except for those which are invoiced
        self.assertEqual(list(Basket.objects.all()), self.unordered_baskets + self.invoiced_baskets)

        # Verify info was output to stderr
        actual = out.getvalue().strip()
        self.assertTrue(actual.startswith('Deleting [{}] baskets.'.format(len(self.orders))))
        self.assertTrue(actual.endswith('All baskets deleted.')) 
開發者ID:edx,項目名稱:ecommerce,代碼行數:21,代碼來源:test_commands.py

示例13: test_without_commit

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import StringIO [as 別名]
def test_without_commit(self):
        """ Verify the command does not modify any baskets, if the commit flag is not specified. """
        queryset = Basket.objects.filter(site__isnull=True)
        expected = queryset.count()

        # Call the command with dry-run flag
        out = StringIO()
        call_command(self.command, site_id=self.site.id, commit=False, stderr=out)

        # Verify no baskets affected
        self.assertEqual(queryset.count(), expected)

        # Verify the number of baskets expected to be deleted was printed to stderr
        expected = 'This has been an example operation. If the --commit flag had been included, the command ' \
                   'would have associated [{}] baskets with site [{}].'.format(len(self.unassociated_baskets),
                                                                               self.site)
        self.assertEqual(out.getvalue().strip(), expected) 
開發者ID:edx,項目名稱:ecommerce,代碼行數:19,代碼來源:test_commands.py

示例14: test_dumpdata

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import StringIO [as 別名]
def test_dumpdata(self):
        "dumpdata honors allow_migrate restrictions on the router"
        User.objects.create_user('alice', 'alice@example.com')
        User.objects.db_manager('default').create_user('bob', 'bob@example.com')

        # dumping the default database doesn't try to include auth because
        # allow_migrate prohibits auth on default
        new_io = StringIO()
        management.call_command('dumpdata', 'auth', format='json', database='default', stdout=new_io)
        command_output = new_io.getvalue().strip()
        self.assertEqual(command_output, '[]')

        # dumping the other database does include auth
        new_io = StringIO()
        management.call_command('dumpdata', 'auth', format='json', database='other', stdout=new_io)
        command_output = new_io.getvalue().strip()
        self.assertIn('"email": "alice@example.com"', command_output) 
開發者ID:denisenkom,項目名稱:django-sqlserver,代碼行數:19,代碼來源:tests.py

示例15: test_args

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import StringIO [as 別名]
def test_args(self):
        pre_migrate_receiver = Receiver(signals.pre_migrate)
        post_migrate_receiver = Receiver(signals.post_migrate)
        management.call_command(
            'migrate', database=MIGRATE_DATABASE, verbosity=MIGRATE_VERBOSITY,
            interactive=MIGRATE_INTERACTIVE, stdout=six.StringIO(),
        )

        for receiver in [pre_migrate_receiver, post_migrate_receiver]:
            args = receiver.call_args
            self.assertEqual(receiver.call_counter, 1)
            self.assertEqual(set(args), set(SIGNAL_ARGS))
            self.assertEqual(args['app_config'], APP_CONFIG)
            self.assertEqual(args['verbosity'], MIGRATE_VERBOSITY)
            self.assertEqual(args['interactive'], MIGRATE_INTERACTIVE)
            self.assertEqual(args['using'], 'default')
            self.assertEqual(args['plan'], [])
            self.assertIsInstance(args['apps'], migrations.state.StateApps) 
開發者ID:denisenkom,項目名稱:django-sqlserver,代碼行數:20,代碼來源:tests.py


注:本文中的django.utils.six.StringIO方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。