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
3
Example 1
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)
3
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())
3
Example 3
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)
3
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())
3
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)
3
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))
3
Example 7
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()
3
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)
3
Example 9
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
3
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)
3
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)
3
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})
3
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)
3
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())
3
Example 15
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
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')
3
Example 17
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])
3
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())
3
Example 19
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
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'))
3
Example 21
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())
3
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())
3
Example 23
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
Example 24
def run_command(self, **options):
options.setdefault('interactive', False)
output = StringIO()
management.call_command('fixtree', stdout=output, **options)
output.seek(0)
return output
3
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)
3
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)
3
Example 27
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()
3
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)
3
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())
3
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)
3
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())
3
Example 32
@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
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())
3
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())
3
Example 35
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)
3
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
3
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')
3
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()
3
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)
3
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)
3
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()
)
3
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())
3
Example 43
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()
3
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()
3
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
3
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())
3
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())
3
Example 48
def writeString(self, encoding):
"""
Returns the feed in the given encoding as a string.
"""
s = StringIO()
self.write(s, encoding)
return s.getvalue()
3
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)
3
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)