django.utils.six.StringIO

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.

155 Examples 7

Example 1

Project: django-two-factor-auth Source File: test_commands.py
Function: test_raises
    def test_raises(self):
        stdout = six.StringIO()
        stderr = six.StringIO()
        with self._assert_raises(CommandError, 'User "some_username" does not exist'):
            call_command(
                'two_factor_disable', 'some_username',
                stdout=stdout, stderr=stderr)

        with self._assert_raises(CommandError, 'User "other_username" does not exist'):
            call_command(
                'two_factor_disable', 'other_username', 'some_username',
                stdout=stdout, stderr=stderr)

Example 2

Project: votainteligente-portal-electoral Source File: second_round_tests.py
    def test_management_command(self):
        out = StringIO()
        previous_count = Election.objects.all().count()
        call_command('cloneelection', self.tarapaca.slug, self.adela.id, self.carlos.id, stdout=out)
        after_count = Election.objects.all().count()
        self.assertEquals(after_count, previous_count + 1)
        second_round = Election.objects.last()
        self.assertEquals(second_round.name, self.tarapaca.name)
        self.assertIn(second_round.name, out.getvalue())
        self.assertIn(second_round.get_absolute_url(), out.getvalue())

Example 3

Project: django-maintenancemode Source File: tests.py
Function: test_management_command
    def test_management_command(self):
        out = StringIO()
        # Explicitly disabling the ``MAINTENANCE_MODE``
        with self.settings(MAINTENANCE_MODE=False, TEMPLATE_DIRS=TEMPLATE_DIRS, TEMPLATES=TEMPLATES):
            management.call_command('maintenance', 'on', stdout=out)
            self.assertContains(self.client.get('/'), text='Temporary unavailable', count=1, status_code=503)

            management.call_command('maintenance', 'off', stdout=out)
            self.assertContains(self.client.get('/'), text='Rendered response page', count=1, status_code=200)

Example 4

Project: django-herald Source File: test_commands.py
    def test_do_not_delete_tomorrow(self):
        SentNotification(
            notification_class=NOTIFICATION_CLASS,
            date_sent=timezone.now()+timedelta(days=1)
        ).save()
        out = StringIO()
        call_command('delnotifs', stdout=out)
        self.assertIn(MSG.format(num=0), out.getvalue())

Example 5

Project: froide Source File: csv_import.py
    def import_from_file(self, csv_file):
        """
        csv_file should be encoded in utf-8
        """
        if PY3:
            csv_file = StringIO(csv_file.read().decode('utf-8'))
        reader = csv.DictReader(csv_file)
        for row in reader:
            self.import_row(row)

Example 6

Project: django-filebrowser Source File: test_commands.py
    def test_fb_version_generate(self):
        self.assertFalse(os.path.exists(self.version_file))

        # sys.stdout = open(os.devnull, 'wb')
        sys.stdin = StringIO("large")

        call_command('fb_version_generate', DIRECTORY)

        self.assertTrue(os.path.exists(self.version_file))

Example 7

Project: django-secure Source File: tests.py
Function: call
    def call(self, **options):
        stdout = options.setdefault("stdout", StringIO())
        stderr = options.setdefault("stderr", StringIO())

        call_command("checksecure", **options)

        stderr.seek(0)
        stdout.seek(0)

        return stdout.read(), stderr.read()

Example 8

Project: myks-gallery Source File: admin.py
@permission_required('gallery.scan')
def scan_photos(request):
    if request.method == 'POST':
        stdout, stderr = six.StringIO(), six.StringIO()
        management.call_command('scanphotos', stdout=stdout, stderr=stderr)
        for line in stdout.getvalue().splitlines():
            messages.info(request, line)
        for line in stderr.getvalue().splitlines():
            messages.error(request, line)
        return HttpResponseRedirect(reverse('admin:gallery_scan_photos'))
    context = {
        'app_label': 'gallery',
        'title': ugettext("Scan photos"),
    }
    return render(request, 'admin/gallery/scan_photos.html', context)

Example 9

Project: hue Source File: tests.py
Function: set_up
    def setUp(self):
        self.old_DJANGO_AUTO_COMPLETE = os.environ.get('DJANGO_AUTO_COMPLETE')
        os.environ['DJANGO_AUTO_COMPLETE'] = '1'
        self.output = StringIO()
        self.old_stdout = sys.stdout
        sys.stdout = self.output

Example 10

Project: informer Source File: test_commands.py
    def test_command_check_with_all(self):
        """
        Call command without specify a Informer.
        """
        out = StringIO()
        call_command('checkinformer', stdout=out)

        expected = [
            'Checking Informers.',
            'Checking StorageInformer... Your FileSystemStorage is '
            'operational.']

        result = out.getvalue()

        for item in expected:
            self.assertTrue(item in result)

Example 11

Project: django-multi-gtfs Source File: test_stop_time.py
    def test_import_stop_times_txt_tomorrow(self):
        stop_times_txt = StringIO("""\
trip_id,arrival_time,departure_time,stop_id,stop_sequence
STBA,23:59:00,24:01:00,STAGECOACH,1
""")
        StopTime.import_txt(stop_times_txt, self.feed)
        stoptime = StopTime.objects.get()
        self.assertEqual(stoptime.trip, self.trip)
        self.assertEqual(str(stoptime.arrival_time), '23:59:00')
        self.assertEqual(str(stoptime.departure_time), '24:01:00')
        self.assertEqual(stoptime.stop, self.stop)
        self.assertEqual(stoptime.stop_sequence, 1)
        self.assertEqual(stoptime.stop_headsign, '')
        self.assertEqual(stoptime.pickup_type, '')
        self.assertEqual(stoptime.drop_off_type, '')
        self.assertEqual(stoptime.shape_dist_traveled, None)

Example 12

Project: wagtail Source File: test_backends.py
    def test_update_index_command(self):
        # Reset the index, this should clear out the index
        self.reset_index()

        # Give Elasticsearch some time to catch up...
        time.sleep(1)

        results = self.backend.search(None, models.SearchTest)
        self.assertEqual(set(results), set())

        # Run update_index command
        with self.ignore_deprecation_warnings():
            # ignore any DeprecationWarnings thrown by models with old-style indexed_fields definitions
            management.call_command(
                'update_index', backend_name=self.backend_name, interactive=False, stdout=StringIO()
            )

        results = self.backend.search(None, models.SearchTest)
        self.assertEqual(set(results), {self.testa, self.testb, self.testc.searchtest_ptr, self.testd.searchtest_ptr})

Example 13

Project: informer Source File: test_commands.py
    @mock.patch('informer.checker.base.BaseInformer.get_class')
    def test_command_failure(self, m_mock):
        m_mock.side_effect = Exception('Cataploft')

        out = StringIO()

        call_command('checkinformer', stderr=out)

        expected = ['A generic exception occurred: Cataploft']

        result = out.getvalue()

        for item in expected:
            self.assertTrue(item in result)

Example 14

Project: django-herald Source File: test_commands.py
    def test_delete_today_start_arg(self):
        SentNotification(
            notification_class=NOTIFICATION_CLASS,
            date_sent=timezone.now()
        ).save()
        SentNotification(
            notification_class=NOTIFICATION_CLASS,
            date_sent=timezone.now()+timedelta(days=1)
        ).save()
        out = StringIO()
        today = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        call_command('delnotifs', stdout=out, start=str(today))
        self.assertIn(MSG.format(num=1), out.getvalue())

Example 15

Project: PyClassLessons Source File: message.py
Function: as_string
    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()

Example 16

Project: django-two-factor-auth Source File: test_commands.py
    def test_status_single(self):
        user = self.create_user()
        stdout = six.StringIO()
        call_command('two_factor_status', '[email protected]', stdout=stdout)
        self.assertEqual(stdout.getvalue(), '[email protected]: disabled\n')

        stdout = six.StringIO()
        self.enable_otp(user)
        call_command('two_factor_status', '[email protected]', stdout=stdout)
        self.assertEqual(stdout.getvalue(), '[email protected]: enabled\n')

Example 17

Project: django-smuggler Source File: utils.py
Function: load_fixtures
def load_fixtures(fixtures):
    stream = StringIO()
    error_stream = StringIO()
    call_command('loaddata', *fixtures, **{
        'stdout': stream,
        'stderr': error_stream,
        'ignore': True,
        'database': DEFAULT_DB_ALIAS,
        'verbosity': 1
    })
    stream.seek(0)
    result = stream.read()
    return int(re.match(r'Installed\s([0-9]+)\s.*', result).groups()[0])

Example 18

Project: django-mutant Source File: test_commands.py
    def test_load_mutable_models(self):
        """
        Makes sure mutable models instances are correctly loaded when calling
        `loaddata`.
        """
        instance = self.model_cls(pk=1)
        # Make sure to remove the model from the app cache because we're
        # actually testing it's correctly loaded.
        remove_from_app_cache(self.model_cls)
        with NamedTemporaryFile(suffix='.json') as stream:
            self.serializer.serialize([instance], stream=BytesWritter(stream))
            stream.seek(0)
            call_command(
                'loaddata', stream.name, stdout=StringIO(), commit=False
            )
        self.assertTrue(self.model_cls.objects.filter(pk=instance.pk).exists())

Example 19

Project: GAE-Bulk-Mailer Source File: message.py
Function: as_string
    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()

Example 20

Project: hue Source File: base.py
    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'))

Example 21

Project: splunk-webframework Source File: management.py
Function: test_create_superuser
    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.assertEqual(command_output, 'Superuser created successfully.')
        u = User.objects.get(username="joe")
        self.assertEqual(u.email, '[email protected]')

        # created password should be unusable
        self.assertFalse(u.has_usable_password())

Example 22

Project: splunk-webframework Source File: management.py
    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.assertEqual(command_output, '')
        u = User.objects.get(username="joe2")
        self.assertEqual(u.email, '[email protected]')
        self.assertFalse(u.has_usable_password())

Example 23

Project: GAE-Bulk-Mailer Source File: message.py
Function: as_string
    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()

Example 24

Project: wagtail Source File: test_management_commands.py
Function: run_command
    def run_command(self, **options):
        options.setdefault('interactive', False)

        output = StringIO()
        management.call_command('fixtree', stdout=output, **options)
        output.seek(0)

        return output

Example 25

Project: informer Source File: test_commands.py
    def test_command_check_with_one(self):
        """
        Call command specifying an informer.
        """
        out = StringIO()
        call_command('checkinformer', 'DatabaseInformer', stdout=out)

        expected = [
            'Checking Informers.',
            'Checking DatabaseInformer... Your database is operational.']

        result = out.getvalue()

        for item in expected:
            self.assertTrue(item in result)

Example 26

Project: django-multi-gtfs Source File: test_stop_time.py
    def test_import_stop_times_txt_empty_optional(self):
        stop_times_txt = StringIO("""\
trip_id,arrival_time,departure_time,stop_id,stop_sequence,stop_headsign,\
pickup_type,drop_off_type,shape_dist_traveled
STBA,6:00:00,6:00:00,STAGECOACH,1,,,,
""")
        StopTime.import_txt(stop_times_txt, self.feed)
        stoptime = StopTime.objects.get()
        self.assertEqual(stoptime.trip, self.trip)
        self.assertEqual(str(stoptime.arrival_time), '06:00:00')
        self.assertEqual(str(stoptime.departure_time), '06:00:00')
        self.assertEqual(stoptime.stop, self.stop)
        self.assertEqual(stoptime.stop_sequence, 1)
        self.assertEqual(stoptime.stop_headsign, '')
        self.assertEqual(stoptime.pickup_type, '')
        self.assertEqual(stoptime.drop_off_type, '')
        self.assertEqual(stoptime.shape_dist_traveled, None)

Example 27

Project: Django-facebook Source File: tests.py
Function: set_up
    def setUp(self):
        setup_users()
        for user_slug, user_object in TEST_USER_OBJECTS.items():
            setattr(self, user_slug, user_object)

        # capture print statements
        import sys
        self.prints = sys.stdout = StringIO()

Example 28

Project: informer Source File: test_commands.py
    def test_command_without_configuration(self):
        """
        Show a friendly message when missing configuration.
        """
        with override_settings(DJANGO_INFORMERS=None):
            out = StringIO()
            call_command('checkinformer', stdout=out)

            expected = [
                'No informer was found.',
                'Missing configuration.']

            result = out.getvalue()

            for item in expected:
                self.assertTrue(item in result)

Example 29

Project: django-herald Source File: test_commands.py
    def test_delete_today(self):
        SentNotification(
            notification_class=NOTIFICATION_CLASS,
            date_sent=timezone.now()
        ).save()
        SentNotification(
            notification_class=NOTIFICATION_CLASS,
            date_sent=timezone.now()+timedelta(days=1)
        ).save()
        out = StringIO()
        call_command('delnotifs', stdout=out)
        self.assertIn(MSG.format(num=1), out.getvalue())

Example 30

Project: silver Source File: test_generate_docs_args.py
    def __init__(self, *args, **kwargs):
        super(TestGenerateDocsArguments, self).__init__(*args, **kwargs)
        self.output = StringIO()
        self.good_output = 'Done. You can have a Club-Mate now. :)\n'
        self.date_string = '2016-06-01'
        self.date = generate_docs_date(self.date_string)

Example 31

Project: django-herald Source File: test_commands.py
    def test_do_not_delete_yesterday(self):
        SentNotification(
            notification_class=NOTIFICATION_CLASS,
            date_sent=timezone.now() - timedelta(days=1)
        ).save()
        out = StringIO()
        call_command('delnotifs', stdout=out)
        self.assertIn(MSG.format(num=0), out.getvalue())

Example 32

Project: Django--an-app-at-a-time Source File: utils.py
Function: captured_output
@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)

Example 33

Project: django-herald Source File: test_commands.py
    def test_do_not_delete_tomorrow_end_arg(self):
        SentNotification(
            notification_class=NOTIFICATION_CLASS,
            date_sent=timezone.now()+timedelta(days=1)
        ).save()
        out = StringIO()
        two_days_later = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=2)
        call_command('delnotifs', stdout=out, end=str(two_days_later))
        self.assertIn(MSG.format(num=1), out.getvalue())

Example 34

Project: django-user-accounts Source File: test_commands.py
    def test_set_history_exists(self):
        """
        Ensure password history is NOT created.
        """
        PasswordHistory.objects.create(user=self.user)
        password_age = 5  # days
        out = StringIO()
        call_command(
            "user_password_history",
            "--days={}".format(password_age),
            stdout=out
        )

        user = self.UserModel.objects.get(username="patrick")
        password_history = user.password_history.all()
        self.assertEqual(password_history.count(), 1)
        self.assertIn("No users found without password history", out.getvalue())

Example 35

Project: django-two-factor-auth Source File: test_commands.py
Function: test_raises
    def test_raises(self):
        stdout = six.StringIO()
        stderr = six.StringIO()
        with self._assert_raises(CommandError, 'User "some_username" does not exist'):
            call_command(
                'two_factor_status', 'some_username',
                stdout=stdout, stderr=stderr)

        with self._assert_raises(CommandError, 'User "other_username" does not exist'):
            call_command(
                'two_factor_status', 'other_username', 'some_username',
                stdout=stdout, stderr=stderr)

Example 36

Project: django-smuggler Source File: utils.py
def serialize_to_response(app_labels=None, exclude=None, response=None,
                          format=settings.SMUGGLER_FORMAT,
                          indent=settings.SMUGGLER_INDENT):
    app_labels = app_labels or []
    exclude = exclude or []
    response = response or HttpResponse(content_type='text/plain')
    stream = StringIO()
    error_stream = StringIO()
    call_command('dumpdata', *app_labels, **{
        'stdout': stream,
        'stderr': error_stream,
        'exclude': exclude,
        'format': format,
        'indent': indent,
        'use_natural_foreign_keys': True,
        'use_natural_primary_keys': True
    })
    response.write(stream.getvalue())
    return response

Example 37

Project: django-two-factor-auth Source File: test_commands.py
    def test_status_mutiple(self):
        users = [self.create_user(n) for n in ['[email protected]', '[email protected]']]
        self.enable_otp(users[0])
        stdout = six.StringIO()
        call_command('two_factor_status', '[email protected]', '[email protected]', stdout=stdout)
        self.assertEqual(stdout.getvalue(), '[email protected]: enabled\n'
                                            '[email protected]: disabled\n')

Example 38

Project: PyClassLessons Source File: creation.py
    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()

Example 39

Project: django-mutant Source File: test_commands.py
    def dump_model_data(self):
        # Make sure to remove the model from the app cache because we're
        # actually testing it's correctly loaded.
        output = StringIO()
        remove_from_app_cache(self.model_cls)
        call_command(
            'dumpdata', str(self.model_def), stdout=output, commit=False
        )
        output.seek(0)
        return json.load(output)

Example 40

Project: django-smuggler Source File: test_dump.py
    def test_serialize_exclude(self):
        stream = StringIO()
        utils.serialize_to_response(exclude=['sites', 'auth', 'contenttypes'],
                                    response=stream)
        out = self.normalize(stream.getvalue())
        self.assertEqual(out, self.PAGE_DUMP)

Example 41

Project: django-mutant Source File: test_commands.py
    def test_invalid_model_idenfitier_raises(self):
        """
        Makes sure an invalid model identifier raises the correct exception.
        """
        instance = self.model_cls(pk=1)
        with NamedTemporaryFile(suffix='.json') as stream:
            self.serializer.serialize([instance], stream=BytesWritter(stream))
            stream.seek(0)
            self.model_def.delete()
            with self.assertRaisesMessage(
                    DeserializationError, "Invalid model identifier: 'mutant.model'"):
                call_command(
                    'loaddata', stream.name, stdout=StringIO()
                )

Example 42

Project: django-user-accounts Source File: test_commands.py
    def test_set_default_password_expiry(self):
        """
        Ensure default password expiry (from settings) is set.
        """
        self.assertFalse(hasattr(self.user, "password_expiry"))
        out = StringIO()
        call_command(
            "user_password_expiry",
            "patrick",
            stdout=out
        )

        user = self.UserModel.objects.get(username="patrick")
        user_expiry = user.password_expiry
        default_expiration = settings.ACCOUNT_PASSWORD_EXPIRY
        self.assertEqual(user_expiry.expiry, default_expiration)
        self.assertIn("User \"{}\" password expiration set to {} seconds".format(self.user.username, default_expiration), out.getvalue())

Example 43

Project: hue Source File: message.py
Function: as_string
    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.Generator(fp, mangle_from_=False)
        if sys.version_info < (2, 6, 6) and isinstance(self._payload, six.text_type):
            self._payload = self._payload.encode(self._charset.output_charset)
        g.flatten(self, unixfrom=unixfrom)
        return fp.getvalue()

Example 44

Project: shuup Source File: makemessages.py
def jinja_messages_to_python(src, origin=None):
    """
    Convert Jinja2 file to Python preserving only messages.
    """
    output = StringIO('')
    output_lineno = 1
    for (lineno, message, comments, context) in extract_jinja(src, origin):
        for comment in comments:
            output.write(('# %s %s\n' % (COMMENT_TAG, comment)))
            output_lineno += 1
        lines_to_add = (lineno - output_lineno)
        if lines_to_add > 0:  # Try to keep line numbers in sync
            output.write(lines_to_add * '\n')
            output_lineno += lines_to_add
        output.write('gettext(%r),' % (message,))
    return output.getvalue()

Example 45

Project: reviewboard Source File: subvertpy.py
    def get_file(self, path, revision=HEAD):
        """Returns the contents of a given file at the given revision."""
        if not path:
            raise FileNotFoundError(path, revision)
        revnum = self._normalize_revision(revision)
        path = B(self.normalize_path(path))
        data = six.StringIO()
        try:
            self.client.cat(path, data, revnum)
        except SubversionException as e:
            raise FileNotFoundError(e)
        contents = data.getvalue()
        keywords = self.get_keywords(path, revision)
        if keywords:
            contents = self.collapse_keywords(contents, keywords)
        return contents

Example 46

Project: django-user-accounts Source File: test_commands.py
    def test_set_explicit_password_expiry(self):
        """
        Ensure specific password expiry is set.
        """
        self.assertFalse(hasattr(self.user, "password_expiry"))
        expiration_period = 60
        out = StringIO()
        call_command(
            "user_password_expiry",
            "patrick",
            "--expire={}".format(expiration_period),
            stdout=out
        )

        user = self.UserModel.objects.get(username="patrick")
        user_expiry = user.password_expiry
        self.assertEqual(user_expiry.expiry, expiration_period)
        self.assertIn("User \"{}\" password expiration set to {} seconds".format(self.user.username, expiration_period), out.getvalue())

Example 47

Project: django-user-accounts Source File: test_commands.py
    def test_set_history(self):
        """
        Ensure password history is created.
        """
        self.assertFalse(self.user.password_history.all())
        password_age = 5  # days
        out = StringIO()
        call_command(
            "user_password_history",
            "--days={}".format(password_age),
            stdout=out
        )

        user = self.UserModel.objects.get(username="patrick")
        password_history = user.password_history.all()
        self.assertEqual(password_history.count(), 1)
        self.assertIn("Password history set to ", out.getvalue())
        self.assertIn("for {} users".format(1), out.getvalue())

Example 48

Project: GAE-Bulk-Mailer Source File: feedgenerator.py
Function: write_string
    def writeString(self, encoding):
        """
        Returns the feed in the given encoding as a string.
        """
        s = StringIO()
        self.write(s, encoding)
        return s.getvalue()

Example 49

Project: informer Source File: test_commands.py
    def test_command_check_with_unknown_informer(self):
        """
        Call command specifying an unknown informer are (silently) ignored.
        """
        out = StringIO()
        call_command('checkinformer', 'UnknownInformer', stdout=out)

        expected = [
            'No informer was found with names provided (UnknownInformer).']

        result = out.getvalue()

        for item in expected:
            self.assertTrue(item in result)

Example 50

Project: django-multi-gtfs Source File: test_stop_time.py
    def test_import_stop_times_txt_maximal(self):
        stop_times_txt = StringIO("""\
trip_id,arrival_time,departure_time,stop_id,stop_sequence,stop_headsign,\
pickup_type,drop_off_type,shape_dist_traveled
STBA,6:00:00,6:00:00,STAGECOACH,1,"SC",2,1,5.25
""")
        StopTime.import_txt(stop_times_txt, self.feed)
        stoptime = StopTime.objects.get()
        self.assertEqual(stoptime.trip, self.trip)
        self.assertEqual(str(stoptime.arrival_time), '06:00:00')
        self.assertEqual(str(stoptime.departure_time), '06:00:00')
        self.assertEqual(stoptime.stop, self.stop)
        self.assertEqual(stoptime.stop_sequence, 1)
        self.assertEqual(stoptime.stop_headsign, 'SC')
        self.assertEqual(stoptime.pickup_type, '2')
        self.assertEqual(stoptime.drop_off_type, '1')
        self.assertEqual(stoptime.shape_dist_traveled, 5.25)
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4