def test_basic(self): """ #15346, #15573 - create_default_site() creates an example site only if none exist. """ with captured_stdout() as stdout: create_default_site(self.app_config) self.assertEqual(Site.objects.count(), 1) self.assertIn("Creating example.com", stdout.getvalue()) with captured_stdout() as stdout: create_default_site(self.app_config) self.assertEqual(Site.objects.count(), 1) self.assertEqual("", stdout.getvalue())
def test_send(self): with captured_stdout() as stdout: sms = self.sms numSent = sms.send() self.assertEqual(numSent, 1) output = stdout.getvalue() self.assertTrue("Subject: None" in output) self.assertTrue("From: +15005550006" in output) self.assertTrue("To: +15005550006" in output) self.assertTrue("Body" in output) with captured_stdout() as stdout: sms_no_recipients = self.sms_no_recipients numSent = sms_no_recipients.send() self.assertEqual(numSent, 0) self.assertEqual(stdout.getvalue(), "")
def _run_autocomplete(self): util = ManagementUtility(argv=sys.argv) with captured_stdout() as stdout: try: util.autocomplete() except SystemExit: pass return stdout.getvalue().strip().split('\n')
def test_interactive_false(self): """ non-interactive mode of remove_stale_contenttypes shouldn't delete stale content types. """ with captured_stdout() as stdout: call_command('remove_stale_contenttypes', interactive=False, verbosity=2) self.assertIn("Stale content types remain.", stdout.getvalue()) self.assertEqual(ContentType.objects.count(), self.before_count + 1)
def test_interactive_false(self): """ non-interactive mode of update_contenttypes() shouldn't delete stale content types. """ with captured_stdout() as stdout: contenttypes_management.update_contenttypes(self.app_config, interactive=False) self.assertIn("Stale content types remain.", stdout.getvalue()) self.assertEqual(ContentType.objects.count(), self.before_count + 1)
def test_send_sms(self): with captured_stdout() as stdout: numSent = send_sms("Body", VALID_FROM_NUMBER, [VALID_TO_NUMBER]) self.assertEqual(numSent, 1) self.assertEqual(len(mail.outbox), 0) output = stdout.getvalue() self.assertTrue("Subject: None" in output) self.assertTrue("From: +15005550006" in output) self.assertTrue("To: +15005550006" in output) self.assertTrue("Body" in output)
def test_interactive_true_without_dependent_objects(self): """ interactive mode of remove_stale_contenttypes (the default) deletes stale contenttypes even if there aren't any dependent objects. """ with mock.patch('builtins.input', return_value='yes'): with captured_stdout() as stdout: call_command('remove_stale_contenttypes', verbosity=2) self.assertIn("Deleting stale content type", stdout.getvalue()) self.assertEqual(ContentType.objects.count(), self.before_count)
def test_interactive_true(self): """ interactive mode of update_contenttypes() (the default) should delete stale contenttypes. """ contenttypes_management.input = lambda x: force_str("yes") with captured_stdout() as stdout: contenttypes_management.update_contenttypes(self.app_config) self.assertIn("Deleting stale content type", stdout.getvalue()) self.assertEqual(ContentType.objects.count(), self.before_count)
def setUpTestData(cls): with captured_stdout(): call_command( "remove_stale_contenttypes", interactive=False, include_stale_apps=True, verbosity=2, ) cls.before_count = ContentType.objects.count() cls.content_type = ContentType.objects.create( app_label="contenttypes_tests", model="Fake")
def test_send_mass_sms(self): with captured_stdout() as stdout: datatuple = (("Body", VALID_FROM_NUMBER, [VALID_TO_NUMBER]) for _ in range(10)) numSent = send_mass_sms(datatuple) self.assertEqual(numSent, 10) self.assertEqual(len(mail.outbox), 0) output = stdout.getvalue() self.assertTrue("Subject: None" in output) self.assertTrue("From: +15005550006" in output) self.assertTrue("To: +15005550006" in output) self.assertTrue("Body" in output)
def test_generate_models_command(self): run_sql(DEFAULT_DB_ALIAS, os.path.join(self.project_root, 'fixtures', 'rename_tables.sql')) with captured_stdout() as stdout: call_command('pg_generate_models') output = stdout.getvalue() self.assertIn('# Generated', output, msg=output) self.assertIn('class InvType(models.Model)', output, msg=output) self.assertIn('db_table = \'sde_invTypes\'', output, msg=output)
def test_clean_dead_youtube_link(self): pondlife = Production.objects.get(title='Pondlife') link = pondlife.links.create(link_class='SpeccyWikiPage', parameter='404', is_download_link=False) ProductionLink.objects.filter(id=link.id).update( link_class='YoutubeVideo') with captured_stdout(): clean_dead_youtube_link(link.id) self.assertEqual( pondlife.links.filter(link_class='YoutubeVideo').count(), 0)
def test_time_logging_runner(self): runner = TimeLoggingTestRunner() suite = runner.build_suite( ['test_project.tests.test_test_utils.TestUtils.test_status_signal_emitted'], ) with captured_stdout() as stdout, captured_stderr() as stderr: runner.run_suite(suite) self.assertIn('slow tests (>0.0s)', stdout.getvalue()) self.assertIn('Total slow tests detected: 1', stdout.getvalue()) self.assertIn('Ran 1 test', stderr.getvalue()) self.assertIn('OK', stderr.getvalue())
def test_remove_unseen_boundaries(self): # insert features in the database geojson_data = [self.data_geojson_level_0, self.data_geojson_level_1] with patch("builtins.open") as mock_file: mock_file.return_value.__enter__ = lambda filename: filename mock_file.return_value.__exit__ = Mock() mock_file.return_value.read.side_effect = lambda: geojson_data.pop( 0) with captured_stdout(): call_command("import_geojson", "admin_level_0_simplified.json", "admin_level_1_simplified.json") self.assertOSMIDs({"R1000", "R2000"}) BoundaryAlias.create(self.org, self.admin, AdminBoundary.objects.get(osm_id="R2000"), "My Alias") # update data, and add a new boundary geojson_data = [ self.data_geojson_level_0, self.data_geojson_level_1_new_boundary ] with patch("builtins.open") as mock_file: mock_file.return_value.__enter__ = lambda filename: filename mock_file.return_value.__exit__ = Mock() mock_file.return_value.read.side_effect = lambda: geojson_data.pop( 0) with captured_stdout() as captured_output: call_command("import_geojson", "admin_level_0_simplified.json", "admin_level_1_simplified.json") self.assertEqual( captured_output.getvalue(), "=== parsing admin_level_0_simplified.json\n ** updating Granica (R1000)\n ** removing unseen boundaries (R1000)\n=== parsing admin_level_1_simplified.json\n ** adding Međa 3 (R3000)\n ** removing unseen boundaries (R3000)\n ** Unseen boundaries removed: 1\nOther unseen boundaries removed: 0\n ** updating paths for all of Granica\n", ) self.assertOSMIDs({"R1000", "R3000"})
def test_missing_parent_in_db(self): with patch("builtins.open", mock_open(read_data=self.data_geojson_without_parent)): with captured_stdout() as captured_output: call_command("import_geojson", "admin_level_1_simplified.json") self.assertEqual( captured_output.getvalue(), "=== parsing admin_level_1_simplified.json\nSkipping Međa (R2000) as parent R0 not found.\n", ) self.assertEqual(AdminBoundary.objects.count(), 0)
def test_ignore_ascii(self, create_screenshot_from_production_link): self.skyrider.types.set([ProductionType.objects.get(name="ASCII")]) link = self.skyrider.links.create( link_class='BaseUrl', parameter='http://example.com/skyrider.zip', is_download_link=True) with captured_stdout(): call_command('fetch_remote_zipped_screenshots') self.assertEqual( create_screenshot_from_production_link.delay.call_count, 0)
def test_optparse_compatibility(self): """ optparse should be supported during Django 1.8/1.9 releases. """ out = StringIO() management.call_command('optparse_cmd', stdout=out) self.assertEqual(out.getvalue(), "All right, let's dance Rock'n'Roll.\n") # Simulate command line execution with captured_stdout() as stdout, captured_stderr(): management.execute_from_command_line(['django-admin', 'optparse_cmd']) self.assertEqual(stdout.getvalue(), "All right, let's dance Rock'n'Roll.\n")
def test_interactive_true_without_dependent_objects(self): """ interactive mode of remove_stale_contenttypes (the default) should delete stale contenttypes even if there aren't any dependent objects. """ with mock.patch( 'django.contrib.contenttypes.management.commands.remove_stale_contenttypes.input', return_value='yes'): with captured_stdout() as stdout: call_command('remove_stale_contenttypes', verbosity=2) self.assertIn("Deleting stale content type", stdout.getvalue()) self.assertEqual(ContentType.objects.count(), self.before_count)
def test_questioner_bad_user_choice(self, mock_input): question = 'Make a choice:' with captured_stdout() as stdout: value = self.questioner._choice_input(question, choices='abc') expected_msg = ( f'{question}\n' f' 1) a\n' f' 2) b\n' f' 3) c\n' ) self.assertIn(expected_msg, stdout.getvalue()) self.assertEqual(value, 1)
def test_basic_export(self): with captured_stdout() as stdout: call_command('exportkeys') stdout.seek(0) data = list(csv.DictReader(stdout)) self.assertEquals(len(data), 4) self.assertEquals(data[0]['key'], 'one') self.assertEquals(data[1]['tier'], 'Gold') self.assertEquals(data[2]['status'], 'u') self.assertEquals(data[3]['email'], '*****@*****.**')
def test_feature_multipolygon_geometry(self): with patch("builtins.open", mock_open(read_data=self.data_geojson_multipolygon)): with captured_stdout() as captured_output: call_command("import_geojson", "admin_level_0_simplified.json") self.assertEqual( captured_output.getvalue(), "=== parsing admin_level_0_simplified.json\n ** adding Granica (R1000)\n ** removing unseen boundaries (R1000)\nOther unseen boundaries removed: 0\n ** updating paths for all of Granica\n", ) self.assertOSMIDs({"R1000"})
def test_run(self, clean_dead_youtube_link): pondlife = Production.objects.get(title='Pondlife') link = pondlife.links.create(link_class='YoutubeVideo', parameter='1lFBXWxSrKE', is_download_link=False) ProductionLink.objects.filter(id=link.id).update( link_class='YoutubeVideo') with captured_stdout(): call_command('purge_dead_youtube_links') clean_dead_youtube_link.delay.assert_called_once_with(link.id)
def test_buffer_mode_test_fail(self): runner = DiscoverRunner(buffer=True, verbosity=0) with captured_stdout() as stdout, captured_stderr() as stderr: suite = runner.build_suite( [ "test_runner_apps.buffer.tests_buffer.WriteToStdoutStderrTestCase." "test_fail", ] ) runner.run_suite(suite) self.assertIn("Write to stderr.", stderr.getvalue()) self.assertIn("Write to stdout.", stdout.getvalue())
def test_wrong_filename(self): with patch("builtins.open", mock_open(read_data=self.data_geojson_level_0)): with captured_stdout() as captured_output: call_command("import_geojson", "data.json") self.assertEqual( captured_output.getvalue(), "=== parsing data.json\nSkipping 'data.json', doesn't match file pattern.\n" ) self.assertEqual(AdminBoundary.objects.count(), 0)
def test_ok_filename_admin_level(self): with patch("builtins.open", mock_open(read_data=self.data_geojson_level_0)): with captured_stdout() as captured_output: call_command("import_geojson", "admin_level_0_simplified.json") self.assertEqual( captured_output.getvalue(), "=== parsing admin_level_0_simplified.json\n ** adding Granica (R1000)\n ** removing unseen boundaries (R1000)\nOther unseen boundaries removed: 0\n ** updating paths for all of Granica\n", ) self.assertEqual(AdminBoundary.objects.count(), 1)
def test_good_file_for_screenshot(self, create_screenshot_from_production_link): self.skyrider.types.set([ProductionType.objects.get(name="Graphics")]) link = self.skyrider.links.create( link_class='BaseUrl', parameter='http://example.com/skyrider.zip', is_download_link=True, file_for_screenshot='skyrider.scr' ) with captured_stdout(): call_command('fetch_remote_zipped_screenshots') self.assertEqual(create_screenshot_from_production_link.delay.call_count, 1) link_id, = create_screenshot_from_production_link.delay.call_args.args self.assertEqual(link_id, link.id)
def test_match_by_member_id(self): spb = Releaser.objects.create(name="Spaceballs", is_group=True) slummy = Releaser.objects.create(name="Slummy", is_group=False) spb.member_memberships.create(member=slummy) slummy.external_links.create(link_class='KestraBitworldAuthor', parameter='126') with captured_stdout(): call_command('match_janeway_groups') self.assertTrue( spb.external_links.filter(link_class='KestraBitworldAuthor', parameter='123').exists())
def test_move_sde_command(self): run_sql(DEFAULT_DB_ALIAS, os.path.join(self.project_root, 'fixtures', 'rename_tables.sql')) with captured_stdout() as stdout: call_command('pg_move_sde') output = stdout.getvalue() self.assertIn('Moving SDE tables to sde schema...', output, msg=output) self.assertIn('Moving evesde.sde_invTypes -> sde.sde_invTypes', output, msg=output) self.assertIn('Adding index for primary key column to table ' 'sde_industryActivityMaterials', output, msg=output)
def test_command_deleted_when_flag_set(self): command = ScheduledCommand( name='load_test_data', arg_string='--number-of-prisoners 60 --number-of-transactions 70', cron_entry='* * * * *', next_execution=timezone.now(), delete_after_next=True ) command.save() run_commands = run_scheduled_commands.Command() with captured_stdout(), silence_logger(): run_commands.handle() self.assertEqual(ScheduledCommand.objects.all().count(), 0)
def test_interactive_true_with_dependent_objects(self): """ interactive mode of update_contenttypes() (the default) should delete stale contenttypes and warn of dependent objects """ Post.objects.create(title='post', content_type=self.content_type) contenttypes_management.input = lambda x: force_str("yes") with captured_stdout() as stdout: contenttypes_management.update_contenttypes(self.app_config) self.assertEqual(Post.objects.count(), 0) self.assertIn("1 object of type contenttypes_tests.post:", stdout.getvalue()) self.assertIn("Deleting stale content type", stdout.getvalue()) self.assertEqual(ContentType.objects.count(), self.before_count)
def test_protocol(self): """Launched server serves with HTTP 1.1.""" with captured_stdout() as debug_output: conn = HTTPConnection(LiveServerViews.server_thread.host, LiveServerViews.server_thread.port) try: conn.set_debuglevel(1) conn.request('GET', '/example_view/', headers={"Connection": "keep-alive"}) conn.getresponse().read() conn.request('GET', '/example_view/', headers={"Connection": "close"}) conn.getresponse() finally: conn.close() self.assertEqual(debug_output.getvalue().count("reply: 'HTTP/1.1 200 OK"), 2)
def test_run(self, fetch_production_link_embed_data): pondlife = Production.objects.get(title='Pondlife') # create with a bogus link_class to prevent fetch_production_link_embed_data # from being called on save() link = pondlife.links.create(link_class='SpeccyWikiPage', parameter='1lFBXWxSrKE', is_download_link=False) ProductionLink.objects.filter(id=link.id).update( link_class='YoutubeVideo') with captured_stdout(): call_command('fetch_embed_data') fetch_production_link_embed_data.delay.assert_called_once_with(link.id)
def test_contenttypes_removed_for_apps_not_in_installed_apps(self): ContentType.objects.create(app_label='empty_models', model='Fake 1') ContentType.objects.create(app_label='no_models', model='Fake 2') with mock.patch('builtins.input', return_value='yes'), captured_stdout() as stdout: call_command('remove_stale_contenttypes', include_stale_apps=True, verbosity=2) self.assertIn( "Deleting stale content type 'empty_models | Fake 1'", stdout.getvalue(), ) self.assertIn( "Deleting stale content type 'no_models | Fake 2'", stdout.getvalue(), ) self.assertEqual(ContentType.objects.count(), self.before_count)
def test_remove_other_unseen_boundaries(self): # other unseen boundaries are boundaries which have not been updated in any way for a country # insert features in the database geojson_data = [self.data_geojson_level_0, self.data_geojson_level_1] with patch("builtins.open") as mock_file: mock_file.return_value.__enter__ = lambda filename: filename mock_file.return_value.__exit__ = Mock() mock_file.return_value.read.side_effect = lambda: geojson_data.pop( 0) with captured_stdout(): call_command("import_geojson", "admin_level_0_simplified.json", "admin_level_1_simplified.json") self.assertOSMIDs({"R1000", "R2000"}) # update data, and add a new boundary geojson_data = [self.data_geojson_level_0] with patch("builtins.open") as mock_file: mock_file.return_value.__enter__ = lambda filename: filename mock_file.return_value.__exit__ = Mock() mock_file.return_value.read.side_effect = lambda: geojson_data.pop( 0) with captured_stdout() as captured_output: call_command("import_geojson", "admin_level_0_simplified.json") self.assertEqual( captured_output.getvalue(), "=== parsing admin_level_0_simplified.json\n ** updating Granica (R1000)\n ** removing unseen boundaries (R1000)\nOther unseen boundaries removed: 1\n ** updating paths for all of Granica\n", ) self.assertOSMIDs({"R1000"})
def test_run(self, import_screenshot): sota = Production.objects.create(title="State Of The Art", supertype="production") sota.links.create(link_class='KestraBitworldRelease', parameter=345) with captured_stdout(): call_command('import_janeway_screenshots') self.assertEqual(import_screenshot.delay.call_count, 1) production_id, screenshot_janeway_id, screenshot_url, screenshot_suffix = import_screenshot.delay.call_args.args self.assertEqual(production_id, sota.id) self.assertEqual(screenshot_janeway_id, 111) self.assertEqual( screenshot_url, "http://kestra.exotica.org.uk/files/screenies/28000/154a.png") self.assertEqual(screenshot_suffix, "a")
def test_contenttypes_removed_in_installed_apps_without_models(self): ContentType.objects.create(app_label="empty_models", model="Fake 1") ContentType.objects.create(app_label="no_models", model="Fake 2") with mock.patch("builtins.input", return_value="yes"), captured_stdout() as stdout: call_command("remove_stale_contenttypes", verbosity=2) self.assertNotIn( "Deleting stale content type 'empty_models | Fake 1'", stdout.getvalue(), ) self.assertIn( "Deleting stale content type 'no_models | Fake 2'", stdout.getvalue(), ) self.assertEqual(ContentType.objects.count(), self.before_count + 1)
def test_filter_and_delete(self): VanillaAuthor.objects.create(name="Alpha") VanillaAuthor.objects.create(name="pants") VanillaAuthor.objects.create(name="Beta") VanillaAuthor.objects.create(name="pants") bad_authors = VanillaAuthor.objects.filter(name="pants") assert bad_authors.count() == 2 with captured_stdout(): for author in SmartIterator(bad_authors, report_progress=True): author.delete() assert bad_authors.count() == 0
def test_interactive_true_with_dependent_objects(self): """ interactive mode of update_contenttypes() (the default) should delete stale contenttypes and warn of dependent objects. """ post = Post.objects.create(title="post", content_type=self.content_type) # A related object is needed to show that a custom collector with # can_fast_delete=False is needed. ModelWithNullFKToSite.objects.create(post=post) contenttypes_management.input = lambda x: force_str("yes") with captured_stdout() as stdout: contenttypes_management.update_contenttypes(self.app_config) self.assertEqual(Post.objects.count(), 0) output = stdout.getvalue() self.assertIn("- Content type for contenttypes_tests.Fake", output) self.assertIn("- 1 contenttypes_tests.Post object(s)", output) self.assertIn("- 1 contenttypes_tests.ModelWithNullFKToSite", output) self.assertIn("Deleting stale content type", output) self.assertEqual(ContentType.objects.count(), self.before_count)
def test_interactive_true_with_dependent_objects(self): """ interactive mode of remove_stale_contenttypes (the default) deletes stale contenttypes and warn of dependent objects. """ post = Post.objects.create(title='post', content_type=self.content_type) # A related object is needed to show that a custom collector with # can_fast_delete=False is needed. ModelWithNullFKToSite.objects.create(post=post) with mock.patch('builtins.input', return_value='yes'): with captured_stdout() as stdout: call_command('remove_stale_contenttypes', verbosity=2, stdout=stdout) self.assertEqual(Post.objects.count(), 0) output = stdout.getvalue() self.assertIn('- Content type for contenttypes_tests.Fake', output) self.assertIn('- 1 contenttypes_tests.Post object(s)', output) self.assertIn('- 1 contenttypes_tests.ModelWithNullFKToSite', output) self.assertIn('Deleting stale content type', output) self.assertEqual(ContentType.objects.count(), self.before_count)
def test_migrate_with_existing_target_permission(self): """ Permissions may already exist: - Old workaround was to manually create permissions for proxy models. - Model may have been concrete and then converted to proxy. Output a reminder to audit relevant permissions. """ proxy_model_content_type = ContentType.objects.get_for_model(Proxy, for_concrete_model=False) Permission.objects.create( content_type=proxy_model_content_type, codename='add_proxy', name='Can add proxy', ) Permission.objects.create( content_type=proxy_model_content_type, codename='display_proxys', name='May display proxys information', ) with captured_stdout() as stdout: update_proxy_permissions.update_proxy_model_permissions(apps, None) self.assertIn('A problem arose migrating proxy model permissions', stdout.getvalue())
def test_contenttypes_removed_in_apps_without_models(self): ContentType.objects.create(app_label='no_models', model='Fake') with mock.patch('builtins.input', return_value='yes'), captured_stdout() as stdout: call_command('remove_stale_contenttypes', verbosity=2) self.assertIn("Deleting stale content type 'no_models | Fake'", stdout.getvalue()) self.assertEqual(ContentType.objects.count(), self.before_count)
def get_databases(self, test_labels): suite = self.runner.build_suite(test_labels) with captured_stdout() as stdout: databases = self.runner.get_databases(suite) return databases, stdout.getvalue()
def test_timedelta_default(self, mock): questioner = InteractiveMigrationQuestioner() with captured_stdout(): value = questioner._ask_default() self.assertEqual(value, datetime.timedelta(days=1))
def test_excluded_tags_displayed(self): runner = DiscoverRunner(exclude_tags=['foo', 'bar'], verbosity=3) with captured_stdout() as stdout: runner.build_suite(['test_runner_apps.tagged.tests']) self.assertIn('Excluding test tag(s): bar, foo.\n', stdout.getvalue())
def test_stdin_read(self, select): with captured_stdin() as stdin, captured_stdout() as stdout: stdin.write('print(100)\n') stdin.seek(0) call_command('shell') self.assertEqual(stdout.getvalue().strip(), '100')
def test_command_help(self): with captured_stdout(), captured_stderr(): # `call_command` bypasses the parser; by calling # `execute_from_command_line` with the help subcommand we # ensure that there are no issues with the parser itself. execute_from_command_line(['django-admin', 'help', 'compilemessages'])