def test_command_output(self): """"Test command output""" # prepare output file for command out = StringIO() # call our command call_command('project_models_counter', stdout=out) # get command output result = out.getvalue() # check if we get proper number of objects in database self.assertIn('apps.person_info.models.Person 1', result) # test command result after create object Person.objects.create(first_name='Vasya', last_name='Pupkin', date_of_birth='2000-01-01', bio="Vasya molodec", email='*****@*****.**', jabber='*****@*****.**', skype='Vasya777', other_contacts='9379992') # call our command call_command('project_models_counter', stdout=out) # get command output result = out.getvalue() self.assertIn('apps.person_info.models.Person 2', result)
def test_command_style(self): out = StringIO() management.call_command('dance', style='Jive', stdout=out) self.assertIn("I don't feel like dancing Jive.\n", out.getvalue()) # Passing options as arguments also works (thanks argparse) management.call_command('dance', '--style', 'Jive', stdout=out) self.assertIn("I don't feel like dancing Jive.\n", out.getvalue())
def serialize_to_response(app_labels=[], exclude=[], response=None, format=settings.SMUGGLER_FORMAT, indent=settings.SMUGGLER_INDENT): response = response or HttpResponse(content_type='text/plain') stream = StringIO() error_stream = StringIO() try: dumpdata = DumpData() dumpdata.style = no_style() dumpdata.execute(*app_labels, **{ 'stdout': stream, 'stderr': error_stream, 'exclude': exclude, 'format': format, 'indent': indent, 'use_natural_keys': True, 'use_natural_foreign_keys': True, 'use_natural_primary_keys': True }) except SystemExit: # Django 1.4's implementation of execute catches CommandErrors and # then calls sys.exit(1), we circumvent this here. errors = error_stream.getvalue().strip().replace('Error: ', '') raise CommandError(errors) response.write(stream.getvalue()) return response
def test_set_history_force(self): """ Ensure specific password history is created for all users. """ another_user = self.UserModel.objects.create_user(username="******") PasswordHistory.objects.create(user=another_user) password_age = 5 # days out = StringIO() call_command( "user_password_history", "--days={}".format(password_age), "--force", stdout=out ) user = self.UserModel.objects.get(username="******") password_history = user.password_history.all() self.assertEqual(password_history.count(), 1) # verify user with existing history DID get another entry user = self.UserModel.objects.get(username="******") password_history = user.password_history.all() self.assertEqual(password_history.count(), 2) self.assertIn("Password history set to ", out.getvalue()) self.assertIn("for {} users".format(2), out.getvalue())
def test_serialization(self): "m2m-through models aren't serialized as m2m fields. Refs #8134" p = Person.objects.create(name="Bob") g = Group.objects.create(name="Roll") m =Membership.objects.create(person=p, group=g) pks = {"p_pk": p.pk, "g_pk": g.pk, "m_pk": m.pk} out = StringIO() management.call_command("dumpdata", "m2m_through_regress", format="json", stdout=out) self.assertJSONEqual(out.getvalue().strip(), """[{"pk": %(m_pk)s, "model": "m2m_through_regress.membership", "fields": {"person": %(p_pk)s, "price": 100, "group": %(g_pk)s}}, {"pk": %(p_pk)s, "model": "m2m_through_regress.person", "fields": {"name": "Bob"}}, {"pk": %(g_pk)s, "model": "m2m_through_regress.group", "fields": {"name": "Roll"}}]""" % pks) out = StringIO() management.call_command("dumpdata", "m2m_through_regress", format="xml", indent=2, stdout=out) self.assertXMLEqual(out.getvalue().strip(), """ <?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"> <object pk="%(m_pk)s" model="m2m_through_regress.membership"> <field to="m2m_through_regress.person" name="person" rel="ManyToOneRel">%(p_pk)s</field> <field to="m2m_through_regress.group" name="group" rel="ManyToOneRel">%(g_pk)s</field> <field type="IntegerField" name="price">100</field> </object> <object pk="%(p_pk)s" model="m2m_through_regress.person"> <field type="CharField" name="name">Bob</field> </object> <object pk="%(g_pk)s" model="m2m_through_regress.group"> <field type="CharField" name="name">Roll</field> </object> </django-objects> """.strip() % pks)
def reload_task_data(request): from django.utils.six import StringIO commands = [ 'update_tasks_git', 'loadtasks', 'collectqueststatic' ] results = [] for command in commands: try: stdout = StringIO() stderr = StringIO() call_command(command, stdout=stdout, stderr=stderr) except CommandError as e: stderr.write('\n\nCommand failed cause {}'.format(e)) results.append({ 'command': command, 'stdout': stdout.getvalue(), 'stderr': stderr.getvalue() }) return render(request, 'quests/command_results.html', { 'title': 'Update tasks', 'commands': results, })
def test_command_output(self): '''Test that printout command gives right output''' out = StringIO() call_command('printout', stdout=out) self.assertIn('Bio objects: 1', out.getvalue()) self.assertIn('Request objects: 0', out.getvalue()) self.assertIn('User objects: 1', out.getvalue())
def test_set_history_multiple(self): """ Ensure password history is created for all users without existing history. """ self.UserModel.objects.create_user(username="******") self.UserModel.objects.create_user(username="******") password_age = 5 # days out = StringIO() call_command( "user_password_history", "--days={}".format(password_age), stdout=out ) user = self.UserModel.objects.get(username="******") password_history = user.password_history.all() self.assertEqual(password_history.count(), 1) first_timestamp = password_history[0].timestamp user = self.UserModel.objects.get(username="******") password_history = user.password_history.all() self.assertEqual(password_history.count(), 1) second_timestamp = password_history[0].timestamp self.assertEqual(first_timestamp, second_timestamp) user = self.UserModel.objects.get(username="******") password_history = user.password_history.all() self.assertEqual(password_history.count(), 1) third_timestamp = password_history[0].timestamp self.assertEqual(first_timestamp, third_timestamp) self.assertIn("Password history set to ", out.getvalue()) self.assertIn("for {} users".format(3), out.getvalue())
def test_regen_blank_avatar(self): """command deletes old notifications""" # create user User = get_user_model() user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123") # notify him notify_user(user, "Hello Bob!", "/") # run command command = deleteoldnotifications.Command() out = StringIO() command.execute(stdout=out) command_output = out.getvalue().splitlines()[0].strip() self.assertEqual(command_output, 'Old notifications have been deleted') self.assertEqual(user.misago_notifications.count(), 1) # outdate notifications cutoff = timedelta(days=settings.MISAGO_NOTIFICATIONS_MAX_AGE * 2) cutoff_date = timezone.now() - cutoff user.misago_notifications.update(date=cutoff_date) # run command again out = StringIO() command.execute(stdout=out) command_output = out.getvalue().splitlines()[0].strip() self.assertEqual(command_output, 'Old notifications have been deleted') self.assertEqual(user.misago_notifications.count(), 0)
def test_command_spiritcompilemessages(self): """ Should compile all locales under the spirit root folder """ commands = [] dirs = [] def call_mock(command, **kwargs): commands.append(command) dirs.append(os.getcwd()) org_call, spiritmakelocales.call_command = spiritmakelocales.call_command, call_mock try: out = StringIO() err = StringIO() call_command('spiritmakelocales', stdout=out, stderr=err) out_put = out.getvalue().strip().splitlines() out_put_err = err.getvalue().strip().splitlines() self.assertEqual(commands[0], 'makemessages') self.assertEqual(commands[1], 'compilemessages') self.assertEqual(len(dirs), 44) self.assertEqual(out_put[-1], "ok") self.assertEqual(out_put_err, []) finally: spiritmakelocales.call_command = org_call
def test_importcookie_verbose(self): httpretty.register_uri(httpretty.GET, 'https://api.github.com/repos/audreyr/cookiecutter-pypackage', body=read(__file__, '..', '_replay_data', 'cookiecutter-pypacker-repository'), content_type='application/json; charset=utf-8' ) httpretty.register_uri(httpretty.GET, 'https://api.github.com/users/audreyr', body=read(__file__, '..', '_replay_data', 'audreyr'), content_type='application/json; charset=utf-8' ) httpretty.register_uri(httpretty.GET, 'https://api.github.com/repos/audreyr/cookiecutter-pypackage/contents/', body=read(__file__, '..', '_replay_data', 'cookiecutter-pypacker-rootdir'), content_type='application/json; charset=utf-8' ) httpretty.register_uri(httpretty.GET, 'https://api.github.com/repos/audreyr/cookiecutter-pypackage/contents/cookiecutter.json', body=read(__file__, '..', '_replay_data', 'cookiecutter-pypacker-cookiecutter.json'), content_type='application/json; charset=utf-8' ) out = StringIO() management.call_command('importcookie', 'https://github.com/audreyr/cookiecutter-pypackage', verbosity=2, stdout=out) self.assertIn('Importing https://github.com/audreyr/cookiecutter-pypackage', out.getvalue()) self.assertIn('Imported https://github.com/audreyr/cookiecutter-pypackage', out.getvalue())
def test_find_user(db): user = UserFactory.create(username='******', email='*****@*****.**') StandupUserFactory.create(user=user, irc_nick='jimbobbaz') stdout = StringIO() call_command('finduser', 'willkg', stdout=stdout) output = stdout.getvalue().splitlines() assert len(output) == 4 for i, starter in enumerate([ 'Searching for: willkg', '-----', 'user_id', '-----' ]): assert output[i].startswith(starter) stdout = StringIO() call_command('finduser', 'jimbob', stdout=stdout) output = stdout.getvalue().splitlines() assert len(output) == 5 for i, starter in enumerate([ 'Searching for: jimbob', '-----', 'user_id username', '%-5d jimbob' % user.id, ]): print((i, output[i], starter)) assert output[i].startswith(starter)
def test_checklinks_command(self): Book.objects.create(title='My Title', description=""" Here's a link: <a href="http://www.example.org">Example</a>, and an image: <img src="http://www.example.org/logo.png" alt="logo">""") out = StringIO() call_command('checklinks', stdout=out) self.assertEqual( out.getvalue(), "Checking all links that haven't been tested for 10080 minutes.\n" "0 internal URLs and 0 external URLs have been checked.\n" ) yesterday = datetime.now() - timedelta(days=1) Url.objects.all().update(last_checked=yesterday) out = StringIO() call_command('checklinks', externalinterval=20, stdout=out) self.assertEqual( out.getvalue(), "Checking all links that haven't been tested for 20 minutes.\n" "0 internal URLs and 2 external URLs have been checked.\n" ) Url.objects.all().update(last_checked=yesterday) out = StringIO() call_command('checklinks', externalinterval=20, limit=1, stdout=out) self.assertEqual( out.getvalue(), "Checking all links that haven't been tested for 20 minutes.\n" "Will run maximum of 1 checks this run.\n" "0 internal URLs and 1 external URLs have been checked.\n" )
def test_command_output(self): out = StringIO() call_command('drf_create_token', self.user.username, stdout=out) token_saved = Token.objects.first() self.assertIn('Generated token', out.getvalue()) self.assertIn(self.user.username, out.getvalue()) self.assertIn(token_saved.key, out.getvalue())
class GenerateTweetHtml(TestCase): def setUp(self): user_1 = factories.UserFactory(screen_name='terry') user_2 = factories.UserFactory(screen_name='bob') tweets_1 = factories.TweetFactory.create_batch(2, user=user_1) tweets_2 = factories.TweetFactory.create_batch(3, user=user_2) account_1 = factories.AccountFactory(user=user_1) account_2 = factories.AccountFactory(user=user_2) self.out = StringIO() @patch.object(Tweet, 'save') def test_with_all_accounts(self, save_method): call_command('generate_twitter_tweet_html', stdout=self.out) self.assertEqual(save_method.call_count, 5) self.assertIn('Generated HTML for 5 Tweets', self.out.getvalue()) @patch.object(Tweet, 'save') def test_with_one_account(self, save_method): call_command('generate_twitter_tweet_html', account='terry', stdout=self.out) self.assertEqual(save_method.call_count, 2) self.assertIn('Generated HTML for 2 Tweets', self.out.getvalue()) def test_with_invalid_account(self): with self.assertRaises(CommandError): call_command('generate_twitter_tweet_html', account='thelma')
class FetchFlickrPhotosTestCase(TestCase): def setUp(self): self.out = StringIO() self.out_err = StringIO() def test_fail_with_no_args(self): with self.assertRaises(CommandError): call_command('fetch_flickr_photos') def test_fail_with_account_only(self): with self.assertRaises(CommandError): call_command('fetch_flickr_photos', account='35034346050@N01') def test_fail_with_non_numeric_days(self): with self.assertRaises(CommandError): call_command('fetch_flickr_photos', days='foo') @patch('ditto.flickr.management.commands.fetch_flickr_photos.RecentPhotosMultiAccountFetcher') def test_sends_days_to_fetcher_with_account(self, fetcher): call_command('fetch_flickr_photos', account='35034346050@N01', days='4') fetcher.assert_called_with(nsid='35034346050@N01') fetcher.return_value.fetch.assert_called_with(days=4) @patch('ditto.flickr.management.commands.fetch_flickr_photos.RecentPhotosMultiAccountFetcher') def test_sends_days_to_fetcher_no_account(self, fetcher): call_command('fetch_flickr_photos', days='4') fetcher.assert_called_with(nsid=None) fetcher.return_value.fetch.assert_called_with(days=4) @patch('ditto.flickr.management.commands.fetch_flickr_photos.RecentPhotosMultiAccountFetcher') def test_sends_all_to_fetcher_with_account(self, fetcher): call_command( 'fetch_flickr_photos', account='35034346050@N01', days='all') fetcher.assert_called_with(nsid='35034346050@N01') fetcher.return_value.fetch.assert_called_with(days='all') @patch('ditto.flickr.management.commands.fetch_flickr_photos.RecentPhotosMultiAccountFetcher') def test_success_output(self, fetcher): fetcher.return_value.fetch.return_value =\ [{'account': 'Phil Gyford', 'success': True, 'fetched': '40'}] call_command('fetch_flickr_photos', days='4', stdout=self.out) self.assertIn('Phil Gyford: Fetched 40 Photos', self.out.getvalue()) @patch('ditto.flickr.management.commands.fetch_flickr_photos.RecentPhotosMultiAccountFetcher') def test_success_output_verbosity_0(self, fetcher): fetcher.return_value.fetch.return_value =\ [{'account': 'Phil Gyford', 'success': True, 'fetched': '40'}] call_command('fetch_flickr_photos', days='4', verbosity=0, stdout=self.out) self.assertEqual('', self.out.getvalue()) @patch('ditto.flickr.management.commands.fetch_flickr_photos.RecentPhotosMultiAccountFetcher') def test_error_output(self, fetcher): fetcher.return_value.fetch.return_value =\ [{'account': 'Phil Gyford', 'success': False, 'messages': ['Oops']}] call_command('fetch_flickr_photos', days='4', stdout=self.out, stderr=self.out_err) self.assertIn('Phil Gyford: Failed to fetch Photos: Oops', self.out_err.getvalue())
class CommandsTest(TestCase): def setUp(self): self.out = StringIO() self.err = StringIO() call_command('printmodels', stdout=self.out, stderr=self.err) def test_print_models_showing(self): """ test printmodels django command for models""" self.assertIn('tasks42.models.Person', self.out.getvalue()) self.assertIn('error: tasks42.models.Person', self.err.getvalue()) def _command_output_to_dict(self, output): """ convert command output to dict """ models_dict = {} for i in (output.strip()).split("\n"): item = i.split("\t") models_dict[item[0]] = int(item[1]) return models_dict def test_print_models_object_count(self): """ test printmodels django command for object counts""" models_out_dict = self._command_output_to_dict(self.out.getvalue()) self.assertEquals(models_out_dict['tasks42.models.Person'], 1) models_err_dict = self._command_output_to_dict(self.err.getvalue()) self.assertEquals(models_err_dict['error: tasks42.models.Person'], 1)
class CliTestCase(TransactionTestCase): def setUp(self): self.out = StringIO() def test_help(self): try: call_command('constance', '--help') except SystemExit: pass def test_list(self): call_command('constance', 'list', stdout=self.out) self.assertEqual(set(self.out.getvalue().splitlines()), set(dedent(smart_str( u""" BOOL_VALUE True EMAIL_VALUE [email protected] INT_VALUE 1 LINEBREAK_VALUE Spam spam DATE_VALUE 2010-12-24 TIME_VALUE 23:59:59 TIMEDELTA_VALUE 1 day, 2:03:00 LONG_VALUE 123456 STRING_VALUE Hello world UNICODE_VALUE Rivière-Bonjour რუსთაველი CHOICE_VALUE yes DECIMAL_VALUE 0.1 DATETIME_VALUE 2010-08-23 11:29:24 FLOAT_VALUE 3.1415926536 """)).splitlines())) def test_get(self): call_command('constance', *('get EMAIL_VALUE'.split()), stdout=self.out) self.assertEqual(self.out.getvalue().strip(), "*****@*****.**") def test_set(self): call_command('constance', *('set EMAIL_VALUE [email protected]'.split()), stdout=self.out) self.assertEqual(config.EMAIL_VALUE, "*****@*****.**") call_command('constance', *('set', 'DATETIME_VALUE', '2011-09-24', '12:30:25'), stdout=self.out) self.assertEqual(config.DATETIME_VALUE, datetime(2011, 9, 24, 12, 30, 25)) def test_get_invalid_name(self): self.assertRaisesMessage(CommandError, "NOT_A_REAL_CONFIG is not defined in settings.CONSTANCE_CONFIG", call_command, 'constance', 'get', 'NOT_A_REAL_CONFIG') def test_set_invalid_name(self): self.assertRaisesMessage(CommandError, "NOT_A_REAL_CONFIG is not defined in settings.CONSTANCE_CONFIG", call_command, 'constance', 'set', 'NOT_A_REAL_CONFIG', 'foo') def test_set_invalid_value(self): self.assertRaisesMessage(CommandError, "Enter a valid email address.", call_command, 'constance', 'set', 'EMAIL_VALUE', 'not a valid email') def test_set_invalid_multi_value(self): self.assertRaisesMessage(CommandError, "Enter a list of values.", call_command, 'constance', 'set', 'DATETIME_VALUE', '2011-09-24 12:30:25')
def test_success(self): out = StringIO() call_command('check_schema', stdout=out) self.assertIn('ERROR', out.getvalue()) with self.settings(SIMPLE_JSONSCHEMA=s): out = StringIO() call_command('check_schema', stdout=out) self.assertIn('SUCCESS', out.getvalue())
def test_command_output_given_handlers_and_typology(self): maat.register(TestModel, TestMaatHandler) out = StringIO() args = ['djangomaat.testmodel:typology1'] call_command('populate_maat_ranking', stdout=out, *args, **{'verbosity': 1}) self.assertIn('Handler: djangomaat.testmodel - Typology: typology1', out.getvalue()) self.assertNotIn('typology2', out.getvalue()) maat.unregister(TestModel)
def test_crearVacaciones(self): out = StringIO() call_command('setVacaciones', '2015', '22', str(self.centro.pk), stdout=out) print(out.getvalue()) self.assertIn('Ok', out.getvalue()) call_command('setVacaciones', '2015', '22', str(self.centro.pk), stdout=out) print(out.getvalue()) self.assertIn('Error', out.getvalue())
def test_creacion_error(self): out = StringIO() call_command('crearCalendario', 'ficheros/festivos.txt', '2015', str(self.centro.pk), stdout=out) print(out.getvalue()) self.assertIn('OK', out.getvalue()) call_command('crearCalendario', 'ficheros/festivos.txt', '2015', str(self.centro.pk), stdout=out) print(out.getvalue()) self.assertIn('Error', out.getvalue())
def test_update_info_only_output(self): SecurityFactory(symbol='600000') out = StringIO() call_command('getbasicinfos', 'Tushare', stdout=out) self.assertIn('Added 0 Securities', out.getvalue()) self.assertIn('Added 1 Infos', out.getvalue())
class ImportTweets(TestCase): def setUp(self): self.patcher = patch('ditto.twitter.management.commands.import_twitter_tweets.TweetIngester.ingest') self.ingest_mock = self.patcher.start() self.out = StringIO() self.out_err = StringIO() def tearDown(self): self.patcher.stop() def test_fails_with_no_args(self): "Fails when no arguments are provided" with self.assertRaises(CommandError): call_command('import_twitter_tweets') def test_fails_with_invalid_directory(self): with patch('os.path.isdir', return_value=False): with self.assertRaises(CommandError): call_command('import_twitter_tweets', path='/wrong/path') def test_calls_ingest_method(self): with patch('os.path.isdir', return_value=True): call_command('import_twitter_tweets', path='/right/path', stdout=self.out) self.ingest_mock.assert_called_once_with( directory='/right/path/data/js/tweets') def test_success_output(self): """Outputs the correct response if ingesting succeeds.""" self.ingest_mock.return_value = { 'success': True, 'tweets': 12345, 'files': 21 } with patch('os.path.isdir', return_value=True): call_command('import_twitter_tweets', path='/right/path', stdout=self.out) self.assertIn('Imported 12345 tweets from 21 files', self.out.getvalue()) def test_success_output_verbosity_0(self): """Outputs nothing if ingesting succeeds.""" self.ingest_mock.return_value = { 'success': True, 'tweets': 12345, 'files': 21 } with patch('os.path.isdir', return_value=True): call_command('import_twitter_tweets', path='/right/path', verbosity=0, stdout=self.out) self.assertEqual('', self.out.getvalue()) def test_error_output(self): """Outputs the correct error if ingesting fails.""" self.ingest_mock.return_value = { 'success': False, 'messages': ['Something went wrong'], } with patch('os.path.isdir', return_value=True): call_command('import_twitter_tweets', path='/right/path', stdout=self.out, stderr=self.out_err) self.assertIn('Something went wrong', self.out_err.getvalue())
def test_silenced_error(self): out = StringIO() err = StringIO() try: call_command('check', stdout=out, stderr=err) except CommandError: self.fail("The mycheck.E001 check should be silenced.") self.assertEqual(out.getvalue(), 'System check identified no issues (1 silenced).\n') self.assertEqual(err.getvalue(), '')
def test_should_build_rules(self): out = StringIO() err = StringIO() build_mock = Mock() with patch('probes.models.Probes.build_rules', build_mock): call_command('refreshprobes', '-b', 'probe1', stdout=out, stderr=err) build_mock.assert_called_once() self.assertIn('Build complete', out.getvalue()) self.assertEqual('', err.getvalue())
def test_invalid_mbox(self): out = StringIO() # we haven't created a project yet, so this will fail call_command('parsearchive', os.path.join(TEST_MAIL_DIR, '0001-git-pull-request.mbox'), stdout=out) self.assertIn('Processed 1 messages -->', out.getvalue()) self.assertIn(' 1 dropped', out.getvalue())
def test_should_update_ruleset(self): out = StringIO() err = StringIO() update_mock = Mock() with patch('rules.models.Ruleset.update', update_mock): call_command('refreshprobes', '-u', 'probe1', stdout=out, stderr=err) update_mock.assert_called_once() self.assertIn('Update complete', out.getvalue()) self.assertEqual('', err.getvalue())
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())
def test_call_command_option_parsing(self): """ When passing the long option name to call_command, the available option key is the option dest name (#22985). """ out = StringIO() management.call_command('dance', stdout=out, opt_3=True) self.assertIn("option3", out.getvalue()) self.assertNotIn("opt_3", out.getvalue()) self.assertNotIn("opt-3", out.getvalue())
def test_proxy_model_included(self): """ Regression for #11428 - Proxy models aren't included when you dumpdata """ stdout = StringIO() # Create an instance of the concrete class widget = Widget.objects.create(name='grommet') management.call_command( 'dumpdata', 'fixtures_regress.widget', 'fixtures_regress.widgetproxy', format='json', stdout=stdout ) self.assertJSONEqual( stdout.getvalue(), """[{"pk": %d, "model": "fixtures_regress.widget", "fields": {"name": "grommet"}}]""" % widget.pk )
def test_attribute_name_not_python_keyword(self): out = StringIO() # Lets limit the introspection to tables created for models of this # application call_command('inspectdb', table_name_filter=lambda tn:tn.startswith('inspectdb_'), stdout=out) output = out.getvalue() error_message = "inspectdb generated an attribute name which is a python keyword" # Recursive foreign keys should be set to 'self' self.assertIn("parent = models.ForeignKey('self')", output) self.assertNotIn("from = models.ForeignKey(InspectdbPeople)", output, msg=error_message) # As InspectdbPeople model is defined after InspectdbMessage, it should be quoted self.assertIn("from_field = models.ForeignKey('InspectdbPeople', db_column='from_id')", output) self.assertIn("people_pk = models.ForeignKey(InspectdbPeople, primary_key=True)", output) self.assertIn("people_unique = models.ForeignKey(InspectdbPeople, unique=True)", output)
def test_custom_fields(self): """ Introspection of columns with a custom field (#21090) """ out = StringIO() orig_data_types_reverse = connection.introspection.data_types_reverse try: connection.introspection.data_types_reverse = { 'text': 'myfields.TextField', 'bigint': 'BigIntegerField', } call_command('inspectdb', table_name_filter=lambda tn: tn.startswith('inspectdb_columntypes'), stdout=out) output = out.getvalue() self.assertIn("text_field = myfields.TextField()", output) self.assertIn("big_int_field = models.BigIntegerField()", output) finally: connection.introspection.data_types_reverse = orig_data_types_reverse
def test_console_stream_kwarg(self): """ Test that the console backend can be pointed at an arbitrary stream. """ s = StringIO() connection = mail.get_connection( 'django.core.mail.backends.console.EmailBackend', stream=s) send_mail('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], connection=connection) message = force_bytes(s.getvalue().split('\n' + ('-' * 79) + '\n')[0]) self.assertMessageHasHeaders( message, {('MIME-Version', '1.0'), ('Content-Type', 'text/plain; charset="utf-8"'), ('Content-Transfer-Encoding', '7bit'), ('Subject', 'Subject'), ('From', '*****@*****.**'), ('To', '*****@*****.**')}) self.assertIn(b'\nDate: ', message)
def test_swappable_user(self): "A superuser can be created when a custom User model is in use" # We can use the management command to create a superuser # We skip validation because the temporary substitution of the # swappable User model messes with validation. new_io = StringIO() call_command("createsuperuser", interactive=False, email="*****@*****.**", date_of_birth="1976-04-01", stdout=new_io, skip_validation=True) command_output = new_io.getvalue().strip() self.assertEqual(command_output, 'Superuser created successfully.') u = CustomUser._default_manager.get(email="*****@*****.**") self.assertEqual(u.date_of_birth, date(1976, 4, 1)) # created password should be unusable self.assertFalse(u.has_usable_password())
def test_create_superuser(self): """command creates superuser""" out = StringIO() call_command("createsuperuser", interactive=False, username="******", email="*****@*****.**", password="******", stdout=out) new_user = UserModel.objects.order_by('-id')[:1][0] self.assertEqual( out.getvalue().splitlines()[-1].strip(), 'Superuser #%s has been created successfully.' % new_user.pk) self.assertEqual(new_user.username, 'joe') self.assertEqual(new_user.email, '*****@*****.**') self.assertTrue(new_user.check_password("Pass.123"))
def test_command(self): if django.VERSION[:2] >= (1, 10): return tmpname = "testapptest" # TODO better temp dir handling tmpdir = "/tmp" tmppath = os.path.join(tmpdir, tmpname) self.assertFalse(os.path.isdir(tmppath)) out = StringIO() try: call_command('create_app', tmpname, parent_path=tmpdir, stdout=out) finally: if os.path.isdir(tmppath): shutil.rmtree(tmppath) output = out.getvalue() self.assertIn("Application '%s' created." % tmpname, output)
def test_unique_together_meta(self): out = StringIO() call_command('inspectdb', table_name_filter=lambda tn: tn.startswith( 'inspectdb_uniquetogether'), stdout=out) output = out.getvalue() unique_re = re.compile(r'.*unique_together = \((.+),\).*') unique_together_match = re.findall(unique_re, output) # There should be one unique_together tuple. self.assertEqual(len(unique_together_match), 1) fields = unique_together_match[0] # Fields with db_column = field name. self.assertIn("('field1', 'field2')", fields) # Fields from columns whose names are Python keywords. self.assertIn("('field1', 'field2')", fields) # Fields whose names normalize to the same Python field name and hence # are given an integer suffix. self.assertIn("('non_unique_column', 'non_unique_column_0')", fields)
def test_clear_delete_referenced_action(self): """ Clear KV store and delete referenced thumbnails """ name1, name2 = self.make_test_thumbnails('400x300', '200x200') management.call_command('thumbnail', 'clear', verbosity=0) name3, = self.make_test_thumbnails('100x100') out = StringIO('') management.call_command('thumbnail', 'clear_delete_referenced', verbosity=1, stdout=out) lines = out.getvalue().split("\n") self.assertEqual( lines[0], "Delete all thumbnail files referenced in Key Value Store ... [Done]" ) self.assertEqual(lines[1], "Clear the Key Value Store ... [Done]") self.assertTrue(os.path.isfile(name1)) self.assertTrue(os.path.isfile(name2)) self.assertFalse(os.path.isfile(name3))
def test_expired_bans_handling(self): """expired bans are flagged as such""" # create 5 bans then update their valid date to past one for i in range(5): Ban.objects.create(banned_value="abcd") expired_date = (timezone.now() - timedelta(days=10)) Ban.objects.all().update(expires_on=expired_date, is_checked=True) self.assertEqual(Ban.objects.filter(is_checked=True).count(), 5) command = invalidatebans.Command() out = StringIO() call_command(command, stdout=out) command_output = out.getvalue().splitlines()[0].strip() self.assertEqual(command_output, 'Bans invalidated: 5') self.assertEqual(Ban.objects.filter(is_checked=True).count(), 0)
def test_optparse_compatibility(self): """ optparse should be supported during Django 1.8/1.9 releases. """ out = StringIO() with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=RemovedInDjango20Warning) management.call_command('optparse_cmd', stdout=out) self.assertEqual(out.getvalue(), "All right, let's dance Rock'n'Roll.\n") # Simulate command line execution old_stdout, old_stderr = sys.stdout, sys.stderr sys.stdout, sys.stderr = StringIO(), StringIO() try: management.execute_from_command_line(['django-admin', 'optparse_cmd']) finally: output = sys.stdout.getvalue() sys.stdout, sys.stderr = old_stdout, old_stderr self.assertEqual(output, "All right, let's dance Rock'n'Roll.\n")
def test_digits_column_name_introspection(self): """Introspection of column names consist/start with digits (#16536/#17676)""" out = StringIO() # Lets limit the introspection to tables created for models of this # application call_command('inspectdb', table_name_filter=lambda tn:tn.startswith('inspectdb_'), stdout=out) output = out.getvalue() error_message = "inspectdb generated a model field name which is a number" self.assertNotIn(" 123 = models.CharField", output, msg=error_message) self.assertIn("number_123 = models.CharField", output) error_message = "inspectdb generated a model field name which starts with a digit" self.assertNotIn(" 4extra = models.CharField", output, msg=error_message) self.assertIn("number_4extra = models.CharField", output) self.assertNotIn(" 45extra = models.CharField", output, msg=error_message) self.assertIn("number_45extra = models.CharField", output)
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
class TestHarmfulCSV(TestCase): def setUp(self): self.dir = mkdtemp() self.csv = join(self.dir, 'test.csv') SuspectChangesetFactory() self.changeset = HarmfulChangesetFactory() self.out = StringIO() call_command('generate_harmful_csv', self.csv, stdout=self.out) def test_csv_creation(self): self.assertTrue(exists(self.csv)) csv = reader(open(self.csv, 'r')) csv_rows = [row for row in csv] self.assertEqual(len(csv_rows), 2) self.assertEqual(csv_rows[1][0], str(self.changeset.id)) self.assertIn('File {} created.'.format(self.csv), self.out.getvalue()) def tearDown(self): rmtree(self.dir)
def test_special_column_name_introspection(self): """ Introspection of column names containing special characters, unsuitable for Python identifiers """ out = StringIO() call_command('inspectdb', stdout=out) output = out.getvalue() base_name = 'Field' if connection.vendor != 'oracle' else 'field' self.assertIn("field = models.IntegerField()", output) self.assertIn("field_field = models.IntegerField(db_column='%s_')" % base_name, output) self.assertIn("field_field_0 = models.IntegerField(db_column='%s__')" % base_name, output) self.assertIn("field_field_1 = models.IntegerField(db_column='__field')", output) self.assertIn("prc_x = models.IntegerField(db_column='prc(%) x')", output) if PY3: # Python 3 allows non-ascii identifiers self.assertIn("tamaño = models.IntegerField()", output) else: self.assertIn("tama_o = models.IntegerField(db_column='tama\\xf1o')", output)
def test_option_with_mixed_arguments(self): out = StringIO() call_command('grepdb', 'quick', 'tests.TestModel.text_field', '-s', '-l', 'staging', 'production', 'default', 'https://dev.example.com', stdout=out) expected = "\x1b[1m\x1b[36m\n<class 'django_grepdb.tests.models.TestModel'> " \ "text_field\x1b[0m\n\x1b[1m\x1b[32mTestModel object (pk=1)\x1b[0m\n" \ "\x1b[32mhttps://staging.example.com/admin/tests/testmodel/1/\x1b[0m\n" \ "\x1b[32mhttps://example.com/admin/tests/testmodel/1/\x1b[0m\n" \ "\x1b[32mhttps://local.example.com/admin/tests/testmodel/1/\x1b[0m\n" \ "\x1b[32mhttps://dev.example.com/admin/tests/testmodel/1/\x1b[0m\n" self.assertEqual(out.getvalue(), expected)
def test_command_start_and_end_index(self, mock_create_manual_enrollment_orders): """ Test command with batch size """ mock_create_manual_enrollment_orders.return_value = ( 0, 0, 0, []) # not correct return value, just fixes unpack out = StringIO() call_command('create_orders_for_old_enterprise_course_enrollment', '--start-index=5', '--end-index=20', '--batch-size=10', '--sleep-time=0.5', stdout=out) output = out.getvalue() self.assertIn("Total Enrollments count to process: 15", output) self.assertIn('[Final Summary] Enrollments Success: ', output) self.assertEqual(mock_create_manual_enrollment_orders.call_count, 2) # batch of 2 (10, 5)
def test_with_no_recent_contact_found(self): """ Test if no recent contact found it should sync all contacts """ with patch.object(sync_command, '_get_last_synced_contact_email', return_value=None): sync_with_hubspot = patch.object(sync_command, '_sync_with_hubspot') mock_sync_with_hubspot = sync_with_hubspot.start() out = StringIO() call_command('sync_hubspot_contacts', '--initial-sync-days=20', '--batch-size=2', stdout=out) output = out.getvalue() self.assertIn('Successfully synced users', output) self.assertEqual(mock_sync_with_hubspot.call_count, 5) sync_with_hubspot.stop()
class HarvestLanguagesTestCase(TestCase): def setUp(self): self.stdout = StringIO() self.stderr = StringIO() self.args = ['app/fixtures/locations'] self.opts = {'stdout': self.stdout, 'stderr': self.stderr} def test_nargs(self): for args in ( [], ['app/fixtures/locations'] * 2, ['app/fixtures/locations'] * 3, ): with self.assertRaises(CommandError): call_command('harvest_languages', *args, **self.opts) def test_command(self): call_command('harvest_languages', *self.args, **self.opts) self.assertEqual('', self.stderr.getvalue()) self.assertEqual(Language.objects.count(), 130) ain = Language.objects.get(iso_code='ain') self.assertEqual(ain.latitude, 43.0) self.assertEqual(ain.longitude, 143.0) fin = Language.objects.get(iso_code='fin') self.assertEqual(fin.latitude, 62.0) self.assertEqual(fin.longitude, 25.0) isl = Language.objects.get(iso_code='isl') self.assertEqual(isl.latitude, 65.0) self.assertEqual(isl.longitude, -17.0) krl = Language.objects.get(iso_code='krl') self.assertEqual(krl.latitude, 64.0) self.assertEqual(krl.longitude, 32.0) rus = Language.objects.get(iso_code='rus') self.assertEqual(rus.latitude, 56.0) self.assertEqual(rus.longitude, 38.0)
def test_forum_archive_by_start_date(self): """command archives forum content based on start date""" forum = Forum.objects.all_forums().filter(role="forum")[:1][0] archive = Forum.objects.all_forums().filter(role="category")[:1][0] forum.prune_started_after = 20 forum.archive_pruned_in = archive forum.save() # post old threads with recent replies started_on = timezone.now() - timedelta(days=30) posted_on = timezone.now() for t in xrange(10): thread = testutils.post_thread(forum, started_on=started_on) testutils.reply_thread(thread, posted_on=posted_on) # post recent threads that will be preserved threads = [testutils.post_thread(forum) for t in xrange(10)] forum.synchronize() self.assertEqual(forum.threads, 20) self.assertEqual(forum.posts, 30) # run command command = pruneforums.Command() out = StringIO() command.execute(stdout=out) forum.synchronize() self.assertEqual(forum.threads, 10) self.assertEqual(forum.posts, 10) archive.synchronize() self.assertEqual(archive.threads, 10) self.assertEqual(archive.posts, 20) for thread in threads: forum.thread_set.get(id=thread.id) command_output = out.getvalue().strip() self.assertEqual(command_output, 'Forums were pruned')
class LoadCountyLimitsTestCase(TestCase): def prepare_sample_data(self, filename): with open(filename, 'w') as data: data.write("Header to be skipped\n") data.write('DC,01,001,01001,DC County 1,417000,271050,417000\n') data.write('DC,01,002,01002,DC County 2,417000,271050,417000\n') data.close() def setUp(self): self.c = Command() self.out = StringIO() self.c.stdout = self.c.stderr = self.out self.test_dir = '%s/test_folder' % os.path.dirname(os.path.realpath(__file__)) os.mkdir(self.test_dir) os.chdir(self.test_dir) def tearDown(self): shutil.rmtree(self.test_dir) def test_handle__no_confirm(self): """ .. check that nothing happens when confirm is not y|Y.""" self.c.handle(stdout=self.out) self.assertNotIn(self.out.getvalue(), 'Successfully loaded data from') def test_handle__no_arguments(self): """ .. check that CommandError is raised.""" self.assertRaises(CommandError, self.c.handle, confirmed='y', stdout=self.out) def test_handle__bad_file(self): """ .. check that CommandError is raised when path to file is wrong.""" self.assertRaises(CommandError, self.c.handle, 'inexistent.file.csv', confirmed='Y', stdout=self.out) def test_handle__success(self): """ .. check that all countylimits are loaded.""" fname = 'county-limits.csv' self.prepare_sample_data(fname) self.c.handle('%s/%s' % (self.test_dir, fname), confirmed='Y') self.assertIn('Successfully loaded data from %s/%s' % (self.test_dir, fname), self.out.getvalue()) county_limits = CountyLimit.objects.all() self.assertEqual(len(county_limits), 2)
def test_generate(self): out = StringIO() call_command( 'demo', username='******', password='******', email='*****@*****.**', currency='USD', interactive=False, stdout=out, ) self.assertEqual( out.getvalue(), 'Data have been generated successfully.\n', ) user_model = get_user_model() user = user_model.objects.get(username='******') self.assertTrue(user.check_password('bar')) self.assertEqual(user.email, '*****@*****.**') self.assertEqual(user.user_permissions.count(), 13) bankaccount = BankAccount.objects.get(owners=user) self.assertEqual(bankaccount.currency, 'USD') self.assertEqual(len(BankTransactionTag.objects.filter(owner=user)), 5) self.assertEqual( (BankTransactionScheduler.objects.filter( bankaccount=bankaccount).count()), 3, ) self.assertEqual( (BankTransaction.objects.filter(bankaccount=bankaccount, scheduled=True).count()), 3, ) self.assertGreaterEqual( (BankTransaction.objects.filter(bankaccount=bankaccount, scheduled=False).count()), 20, )
def test_remove_experiment_displays_prompt_and_user_do_not_confirm_removing( self, mock_user_input): owner = create_owner('labX') experiment = create_experiment(1, owner=owner) out = StringIO() call_command('remove_experiment', experiment.nes_id, experiment.owner, stdout=out) self.assertEqual(mock_user_input.called, True) (text, ), kwargs = mock_user_input.call_args self.assertEqual( text, BaseCommand().style.WARNING( 'All versions of experiment "%s" will be destroyed and cannot be ' 'recovered. Are you sure? (Yes/n) ' % experiment.title)) self.assertTrue(Experiment.objects.exists()) self.assertIn('Aborted', out.getvalue())
class ImportCategoriesTest(TestCase): def setUp(self): self.out = StringIO() call_command( 'importcategories', 'marketplace', os.path.abspath('channels/tests/fixtures/categories.csv'), stdout=self.out ) def test_channel_created(self): self.assertEqual(Channel.objects.count(), 1) def test_categories_created(self): self.assertEqual( Channel.objects.get(name='marketplace').categories.count(), 23) def test_stdout(self): self.assertIn('Total: 23', self.out.getvalue())
def test_createsuperuser_command_with_database_option(self): " createsuperuser command should operate on specified DB" new_io = StringIO() call_command( "createsuperuser", interactive=False, username="******", email="*****@*****.**", database='other', stdout=new_io ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, 'Superuser created successfully.') u = models.User.objects.using('other').get(username="******") self.assertEqual(u.email, '*****@*****.**') new_io.close()
def test_without_commit(self): """ Verify the command does not modify any baskets, if the commit flag is not specified. """ queryset = Basket.objects.filter(site__isnull=True) expected = queryset.count() # Call the command with dry-run flag out = StringIO() call_command(self.command, site_id=self.site.id, commit=False, stderr=out) # Verify no baskets affected self.assertEqual(queryset.count(), expected) # Verify the number of baskets expected to be deleted was printed to stderr expected = 'This has been an example operation. If the --commit flag had been included, the command ' \ 'would have associated [{}] baskets with site [{}].'.format(len(self.unassociated_baskets), self.site) self.assertEqual(out.getvalue().strip(), expected)
def test_for_missing_migrations(self): output = StringIO() options = { "interactive": False, "dry_run": True, "stdout": output, "check_changes": True, } try: call_command("makemigrations", **options) except SystemExit as e: status_code = text_type(e) else: # the "no changes" exit code is 0 status_code = "0" if status_code == "1": self.fail("There are missing migrations:\n {}".format( output.getvalue()))
def test_show_usage_yearly(self): out = StringIO() call_command('show_usage', '--yearly', '--subscription-start={:%m/%d/%Y}'.format( self.subscription_start), '--ascending', stdout=out) assert out.getvalue().split() == ''' year start end registered activated active ------ ---------- ---------- ------------ ----------- -------- Y01 2010-01-24 2011-01-24 1 1 1 Y02 2011-01-24 2012-01-24 2 2 1 Y03 2012-01-24 2013-01-24 3 3 1 Y04 2013-01-24 2014-01-24 4 4 1 Y05 2014-01-24 2015-01-24 5 5 1 Y06 2015-01-24 2016-01-24 7 7 2 Y07 2016-01-24 2017-01-24 8 8 1 Y08 2017-01-24 2017-04-04 9 9 1 '''.split()
def test_3d_columns(self): out = StringIO() call_command('inspectdb', table_name_filter=lambda tn: tn == 'inspectapp_fields3d', stdout=out) output = out.getvalue() if connection.features.supports_geometry_field_introspection: self.assertIn('point = models.PointField(dim=3)', output) if postgis: # Geography type is specific to PostGIS self.assertIn( 'pointg = models.PointField(geography=True, dim=3)', output) self.assertIn('line = models.LineStringField(dim=3)', output) self.assertIn('poly = models.PolygonField(dim=3)', output) else: self.assertIn('point = models.GeometryField(', output) self.assertIn('pointg = models.GeometryField(', output) self.assertIn('line = models.GeometryField(', output) self.assertIn('poly = models.GeometryField(', output)
def test_successful_project_transfer(self): # pylint: disable=C0103 """"Test for a successful project transfer.""" user_model = get_user_model() user_1_data = { 'username': '******', 'email': '*****@*****.**', 'password': '******' } user_2_data = { 'username': '******', 'email': '*****@*****.**', 'password': '******' } user1 = user_model.objects.create_user(**user_1_data) user2 = user_model.objects.create_user(**user_2_data) Project.objects.create(name='Test_project_1', organization=user1, created_by=user1) Project.objects.create(name='Test_project_2', organization=user1, created_by=user1) Project.objects.create(name='Test_project_3', organization=user1, created_by=user1) Project.objects.create(name='Test_project_4', organization=user1, created_by=user1) Project.objects.create(name='Test_project_5', organization=user1, created_by=user1) mock_stdout = StringIO() sys.stdout = mock_stdout call_command('transferproject', current_owner='user1', new_owner='user2', all_projects=True, stdout=mock_stdout) expected_output = 'Projects transferred successfully' self.assertIn(expected_output, mock_stdout.getvalue()) self.assertEqual(0, Project.objects.filter(organization=user1).count()) self.assertEqual(5, Project.objects.filter(organization=user2).count())