def test_load_fixture_with_special_characters(self): management.call_command('loaddata', 'fixture_with[special]chars', verbosity=0) self.assertQuerysetEqual( Article.objects.all(), ['<Article: How To Deal With Special Characters>'])
def handle(self, *fixture_labels, **options): verbosity = options['verbosity'] interactive = options['interactive'] # Create a test database. db_name = connection.creation.create_test_db(verbosity=verbosity, autoclobber=not interactive, serialize=False) # Import the fixture data into the test database. call_command('loaddata', *fixture_labels, **{'verbosity': verbosity}) # Run the development server. Turn off auto-reloading because it causes # a strange error -- it causes this handle() method to be called # multiple times. shutdown_message = ( '\nServer stopped.\nNote that the test database, %r, has not been ' 'deleted. You can explore it on your own.' % db_name ) use_threading = connection.features.test_db_allows_multiple_connections call_command( 'runserver', addrport=options['addrport'], shutdown_message=shutdown_message, use_reloader=False, use_ipv6=options['use_ipv6'], use_threading=use_threading )
def test_dump_and_load_m2m_simple(self): """ Test serializing and deserializing back models with simple M2M relations """ a = M2MSimpleA.objects.create(data="a") b1 = M2MSimpleB.objects.create(data="b1") b2 = M2MSimpleB.objects.create(data="b2") a.b_set.add(b1) a.b_set.add(b2) out = StringIO() management.call_command( 'dumpdata', 'fixtures_regress.M2MSimpleA', 'fixtures_regress.M2MSimpleB', use_natural_foreign_keys=True, stdout=out, ) for model in [M2MSimpleA, M2MSimpleB]: model.objects.all().delete() objects = serializers.deserialize("json", out.getvalue()) for obj in objects: obj.save() new_a = M2MSimpleA.objects.get_by_natural_key("a") self.assertQuerysetEqual(new_a.b_set.all(), ["<M2MSimpleB: b1>", "<M2MSimpleB: b2>"], ordered=False)
def test_comments_extractor(self): management.call_command('makemessages', locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE, 'r', encoding='utf-8') as fp: po_contents = fp.read() self.assertNotIn('This comment should not be extracted', po_contents) # Comments in templates self.assertIn('#. Translators: This comment should be extracted', po_contents) self.assertIn( "#. Translators: Django comment block for translators\n#. " "string's meaning unveiled", po_contents ) self.assertIn('#. Translators: One-line translator comment #1', po_contents) self.assertIn('#. Translators: Two-line translator comment #1\n#. continued here.', po_contents) self.assertIn('#. Translators: One-line translator comment #2', po_contents) self.assertIn('#. Translators: Two-line translator comment #2\n#. continued here.', po_contents) self.assertIn('#. Translators: One-line translator comment #3', po_contents) self.assertIn('#. Translators: Two-line translator comment #3\n#. continued here.', po_contents) self.assertIn('#. Translators: One-line translator comment #4', po_contents) self.assertIn('#. Translators: Two-line translator comment #4\n#. continued here.', po_contents) self.assertIn( '#. Translators: One-line translator comment #5 -- with ' 'non ASCII characters: áéÃóúö', po_contents ) self.assertIn( '#. Translators: Two-line translator comment #5 -- with ' 'non ASCII characters: áéÃóúö\n#. continued here.', po_contents )
def test_path_containing_dots(self): management.call_command( 'loaddata', 'path.containing.dots.json', verbosity=0, ) self.assertEqual(Absolute.objects.count(), 1)
def test_include_views(self): """inspectdb --include-views creates models for database views.""" with connection.cursor() as cursor: cursor.execute('CREATE VIEW inspectdb_people_view AS ' 'SELECT id, name FROM inspectdb_people') out = StringIO() view_model = 'class InspectdbPeopleView(models.Model):' view_managed = 'managed = False # Created from a view.' try: call_command('inspectdb', table_name_filter=inspectdb_tables_only, stdout=out) no_views_output = out.getvalue() self.assertNotIn(view_model, no_views_output) self.assertNotIn(view_managed, no_views_output) call_command('inspectdb', table_name_filter=inspectdb_tables_only, include_views=True, stdout=out) with_views_output = out.getvalue() self.assertIn(view_model, with_views_output) self.assertIn(view_managed, with_views_output) finally: with connection.cursor() as cursor: cursor.execute('DROP VIEW inspectdb_people_view')
def test_attribute_name_not_python_keyword(self): out = StringIO() call_command('inspectdb', table_name_filter=inspectdb_tables_only, 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', models.DO_NOTHING)", output) self.assertNotIn( "from = models.ForeignKey(InspectdbPeople, models.DO_NOTHING)", output, msg=error_message, ) # As InspectdbPeople model is defined after InspectdbMessage, it should be quoted self.assertIn( "from_field = models.ForeignKey('InspectdbPeople', models.DO_NOTHING, db_column='from_id')", output, ) self.assertIn( "people_pk = models.ForeignKey(InspectdbPeople, models.DO_NOTHING, primary_key=True)", output, ) self.assertIn( "people_unique = models.ForeignKey(InspectdbPeople, models.DO_NOTHING, unique=True)", output, )
def test_nk_on_serialize(self): """ Natural key requirements are taken into account when serializing models. """ management.call_command( 'loaddata', 'forward_ref_lookup.json', verbosity=0, ) out = StringIO() management.call_command( 'dumpdata', 'fixtures_regress.book', 'fixtures_regress.person', 'fixtures_regress.store', verbosity=0, format='json', use_natural_foreign_keys=True, use_natural_primary_keys=True, stdout=out, ) self.assertJSONEqual( out.getvalue(), """ [{"fields": {"main": null, "name": "Amazon"}, "model": "fixtures_regress.store"}, {"fields": {"main": null, "name": "Borders"}, "model": "fixtures_regress.store"}, {"fields": {"name": "Neal Stephenson"}, "model": "fixtures_regress.person"}, {"pk": 1, "model": "fixtures_regress.book", "fields": {"stores": [["Amazon"], ["Borders"]], "name": "Cryptonomicon", "author": ["Neal Stephenson"]}}] """)
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 test_adding_arrayfield_with_index(self): """ ArrayField shouldn't have varchar_patterns_ops or text_patterns_ops indexes. """ table_name = 'postgres_tests_chartextarrayindexmodel' call_command('migrate', 'postgres_tests', verbosity=0) with connection.cursor() as cursor: like_constraint_columns_list = [ v['columns'] for k, v in list(connection.introspection.get_constraints(cursor, table_name).items()) if k.endswith('_like') ] # Only the CharField should have a LIKE index. self.assertEqual(like_constraint_columns_list, [['char2']]) # All fields should have regular indexes. with connection.cursor() as cursor: indexes = [ c['columns'][0] for c in connection.introspection.get_constraints(cursor, table_name).values() if c['index'] and len(c['columns']) == 1 ] self.assertIn('char', indexes) self.assertIn('char2', indexes) self.assertIn('text', indexes) call_command('migrate', 'postgres_tests', 'zero', verbosity=0) with connection.cursor() as cursor: self.assertNotIn(table_name, connection.introspection.table_names(cursor))
def test_missing_content_type_rename_ignore(self): call_command('migrate', 'contenttypes_tests', database='default', interactive=False, verbosity=0,) self.assertFalse(ContentType.objects.filter(app_label='contenttypes_tests', model='foo').exists()) self.assertTrue(ContentType.objects.filter(app_label='contenttypes_tests', model='renamedfoo').exists()) call_command('migrate', 'contenttypes_tests', 'zero', database='default', interactive=False, verbosity=0) self.assertTrue(ContentType.objects.filter(app_label='contenttypes_tests', model='foo').exists()) self.assertFalse(ContentType.objects.filter(app_label='contenttypes_tests', model='renamedfoo').exists())
def test_call_command_option_parsing_non_string_arg(self): """ It should be possible to pass non-string arguments to call_command. """ out = StringIO() management.call_command('dance', 1, verbosity=0, stdout=out) self.assertIn("You passed 1 as a positional argument.", out.getvalue())
def test_template_message_context_extractor(self): """ Message contexts are correctly extracted for the {% trans %} and {% blocktrans %} template tags (#14806). """ management.call_command('makemessages', locale=[LOCALE], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE, 'r') as fp: po_contents = fp.read() # {% trans %} self.assertIn('msgctxt "Special trans context #1"', po_contents) self.assertMsgId("Translatable literal #7a", po_contents) self.assertIn('msgctxt "Special trans context #2"', po_contents) self.assertMsgId("Translatable literal #7b", po_contents) self.assertIn('msgctxt "Special trans context #3"', po_contents) self.assertMsgId("Translatable literal #7c", po_contents) # {% trans %} with a filter for minor_part in 'abcdefgh': # Iterate from #7.1a to #7.1h template markers self.assertIn('msgctxt "context #7.1{}"'.format(minor_part), po_contents) self.assertMsgId('Translatable literal #7.1{}'.format(minor_part), po_contents) # {% blocktrans %} self.assertIn('msgctxt "Special blocktrans context #1"', po_contents) self.assertMsgId("Translatable literal #8a", po_contents) self.assertIn('msgctxt "Special blocktrans context #2"', po_contents) self.assertMsgId("Translatable literal #8b-singular", po_contents) self.assertIn("Translatable literal #8b-plural", po_contents) self.assertIn('msgctxt "Special blocktrans context #3"', po_contents) self.assertMsgId("Translatable literal #8c-singular", po_contents) self.assertIn("Translatable literal #8c-plural", po_contents) self.assertIn('msgctxt "Special blocktrans context #4"', po_contents) self.assertMsgId("Translatable literal #8d %(a)s", po_contents)
def test_loading_stdin(self): """Loading fixtures from stdin with json and xml.""" tests_dir = os.path.dirname(__file__) fixture_json = os.path.join(tests_dir, 'fixtures', 'fixture1.json') fixture_xml = os.path.join(tests_dir, 'fixtures', 'fixture3.xml') with mock.patch('djmodels.core.management.commands.loaddata.sys.stdin', open(fixture_json, 'r')): management.call_command('loaddata', '--format=json', '-', verbosity=0) self.assertEqual(Article.objects.count(), 2) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Time to reform copyright>', '<Article: Poker has no place on ESPN>', ]) with mock.patch('djmodels.core.management.commands.loaddata.sys.stdin', open(fixture_xml, 'r')): management.call_command('loaddata', '--format=xml', '-', verbosity=0) self.assertEqual(Article.objects.count(), 3) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: XML identified as leading cause of cancer>', '<Article: Time to reform copyright>', '<Article: Poker on TV is great!>', ])
def test_silenced_warning(self): out = StringIO() err = StringIO() call_command('check', stdout=out, stderr=err) self.assertEqual(out.getvalue(), 'System check identified no issues (1 silenced).\n') self.assertEqual(err.getvalue(), '')
def test_forward_reference_fk(self): management.call_command('loaddata', 'forward_reference_fk.json', verbosity=0) self.assertEqual(NaturalKeyThing.objects.count(), 2) t1, t2 = NaturalKeyThing.objects.all() self.assertEqual(t1.other_thing, t2) self.assertEqual(t2.other_thing, t1)
def test_loaddata_not_existent_fixture_file(self): stdout_output = StringIO() with self.assertRaisesMessage( CommandError, "No fixture named 'this_fixture_doesnt_exist' found."): management.call_command('loaddata', 'this_fixture_doesnt_exist', stdout=stdout_output)
def test_db_loading(self): # Load db fixtures 1 and 2. These will load using the 'default' database identifier implicitly management.call_command('loaddata', 'db_fixture_1', verbosity=0) management.call_command('loaddata', 'db_fixture_2', verbosity=0) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Who needs more than one database?>', '<Article: Who needs to use compressed data?>', ])
def test_command_option(self): with self.assertLogs('test', 'INFO') as cm: call_command( 'shell', command=('import djmodels; from logging import getLogger; ' 'getLogger("test").info(djmodels.__version__)'), ) self.assertEqual(cm.records[0].getMessage(), __version__)
def test_add_location_gettext_version_check(self): """ CommandError is raised when using makemessages --add-location with gettext < 0.19. """ msg = "The --add-location option requires gettext 0.19 or later. You have 0.18.99." with self.assertRaisesMessage(CommandError, msg): management.call_command('makemessages', locale=[LOCALE], verbosity=0, add_location='full')
def test_given_app(self): call_command('check', 'auth', 'admin') auth_config = apps.get_app_config('auth') admin_config = apps.get_app_config('admin') self.assertEqual(simple_system_check.kwargs, {'app_configs': [auth_config, admin_config]}) self.assertEqual(tagged_system_check.kwargs, {'app_configs': [auth_config, admin_config]})
def test_add_location_file(self): """makemessages --add-location=file""" management.call_command('makemessages', locale=[LOCALE], verbosity=0, add_location='file') self.assertTrue(os.path.exists(self.PO_FILE)) # Comment with source file relative path is present. self.assertLocationCommentPresent(self.PO_FILE, None, 'templates', 'test.html') # But it should not contain the line number. self.assertLocationCommentNotPresent(self.PO_FILE, 'Translatable literal #6b', 'templates', 'test.html')
def test_override_plural_forms(self): """Ticket #20311.""" management.call_command('makemessages', locale=['es'], extensions=['djtpl'], verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE_ES)) with open(self.PO_FILE_ES, 'r', encoding='utf-8') as fp: po_contents = fp.read() found = re.findall(r'^(?P<value>"Plural-Forms.+?\\n")\s*$', po_contents, re.MULTILINE | re.DOTALL) self.assertEqual(1, len(found))
def test_managed_models(self): """By default the command generates models with `Meta.managed = False` (#14305)""" out = StringIO() call_command('inspectdb', 'inspectdb_columntypes', stdout=out) output = out.getvalue() self.longMessage = False self.assertIn(" managed = False", output, msg='inspectdb should generate unmanaged models.')
def test_dumpdata_with_file_output(self): management.call_command('loaddata', 'fixture1.json', verbosity=0) self._dumpdata_assert( ['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": ' '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place ' 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": ' '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]', filename='dumpdata.json')
def test_table_exists(self): with extend_sys_path(os.path.dirname(os.path.abspath(__file__))): with self.modify_settings( INSTALLED_APPS={'append': ['app1', 'app2']}): call_command('migrate', verbosity=0, run_syncdb=True) from app1.models import ProxyModel from app2.models import NiceModel self.assertEqual(NiceModel.objects.all().count(), 0) self.assertEqual(ProxyModel.objects.all().count(), 0)
def test_loading_with_exclude_app(self): Site.objects.all().delete() management.call_command('loaddata', 'fixture1', exclude=['fixtures'], verbosity=0) self.assertFalse(Article.objects.exists()) self.assertFalse(Category.objects.exists()) self.assertQuerysetEqual(Site.objects.all(), ['<Site: example.com>'])
def test_forward_reference_m2m(self): management.call_command('loaddata', 'forward_reference_m2m.json', verbosity=0) self.assertEqual(NaturalKeyThing.objects.count(), 3) t1 = NaturalKeyThing.objects.get_by_natural_key('t1') self.assertQuerysetEqual( t1.other_things.order_by('key'), ['<NaturalKeyThing: t2>', '<NaturalKeyThing: t3>'])
def _run_makemessages(self, **options): os.chdir(self.test_dir) out = StringIO() management.call_command('makemessages', locale=[LOCALE], verbosity=2, stdout=out, **options) output = out.getvalue() self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE, 'r') as fp: po_contents = fp.read() return output, po_contents
def test_extraction_error(self): msg = ( 'Translation blocks must not include other block tags: blocktrans ' '(file %s, line 3)' % os.path.join('templates', 'template_with_error.tpl') ) with self.assertRaisesMessage(SyntaxError, msg): management.call_command('makemessages', locale=[LOCALE], extensions=['tpl'], verbosity=0) # The temporary file was cleaned up self.assertFalse(os.path.exists('./templates/template_with_error.tpl.py'))