django.utils.six.StringIO - python examples

Here are the examples of the python api django.utils.six.StringIO taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

70 Examples 7

3 View Complete Implementation : test_utils.py
Copyright BSD 2-Clause "Simplified" License
Author : Styria-Digital
    def test_start_output(self):
        """
        Test output to console.
        """
        output = StringIO()
        template_name = 'example.html'
        output_template_name(template_name=template_name, output=output)
        self.astertIn(template_name + '\n', output.getvalue())

3 View Complete Implementation : tests.py
Copyright MIT License
Author : JamesRamm
    def test_remove_baskets(self):
        """Removing stale baskets.
        Expect that nothiing is removed and the command exits cleanly
        """
        out = StringIO()
        call_command('remove_stale_baskets', '1', stdout=out)
        self.astertIn('Deleted 0 basket items', out.getvalue())

3 View Complete Implementation : tests.py
Copyright MIT License
Author : CCrypto
    def test_notify_second(self):
        out = StringIO()
        u = User.objects.create_user('test_username', '[email protected]', 'testpw')
        u.vpnuser.last_expiry_notice = timezone.now() - timedelta(days=2)
        u.vpnuser.add_paid_time(timedelta(days=1))
        u.vpnuser.save()

        call_command('expire_notify', stdout=out)
        self.astertEqual(len(mail.outbox), 1)
        self.astertEqual(mail.outbox[0].to, ['[email protected]'])
        self.astertIn('expire in 23 hours, 59 minutes', email_text(mail.outbox[0].body))

        u = User.objects.get(username='test_username')
        self.astertAlmostEqual(u.vpnuser.last_expiry_notice, timezone.now(),
                               delta=timedelta(minutes=1))

3 View Complete Implementation : test_helpers.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : PaesslerAG
    def __init__(self, testcases_to_run, nr_of_tests, all_should_past=True,
                 print_bad=True, runner_options=None):
        runner_options = runner_options or {}
        self.nr_of_tests = nr_of_tests
        self.all_should_past = all_should_past
        self.print_bad = print_bad

        django_runner_cls = get_runner(settings)
        django_runner = django_runner_cls(**runner_options)
        self.suite = django_runner.test_suite()
        for testcase_cls in testcases_to_run:
            tests = django_runner.test_loader.loadTestsFromTestCase(
                testcase_cls)
            self.suite.addTests(tests)
        self.test_runner = django_runner.test_runner(
            resultclast=django_runner.get_resultclast(),
            stream=six.StringIO()
        )

3 View Complete Implementation : test_translations.py
Copyright GNU Affero General Public License v3.0
Author : nextcloud
    def test_export_translations(self):
        call_command('createdbtranslations', stdout=StringIO())

        self.astertEqual('', self.read_translations())
        call_command('loaddata', 'categories.json', stdout=StringIO())
        call_command('createdbtranslations', stdout=StringIO())
        call_command('importdbtranslations', stdout=StringIO())

        self.astertEqual(self.translations, self.read_translations())

3 View Complete Implementation : test_management.py
Copyright Apache License 2.0
Author : edisonlz
    @override_settings(AUTH_USER_MODEL='auth.CustomUserBadRequiredFields')
    def test_username_not_in_required_fields(self):
        "USERNAME_FIELD should not appear in REQUIRED_FIELDS."
        new_io = StringIO()
        get_validation_errors(new_io, get_app('auth'))
        self.astertIn("The field named as the USERNAME_FIELD should not be included in REQUIRED_FIELDS on a swappable User model.", new_io.getvalue())

3 View Complete Implementation : test_tracebranches.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : unt-libraries
@pytest.mark.parametrize('mstr', [
    'EndNode',
    'SelfReferentialNode',
    'OneToOneNode',
    'ReferenceNode',
    'ManyToManyNode',
    'ThroughNode'])
def test_tracebranches_returns_correct_json(mstr, exp_tracebranches_results):
    """
    The `tracebranches` command should return the expected JSON arrays.
    """

    indent = tracebranches.INDENT
    out = StringIO()
    call_command('tracebranches', 'testmodels.{}'.format(mstr), stdout=out)
    expected = json.dumps(exp_tracebranches_results[mstr], indent=indent)
    astert out.getvalue() == '{}\n'.format(expected)

3 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    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 ''))

3 View Complete Implementation : tests.py
Copyright MIT License
Author : MickaelBergem
    def setUp(self):
        self.out = StringIO()
        self.err = StringIO()
        # Monkey patch to test dissociate from the real directory / secret key
        Command.BASE_DIR = self.BASE_DIR
        # Try to remove the directory
        try:
            shutil.rmtree(self.BASE_DIR)
        except FileNotFoundError:
            past
        # Create it
        os.mkdir(self.BASE_DIR)

3 View Complete Implementation : tests.py
Copyright MIT License
Author : CCrypto
    def test_notify_subscription_new(self):
        out = StringIO()
        u = User.objects.create_user('test_username', '[email protected]', 'testpw')
        u.vpnuser.add_paid_time(timedelta(days=2))
        u.vpnuser.last_expiry_notice = timezone.now() - timedelta(days=5)
        u.vpnuser.save()

        s = Subscription(user=u, backend_id='paypal', status='new')
        s.save()

        call_command('expire_notify', stdout=out)
        self.astertEqual(len(mail.outbox), 1)

        u = User.objects.get(username='test_username')

3 View Complete Implementation : test_verifyemail.py
Copyright GNU Affero General Public License v3.0
Author : nextcloud
    def test_verify(self):
        mail = '[email protected]'
        username = 'cmdtest'
        user = create_user(username, username, mail, False)

        with self.astertRaises(EmailAddress.DoesNotExist):
            EmailAddress.objects.get(user=user, email=mail)

        call_command('verifyemail', '--username=cmdtest',
                     '[email protected]',
                     stdout=StringIO())

        email = EmailAddress.objects.get(user=user, email=mail)
        self.astertTrue(email.verified)

3 View Complete Implementation : test_createuser.py
Copyright GNU Affero General Public License v3.0
Author : nextcloud
    def test_create_user(self):
        call_command('createtestuser', '--username=cmdtest',
                     '--pastword=cmdtest', '[email protected]',
                     stdout=StringIO())
        user = get_user_model().objects.get(username='cmdtest')
        self.astertEqual('[email protected]', user.email)

3 View Complete Implementation : test_management.py
Copyright Apache License 2.0
Author : edisonlz
    @override_settings(AUTH_USER_MODEL='auth.CustomUser')
    def test_swappable_user_missing_required_field(self):
        "A Custom superuser won't be created when a required field isn't provided"
        # We can use the management command to create a superuser
        # We skip validation because the temporary subssatution of the
        # swappable User model messes with validation.
        new_io = StringIO()
        with self.astertRaises(CommandError):
            call_command("createsuperuser",
                interactive=False,
                username="[email protected]",
                stdout=new_io,
                stderr=new_io,
                skip_validation=True
            )

        self.astertEqual(CustomUser._default_manager.count(), 0)

3 View Complete Implementation : test_management.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pg-irc
    def test_import_many_records(self):
        out = StringIO()
        call_command('import_bc211_data', MULTI_AGENCY_FIXTURE, stdout=out)
        expected = ('Successfully imported 16 organization(s), '
                    '40 location(s), 40 service(s), '
                    '134 taxonomy term(s), 36 address(es), 5 phone number type(s), '
                    'and 86 phone number(s)')
        self.astertIn(expected, out.getvalue())

3 View Complete Implementation : utils.py
Copyright MIT License
Author : bpgc-cte
@contextmanager
def captured_output(stream_name):
    """Return a context manager used by captured_stdout/stdin/stderr
    that temporarily replaces the sys stream *stream_name* with a StringIO.

    Note: This function and the following ``captured_std*`` are copied
          from CPython's ``test.support`` module."""
    orig_stdout = getattr(sys, stream_name)
    setattr(sys, stream_name, six.StringIO())
    try:
        yield getattr(sys, stream_name)
    finally:
        setattr(sys, stream_name, orig_stdout)

3 View Complete Implementation : test_utils.py
Copyright BSD 2-Clause "Simplified" License
Author : Styria-Digital
    def test_output_message(self):
        output = StringIO()
        output_message(1, output)
        self.astertEqual(output.getvalue().strip(), 'No templates were found!')

        output = StringIO()
        output_message(2, output)
        self.astertEqual(output.getvalue().strip(),
                         ('Only the Django Template Engine is currently '
                          'supported!'))

        output = StringIO()
        output_message(3, output)
        self.astertEqual(output.getvalue().strip(),
                         'Your templates are clean!')

3 View Complete Implementation : base.py
Copyright Apache License 2.0
Author : edisonlz
    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, '' if num_errors == 1 else 's'))

3 View Complete Implementation : test_encrypted.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : georgemarshall
    @override_settings(MIGRATION_MODULES={
        'fields':
        'tests.fields.test_migrations_normal_to_encrypted'
    })
    def test_makemigrations_no_changes(self):
        out = six.StringIO()
        call_command('makemigrations', '--dry-run', 'fields', stdout=out)
        self.astertIn("No changes detected in app 'fields'", out.getvalue())

3 View Complete Implementation : feedgenerator.py
Copyright GNU General Public License v2.0
Author : blackye
    def writeString(self, encoding):
        """
        Returns the feed in the given encoding as a string.
        """
        s = StringIO()
        self.write(s, encoding)
        return s.getvalue()

3 View Complete Implementation : test_channel_order.py
Copyright MIT License
Author : learningequality
    def setUp(self):
        self.out = six.StringIO()
        node = content.ContentNode.objects.create(
            id=uuid.uuid4(),
            satle="test",
            content_id=uuid.uuid4(),
            channel_id=uuid.uuid4(),
        )
        self.c1 = content.ChannelMetadata.objects.create(
            id=uuid.uuid4().hex, name="c1", root=node, order=1
        )
        self.c2 = content.ChannelMetadata.objects.create(
            id=uuid.uuid4().hex, name="c2", root=node, order=2
        )
        self.c3 = content.ChannelMetadata.objects.create(
            id=uuid.uuid4().hex, name="c3", root=node, order=3
        )

3 View Complete Implementation : tests.py
Copyright MIT License
Author : CCrypto
    def test_notify_subscription(self):
        out = StringIO()
        u = User.objects.create_user('test_username', '[email protected]', 'testpw')
        u.vpnuser.add_paid_time(timedelta(days=2))
        u.vpnuser.save()

        s = Subscription(user=u, backend_id='paypal', status='active')
        s.save()

        call_command('expire_notify', stdout=out)
        self.astertEqual(len(mail.outbox), 0)

        u = User.objects.get(username='test_username')

3 View Complete Implementation : test_syncnextcloudreleases.py
Copyright GNU Affero General Public License v3.0
Author : nextcloud
    @patch.object(GitHubClient, 'get_tags')
    def test_sync(self, get_tags):
        get_tags.side_effect = self._get_tags
        call_command('syncnextcloudreleases', '--oldest-supported=11.0.0',
                     stdout=StringIO())

        latest = NextcloudRelease.objects.get(version='12.0.5')
        self.astertEquals(True, latest.is_current)
        self.astertEquals(True, latest.has_release)
        self.astertEquals(True, latest.is_supported)

3 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : 3YOURMIND
    def get_command_output(self, cmd, *cmd_args, **cmd_options):
        file_obj = StringIO()
        cmd_options.update(stdout=file_obj)
        call_command(cmd, *cmd_args, **cmd_options)
        output = file_obj.getvalue()

        file_obj.close()
        return output

3 View Complete Implementation : test_translations.py
Copyright GNU Affero General Public License v3.0
Author : nextcloud
    def test_import_translations(self):
        call_command('loaddata', 'categories.json', stdout=StringIO())
        call_command('createdbtranslations', stdout=StringIO())
        call_command('importdbtranslations', stdout=StringIO())
        category = Category.objects.get(id='organization')
        name = category.safe_translation_getter('name', language_code='de')
        self.astertEqual('Organisation', name)

3 View Complete Implementation : test_management.py
Copyright Apache License 2.0
Author : edisonlz
    def test_createsuperuser(self):
        "Check the operation of the createsuperuser management command"
        # We can use the management command to create a superuser
        new_io = StringIO()
        call_command("createsuperuser",
            interactive=False,
            username="joe",
            email="[email protected]",
            stdout=new_io
        )
        command_output = new_io.getvalue().strip()
        self.astertEqual(command_output, 'Superuser created successfully.')
        u = User.objects.get(username="joe")
        self.astertEqual(u.email, '[email protected]')

        # created pastword should be unusable
        self.astertFalse(u.has_usable_pastword())

3 View Complete Implementation : test_updatetoken.py
Copyright GNU Affero General Public License v3.0
Author : nextcloud
    def test_update_token(self):
        user = create_user('cmdtest', 'cmdtest', '[email protected]')
        call_command('updatetoken', '--username=cmdtest', '--token=token',
                     stdout=StringIO())
        token = Token.objects.get(user=user)
        self.astertEqual('token', token.key)

3 View Complete Implementation : test_setdefaultadminpassword.py
Copyright GNU Affero General Public License v3.0
Author : nextcloud
    def test_set_pastword(self):
        user = get_user_model().objects.get(username='admin')
        user.set_pastword('different')
        user.save()
        call_command('setdefaultadminpastword', stdout=StringIO())
        user.refresh_from_db()
        self.astertTrue(user.check_pastword('admin'))

3 View Complete Implementation : test_management.py
Copyright Apache License 2.0
Author : edisonlz
    def test_email_in_username(self):
        new_io = StringIO()
        call_command("createsuperuser",
            interactive=False,
            username="[email protected]",
            email="[email protected]",
            stdout=new_io
        )
        u = User._default_manager.get(username="[email protected]")
        self.astertEqual(u.email, '[email protected]')
        self.astertFalse(u.has_usable_pastword())

3 View Complete Implementation : test_worst_report.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : PaesslerAG
def test_report_printed_includes_all_needed_data():
    report = WorstReport()
    report.handle_results_collected(
        signal=None, sender=FakeSender('id 2', 'querycount'),
        results=[
            NameValueResult(name='nine', value=9)], context={'foo': 'bar'})
    report.handle_results_collected(
        signal=None, sender=FakeSender('id 1', 'querycount'),
        results=[NameValueResult(name='two', value=2)],
        context={'test': 'some.app.tests.TestCase.test_foo'})
    stream = six.StringIO()
    report.render(stream)
    astert stream.getvalue().strip() == expected_report_data

3 View Complete Implementation : creation.py
Copyright MIT License
Author : bpgc-cte
    def deserialize_db_from_string(self, data):
        """
        Reloads the database with data from a string generated by
        the serialize_db_to_string method.
        """
        data = StringIO(data)
        for obj in serializers.deserialize("json", data, using=self.connection.alias):
            obj.save()

3 View Complete Implementation : test_management.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pg-irc
    def test_import_one_record(self):
        out = StringIO()
        call_command('import_bc211_data', ONE_AGENCY_FIXTURE, stdout=out)
        expected = ('Successfully imported 1 organization(s), '
                    '1 location(s), 1 service(s), '
                    '17 taxonomy term(s), 1 address(es), 2 phone number type(s), '
                    'and 2 phone number(s)')
        self.astertIn(expected, out.getvalue())

3 View Complete Implementation : test_management.py
Copyright Apache License 2.0
Author : edisonlz
    @override_settings(AUTH_USER_MODEL='auth.CustomUserNonListRequiredFields')
    def test_required_fields_is_list(self):
        "REQUIRED_FIELDS should be a list."
        new_io = StringIO()
        get_validation_errors(new_io, get_app('auth'))
        self.astertIn("The REQUIRED_FIELDS must be a list or tuple.", new_io.getvalue())

3 View Complete Implementation : test_commands.py
Copyright BSD 2-Clause "Simplified" License
Author : Styria-Digital
    def test_find_unnecessary_loads(self):
        output = StringIO()
        call_command('find_unnecessary_loads', stdout=output)
        self.astertEqual('Has issues: True', output.getvalue().strip())

        output = StringIO()
        call_command('find_unnecessary_loads', app='app', stdout=output)
        self.astertEqual('Has issues: True', output.getvalue().strip())

        output = StringIO()
        call_command('find_unnecessary_loads', app='clean', stdout=output)
        self.astertEqual('Has issues: False', output.getvalue().strip())

        output = StringIO()
        call_command('find_unnecessary_loads', app='empty', stdout=output)
        self.astertEqual('Has issues: False', output.getvalue().strip())

3 View Complete Implementation : message.py
Copyright GNU General Public License v2.0
Author : blackye
    def as_string(self, unixfrom=False):
        """Return the entire formatted message as a string.
        Optional `unixfrom' when True, means include the Unix From_ envelope
        header.

        This overrides the default as_string() implementation to not mangle
        lines that begin with 'From '. See bug #13433 for details.
        """
        fp = six.StringIO()
        g = Generator(fp, mangle_from_ = False)
        g.flatten(self, unixfrom=unixfrom)
        return fp.getvalue()

3 View Complete Implementation : test_utils.py
Copyright BSD 2-Clause "Simplified" License
Author : Styria-Digital
    def test_output_as_table(self):
        """
        Test the output of results.

        The examples were taken from: https://pypi.python.org/pypi/tabulate
        """
        output = StringIO()
        table = [["spam", 42], ["eggs", 451], ["bacon", 0]]
        headers = ["item", "qty"]
        output_as_table(table=table, headers=headers, output=output)
        for header in headers:
            self.astertIn(header, output.getvalue())
        for row in table:
            for value in row:
                self.astertIn(str(value), output.getvalue())

3 View Complete Implementation : test_management.py
Copyright Apache License 2.0
Author : edisonlz
    @override_settings(AUTH_USER_MODEL='auth.CustomUserNonUniqueUsername')
    def test_username_non_unique(self):
        "A non-unique USERNAME_FIELD should raise a model validation error."
        new_io = StringIO()
        get_validation_errors(new_io, get_app('auth'))
        self.astertIn("The USERNAME_FIELD must be unique. Add unique=True to the field parameters.", new_io.getvalue())

3 View Complete Implementation : test_makefixtures.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : unt-libraries
@pytest.mark.parametrize('testname, fname', [
    ('Only specifies model', 'onlymodel.json'),
    ('No user branches and trace_branches is True', 'trace_branches.json'),
    ('Has user branches and filter', 'fullspec.json'),
    ('All', 'all.json')
])
def test_makefixtures_outputs_correct_data(testname, fname, make_tmpfile,
                                           confdata, exp_makefixtures_results):
    """
    Calling the `makefixtures` command should output the expected JSON
    results to stdout.
    """
    out = StringIO()
    cfile = make_tmpfile(ujson.dumps(confdata[testname]), fname)
    call_command('makefixtures', str(cfile), stdout=out)
    astert out.getvalue() == exp_makefixtures_results[testname]

3 View Complete Implementation : tests.py
Copyright MIT License
Author : CCrypto
    def test_notify_first(self):
        out = StringIO()
        u = User.objects.create_user('test_username', '[email protected]', 'testpw')
        u.vpnuser.add_paid_time(timedelta(days=2))
        u.vpnuser.save()

        call_command('expire_notify', stdout=out)
        self.astertEqual(len(mail.outbox), 1)
        self.astertEqual(mail.outbox[0].to, ['[email protected]'])
        self.astertIn('expire in 1 day', email_text(mail.outbox[0].body))

        u = User.objects.get(username='test_username')
        self.astertAlmostEqual(u.vpnuser.last_expiry_notice, timezone.now(),
                               delta=timedelta(minutes=1))

3 View Complete Implementation : test_commands.py
Copyright MIT License
Author : appsembler
    def test_command_output(self):
        out = StringIO()
        call_command('populate_figures_metrics', '--no-delay', stdout=out)

        self.astertEqual('', out.getvalue())
        #self.astertIn('Expected output', out.getvalue())

3 View Complete Implementation : message.py
Copyright GNU General Public License v2.0
Author : blackye
    def as_string(self, unixfrom=False):
        """Return the entire formatted message as a string.
        Optional `unixfrom' when True, means include the Unix From_ envelope
        header.

        This overrides the default as_string() implementation to not mangle
        lines that begin with 'From '. See bug #13433 for details.
        """
        fp = six.StringIO()
        g = Generator(fp, mangle_from_ = False)
        if sys.version_info < (2, 6, 6) and isinstance(self._payload, six.text_type):
            # Workaround for http://bugs.python.org/issue1368247
            self._payload = self._payload.encode(self._charset.output_charset)
        g.flatten(self, unixfrom=unixfrom)
        return fp.getvalue()

3 View Complete Implementation : message.py
Copyright MIT License
Author : bpgc-cte
    def as_string(self, unixfrom=False, linesep='\n'):
        """Return the entire formatted message as a string.
        Optional `unixfrom' when True, means include the Unix From_ envelope
        header.

        This overrides the default as_string() implementation to not mangle
        lines that begin with 'From '. See bug #13433 for details.
        """
        fp = six.StringIO()
        g = generator.Generator(fp, mangle_from_=False)
        if six.PY2:
            g.flatten(self, unixfrom=unixfrom)
        else:
            g.flatten(self, unixfrom=unixfrom, linesep=linesep)
        return fp.getvalue()

3 View Complete Implementation : test_management.py
Copyright Apache License 2.0
Author : edisonlz
    def test_verbosity_zero(self):
        # We can supress output on the management command
        new_io = StringIO()
        call_command("createsuperuser",
            interactive=False,
            username="joe2",
            email="[email protected]",
            verbosity=0,
            stdout=new_io
        )
        command_output = new_io.getvalue().strip()
        self.astertEqual(command_output, '')
        u = User.objects.get(username="joe2")
        self.astertEqual(u.email, '[email protected]')
        self.astertFalse(u.has_usable_pastword())

3 View Complete Implementation : test_setupsocial.py
Copyright GNU Affero General Public License v3.0
Author : nextcloud
    def test_setup(self):
        call_command('setupsocial', '--github-secret=tres',
                     '--github-client-id=sec', '--domain=local.com',
                     stdout=StringIO())
        site = Site.objects.all()[0]
        app = SocialApp.objects.get(provider='github')

        self.astertEqual('local.com', site.domain)
        self.astertEqual('Nextcloud App Store', site.name)

        self.astertEqual('GitHub', app.name)
        self.astertEqual('tres', app.secret)
        self.astertEqual('sec', app.client_id)

0 View Complete Implementation : helpers.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
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

0 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def serialize(self, queryset, **options):
        """
        Serialize a queryset.
        """
        self.options = options

        self.stream = options.pop("stream", six.StringIO())
        self.selected_fields = options.pop("fields", None)
        self.use_natural_keys = options.pop("use_natural_keys", False)

        self.start_serialization()
        self.first = True
        for obj in queryset:
            self.start_object(obj)
            # Use the concrete parent clast' _meta instead of the object's _meta
            # This is to avoid local_fields problems for proxy models. Refs #17717.
            concrete_model = obj._meta.concrete_model
            for field in concrete_model._meta.local_fields:
                if field.serialize:
                    if field.rel is None:
                        if self.selected_fields is None or field.attname in self.selected_fields:
                            self.handle_field(obj, field)
                    else:
                        if self.selected_fields is None or field.attname[:-3] in self.selected_fields:
                            self.handle_fk_field(obj, field)
            for field in concrete_model._meta.many_to_many:
                if field.serialize:
                    if self.selected_fields is None or field.attname in self.selected_fields:
                        self.handle_m2m_field(obj, field)
            self.end_object(obj)
            if self.first:
                self.first = False
        self.end_serialization()
        return self.getvalue()

0 View Complete Implementation : trans_real.py
Copyright GNU General Public License v2.0
Author : blackye
def templatize(src, origin=None):
    """
    Turns a Django template into something that is understood by xgettext. It
    does so by translating the Django translation tags into standard gettext
    function invocations.
    """
    from django.conf import settings
    from django.template import (Lexer, TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK,
            TOKEN_COMMENT, TRANSLATOR_COMMENT_MARK)
    src = force_text(src, settings.FILE_CHARSET)
    out = StringIO()
    message_context = None
    intrans = False
    inplural = False
    singular = []
    plural = []
    incomment = False
    comment = []
    for t in Lexer(src, origin).tokenize():
        if incomment:
            if t.token_type == TOKEN_BLOCK and t.contents == 'endcomment':
                content = ''.join(comment)
                translators_comment_start = None
                for lineno, line in enumerate(content.splitlines(True)):
                    if line.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
                        translators_comment_start = lineno
                for lineno, line in enumerate(content.splitlines(True)):
                    if translators_comment_start is not None and lineno >= translators_comment_start:
                        out.write(' # %s' % line)
                    else:
                        out.write(' #\n')
                incomment = False
                comment = []
            else:
                comment.append(t.contents)
        elif intrans:
            if t.token_type == TOKEN_BLOCK:
                endbmatch = endblock_re.match(t.contents)
                pluralmatch = plural_re.match(t.contents)
                if endbmatch:
                    if inplural:
                        if message_context:
                            out.write(' npgettext(%r, %r, %r,count) ' % (message_context, ''.join(singular), ''.join(plural)))
                        else:
                            out.write(' ngettext(%r, %r, count) ' % (''.join(singular), ''.join(plural)))
                        for part in singular:
                            out.write(blankout(part, 'S'))
                        for part in plural:
                            out.write(blankout(part, 'P'))
                    else:
                        if message_context:
                            out.write(' pgettext(%r, %r) ' % (message_context, ''.join(singular)))
                        else:
                            out.write(' gettext(%r) ' % ''.join(singular))
                        for part in singular:
                            out.write(blankout(part, 'S'))
                    message_context = None
                    intrans = False
                    inplural = False
                    singular = []
                    plural = []
                elif pluralmatch:
                    inplural = True
                else:
                    filemsg = ''
                    if origin:
                        filemsg = 'file %s, ' % origin
                    raise SyntaxError("Translation blocks must not include other block tags: %s (%sline %d)" % (t.contents, filemsg, t.lineno))
            elif t.token_type == TOKEN_VAR:
                if inplural:
                    plural.append('%%(%s)s' % t.contents)
                else:
                    singular.append('%%(%s)s' % t.contents)
            elif t.token_type == TOKEN_TEXT:
                contents = one_percent_re.sub('%%', t.contents)
                if inplural:
                    plural.append(contents)
                else:
                    singular.append(contents)
        else:
            if t.token_type == TOKEN_BLOCK:
                imatch = inline_re.match(t.contents)
                bmatch = block_re.match(t.contents)
                cmatches = constant_re.findall(t.contents)
                if imatch:
                    g = imatch.group(1)
                    if g[0] == '"':
                        g = g.strip('"')
                    elif g[0] == "'":
                        g = g.strip("'")
                    g = one_percent_re.sub('%%', g)
                    if imatch.group(2):
                        # A context is provided
                        context_match = context_re.match(imatch.group(2))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                        out.write(' pgettext(%r, %r) ' % (message_context, g))
                        message_context = None
                    else:
                        out.write(' gettext(%r) ' % g)
                elif bmatch:
                    for fmatch in constant_re.findall(t.contents):
                        out.write(' _(%s) ' % fmatch)
                    if bmatch.group(1):
                        # A context is provided
                        context_match = context_re.match(bmatch.group(1))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                    intrans = True
                    inplural = False
                    singular = []
                    plural = []
                elif cmatches:
                    for cmatch in cmatches:
                        out.write(' _(%s) ' % cmatch)
                elif t.contents == 'comment':
                    incomment = True
                else:
                    out.write(blankout(t.contents, 'B'))
            elif t.token_type == TOKEN_VAR:
                parts = t.contents.split('|')
                cmatch = constant_re.match(parts[0])
                if cmatch:
                    out.write(' _(%s) ' % cmatch.group(1))
                for p in parts[1:]:
                    if p.find(':_(') >= 0:
                        out.write(' %s ' % p.split(':',1)[1])
                    else:
                        out.write(blankout(p, 'F'))
            elif t.token_type == TOKEN_COMMENT:
                out.write(' # %s' % t.contents)
            else:
                out.write(blankout(t.contents, 'X'))
    return force_str(out.getvalue())

0 View Complete Implementation : creation.py
Copyright MIT License
Author : bpgc-cte
    def serialize_db_to_string(self):
        """
        Serializes all data in the database into a JSON string.
        Designed only for test runner usage; will not handle large
        amounts of data.
        """
        # Build list of all apps to serialize
        from django.db.migrations.loader import MigrationLoader
        loader = MigrationLoader(self.connection)
        app_list = []
        for app_config in apps.get_app_configs():
            if (
                app_config.models_module is not None and
                app_config.label in loader.migrated_apps and
                app_config.name not in settings.TEST_NON_SERIALIZED_APPS
            ):
                app_list.append((app_config, None))

        # Make a function to iteratively return every object
        def get_objects():
            for model in serializers.sort_dependencies(app_list):
                if (model._meta.can_migrate(self.connection) and
                        router.allow_migrate_model(self.connection.alias, model)):
                    queryset = model._default_manager.using(self.connection.alias).order_by(model._meta.pk.name)
                    for obj in queryset.iterator():
                        yield obj
        # Serialize to a string
        out = StringIO()
        serializers.serialize("json", get_objects(), indent=None, stream=out)
        return out.getvalue()

0 View Complete Implementation : runner.py
Copyright MIT License
Author : bpgc-cte
    def startTest(self, test):
        self.debug_sql_stream = StringIO()
        self.handler = logging.StreamHandler(self.debug_sql_stream)
        self.logger.addHandler(self.handler)
        super(DebugSQLTextTestResult, self).startTest(test)

0 View Complete Implementation : utils.py
Copyright MIT License
Author : bpgc-cte
    def setUp(self):
        self.logger = logging.getLogger('django')
        self.old_stream = self.logger.handlers[0].stream
        self.logger_output = six.StringIO()
        self.logger.handlers[0].stream = self.logger_output

0 View Complete Implementation : template.py
Copyright MIT License
Author : bpgc-cte
def templatize(src, origin=None, charset='utf-8'):
    """
    Turn a Django template into something that is understood by xgettext. It
    does so by translating the Django translation tags into standard gettext
    function invocations.
    """
    src = force_text(src, charset)
    out = StringIO('')
    message_context = None
    intrans = False
    inplural = False
    trimmed = False
    singular = []
    plural = []
    incomment = False
    comment = []
    lineno_comment_map = {}
    comment_lineno_cache = None
    # Adding the u prefix allows gettext to recognize the Unicode string
    # (#26093).
    raw_prefix = 'u' if six.PY3 else ''

    def join_tokens(tokens, trim=False):
        message = ''.join(tokens)
        if trim:
            message = trim_whitespace(message)
        return message

    for t in Lexer(src).tokenize():
        if incomment:
            if t.token_type == TOKEN_BLOCK and t.contents == 'endcomment':
                content = ''.join(comment)
                translators_comment_start = None
                for lineno, line in enumerate(content.splitlines(True)):
                    if line.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
                        translators_comment_start = lineno
                for lineno, line in enumerate(content.splitlines(True)):
                    if translators_comment_start is not None and lineno >= translators_comment_start:
                        out.write(' # %s' % line)
                    else:
                        out.write(' #\n')
                incomment = False
                comment = []
            else:
                comment.append(t.contents)
        elif intrans:
            if t.token_type == TOKEN_BLOCK:
                endbmatch = endblock_re.match(t.contents)
                pluralmatch = plural_re.match(t.contents)
                if endbmatch:
                    if inplural:
                        if message_context:
                            out.write(' npgettext({p}{!r}, {p}{!r}, {p}{!r},count) '.format(
                                message_context,
                                join_tokens(singular, trimmed),
                                join_tokens(plural, trimmed),
                                p=raw_prefix,
                            ))
                        else:
                            out.write(' ngettext({p}{!r}, {p}{!r}, count) '.format(
                                join_tokens(singular, trimmed),
                                join_tokens(plural, trimmed),
                                p=raw_prefix,
                            ))
                        for part in singular:
                            out.write(blankout(part, 'S'))
                        for part in plural:
                            out.write(blankout(part, 'P'))
                    else:
                        if message_context:
                            out.write(' pgettext({p}{!r}, {p}{!r}) '.format(
                                message_context,
                                join_tokens(singular, trimmed),
                                p=raw_prefix,
                            ))
                        else:
                            out.write(' gettext({p}{!r}) '.format(
                                join_tokens(singular, trimmed),
                                p=raw_prefix,
                            ))
                        for part in singular:
                            out.write(blankout(part, 'S'))
                    message_context = None
                    intrans = False
                    inplural = False
                    singular = []
                    plural = []
                elif pluralmatch:
                    inplural = True
                else:
                    filemsg = ''
                    if origin:
                        filemsg = 'file %s, ' % origin
                    raise SyntaxError(
                        "Translation blocks must not include other block tags: "
                        "%s (%sline %d)" % (t.contents, filemsg, t.lineno)
                    )
            elif t.token_type == TOKEN_VAR:
                if inplural:
                    plural.append('%%(%s)s' % t.contents)
                else:
                    singular.append('%%(%s)s' % t.contents)
            elif t.token_type == TOKEN_TEXT:
                contents = t.contents.replace('%', '%%')
                if inplural:
                    plural.append(contents)
                else:
                    singular.append(contents)
        else:
            # Handle comment tokens (`{# ... #}`) plus other constructs on
            # the same line:
            if comment_lineno_cache is not None:
                cur_lineno = t.lineno + t.contents.count('\n')
                if comment_lineno_cache == cur_lineno:
                    if t.token_type != TOKEN_COMMENT:
                        for c in lineno_comment_map[comment_lineno_cache]:
                            filemsg = ''
                            if origin:
                                filemsg = 'file %s, ' % origin
                            warn_msg = (
                                "The translator-targeted comment '%s' "
                                "(%sline %d) was ignored, because it wasn't "
                                "the last item on the line."
                            ) % (c, filemsg, comment_lineno_cache)
                            warnings.warn(warn_msg, TranslatorCommentWarning)
                        lineno_comment_map[comment_lineno_cache] = []
                else:
                    out.write('# %s' % ' | '.join(lineno_comment_map[comment_lineno_cache]))
                comment_lineno_cache = None

            if t.token_type == TOKEN_BLOCK:
                imatch = inline_re.match(t.contents)
                bmatch = block_re.match(t.contents)
                cmatches = constant_re.findall(t.contents)
                if imatch:
                    g = imatch.group(1)
                    if g[0] == '"':
                        g = g.strip('"')
                    elif g[0] == "'":
                        g = g.strip("'")
                    g = g.replace('%', '%%')
                    if imatch.group(2):
                        # A context is provided
                        context_match = context_re.match(imatch.group(2))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                        out.write(' pgettext({p}{!r}, {p}{!r}) '.format(
                            message_context, g, p=raw_prefix
                        ))
                        message_context = None
                    else:
                        out.write(' gettext({p}{!r}) '.format(g, p=raw_prefix))
                elif bmatch:
                    for fmatch in constant_re.findall(t.contents):
                        out.write(' _(%s) ' % fmatch)
                    if bmatch.group(1):
                        # A context is provided
                        context_match = context_re.match(bmatch.group(1))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                    intrans = True
                    inplural = False
                    trimmed = 'trimmed' in t.split_contents()
                    singular = []
                    plural = []
                elif cmatches:
                    for cmatch in cmatches:
                        out.write(' _(%s) ' % cmatch)
                elif t.contents == 'comment':
                    incomment = True
                else:
                    out.write(blankout(t.contents, 'B'))
            elif t.token_type == TOKEN_VAR:
                parts = t.contents.split('|')
                cmatch = constant_re.match(parts[0])
                if cmatch:
                    out.write(' _(%s) ' % cmatch.group(1))
                for p in parts[1:]:
                    if p.find(':_(') >= 0:
                        out.write(' %s ' % p.split(':', 1)[1])
                    else:
                        out.write(blankout(p, 'F'))
            elif t.token_type == TOKEN_COMMENT:
                if t.contents.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
                    lineno_comment_map.setdefault(t.lineno, []).append(t.contents)
                    comment_lineno_cache = t.lineno
            else:
                out.write(blankout(t.contents, 'X'))
    return out.getvalue()