Example #1
0
 def test_extraction_warning(self):
     os.chdir(self.test_dir)
     shutil.copyfile('./code.sample', './code_sample.py')
     stdout = StringIO()
     management.call_command('makemessages', locale=LOCALE, stdout=stdout)
     os.remove('./code_sample.py')
     self.assertIn("code_sample.py:4", stdout.getvalue())
Example #2
0
 def writeString(self, encoding):
     """
     Returns the feed in the given encoding as a string.
     """
     s = StringIO()
     self.write(s, encoding)
     return s.getvalue()
Example #3
0
    def test_nk_on_serialize(self):
        """
        Check that natural key requirements are taken into account
        when serializing models
        """
        management.call_command(
            'loaddata',
            'forward_ref_lookup.json',
            verbosity=0,
            commit=False
            )

        stdout = StringIO()
        management.call_command(
            'dumpdata',
            'fixtures_regress.book',
            'fixtures_regress.person',
            'fixtures_regress.store',
            verbosity=0,
            format='json',
            use_natural_keys=True,
            stdout=stdout,
        )
        self.assertEqual(
            stdout.getvalue(),
            """[{"pk": 2, "model": "fixtures_regress.store", "fields": {"main": null, "name": "Amazon"}}, {"pk": 3, "model": "fixtures_regress.store", "fields": {"main": null, "name": "Borders"}}, {"pk": 4, "model": "fixtures_regress.person", "fields": {"name": "Neal Stephenson"}}, {"pk": 1, "model": "fixtures_regress.book", "fields": {"stores": [["Amazon"], ["Borders"]], "name": "Cryptonomicon", "author": ["Neal Stephenson"]}}]"""
        )
Example #4
0
    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.assertEqual(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.assertEqual(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)
Example #5
0
class ChangepasswordManagementCommandTestCase(TestCase):

    def setUp(self):
        self.user = models.User.objects.create_user(username='******', password='******')
        self.stdout = StringIO()
        self.stderr = StringIO()

    def tearDown(self):
        self.stdout.close()
        self.stderr.close()

    def test_that_changepassword_command_changes_joes_password(self):
        " Executing the changepassword management command should change joe's password "
        self.assertTrue(self.user.check_password('qwerty'))
        command = changepassword.Command()
        command._get_pass = lambda *args: 'not qwerty'

        command.execute("joe", stdout=self.stdout)
        command_output = self.stdout.getvalue().strip()

        self.assertEqual(command_output, "Changing password for user 'joe'\nPassword changed successfully for user 'joe'")
        self.assertTrue(models.User.objects.get(username="******").check_password("not qwerty"))

    def test_that_max_tries_exits_1(self):
        """
        A CommandError should be thrown by handle() if the user enters in
        mismatched passwords three times.
        """
        command = changepassword.Command()
        command._get_pass = lambda *args: args or 'foo'

        with self.assertRaises(CommandError):
            command.execute("joe", stdout=self.stdout, stderr=self.stderr)
Example #6
0
 def test_console_stream_kwarg(self):
     """
     Test that the console backend can be pointed at an arbitrary stream.
     """
     s = StringIO()
     connection = mail.get_connection('djangocg.core.mail.backends.console.EmailBackend', stream=s)
     send_mail('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], connection=connection)
     self.assertTrue(s.getvalue().startswith('Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]\nDate: '))
Example #7
0
 def test_loaddata_not_existant_fixture_file(self):
     stdout_output = StringIO()
     management.call_command(
         'loaddata',
         'this_fixture_doesnt_exist',
         verbosity=2,
         commit=False,
         stdout=stdout_output,
     )
     self.assertTrue("No xml fixture 'this_fixture_doesnt_exist' in" in
         stdout_output.getvalue())
Example #8
0
 def test_ignore_option(self):
     os.chdir(self.test_dir)
     pattern1 = os.path.join('ignore_dir', '*')
     stdout = StringIO()
     management.call_command('makemessages', locale=LOCALE, verbosity=2,
         ignore_patterns=[pattern1], stdout=stdout)
     data = stdout.getvalue()
     self.assertTrue("ignoring directory ignore_dir" in data)
     self.assertTrue(os.path.exists(self.PO_FILE))
     with open(self.PO_FILE, 'r') as fp:
         po_contents = fp.read()
         self.assertMsgId('This literal should be included.', po_contents)
         self.assertNotMsgId('This should be ignored.', po_contents)
Example #9
0
    def test_dumpdata_uses_default_manager(self):
        """
        Regression for #11286
        Ensure that dumpdata honors the default manager
        Dump the current contents of the database as a JSON fixture
        """
        management.call_command(
            'loaddata',
            'animal.xml',
            verbosity=0,
            commit=False,
        )
        management.call_command(
            'loaddata',
            'sequence.json',
            verbosity=0,
            commit=False,
        )
        animal = Animal(
            name='Platypus',
            latin_name='Ornithorhynchus anatinus',
            count=2,
            weight=2.2
        )
        animal.save()

        stdout = StringIO()
        management.call_command(
            'dumpdata',
            'fixtures_regress.animal',
            format='json',
            stdout=stdout
        )

        # Output order isn't guaranteed, so check for parts
        data = stdout.getvalue()

        # Get rid of artifacts like '000000002' to eliminate the differences
        # between different Python versions.
        data = re.sub('0{6,}\d', '', data)

        lion_json = '{"pk": 1, "model": "fixtures_regress.animal", "fields": {"count": 3, "weight": 1.2, "name": "Lion", "latin_name": "Panthera leo"}}'
        emu_json = '{"pk": 10, "model": "fixtures_regress.animal", "fields": {"count": 42, "weight": 1.2, "name": "Emu", "latin_name": "Dromaius novaehollandiae"}}'
        platypus_json = '{"pk": %d, "model": "fixtures_regress.animal", "fields": {"count": 2, "weight": 2.2, "name": "Platypus", "latin_name": "Ornithorhynchus anatinus"}}'
        platypus_json = platypus_json % animal.pk

        self.assertEqual(len(data), len('[%s]' % ', '.join([lion_json, emu_json, platypus_json])))
        self.assertTrue(lion_json in data)
        self.assertTrue(emu_json in data)
        self.assertTrue(platypus_json in data)
Example #10
0
    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 djangocg.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, num_errors != 1 and 's' or ''))
Example #11
0
 def _dumpdata_assert(
     self, args, output, format="json", natural_keys=False, use_base_manager=False, exclude_list=[]
 ):
     new_io = StringIO()
     management.call_command(
         "dumpdata",
         *args,
         **{
             "format": format,
             "stdout": new_io,
             "stderr": new_io,
             "use_natural_keys": natural_keys,
             "use_base_manager": use_base_manager,
             "exclude": exclude_list,
         }
     )
     command_output = new_io.getvalue().strip()
     self.assertEqual(command_output, output)
Example #12
0
    def test_createsuperuser_management_command(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="******",
            email="*****@*****.**",
            stdout=new_io
        )
        command_output = new_io.getvalue().strip()
        self.assertEqual(command_output, 'Superuser created successfully.')
        u = User.objects.get(username="******")
        self.assertEqual(u.email, '*****@*****.**')

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

        # We can supress output on the management command
        new_io = StringIO()
        call_command("createsuperuser",
            interactive=False,
            username="******",
            email="*****@*****.**",
            verbosity=0,
            stdout=new_io
        )
        command_output = new_io.getvalue().strip()
        self.assertEqual(command_output, '')
        u = User.objects.get(username="******")
        self.assertEqual(u.email, '*****@*****.**')
        self.assertFalse(u.has_usable_password())


        new_io = StringIO()
        call_command("createsuperuser",
            interactive=False,
            username="******",
            email="*****@*****.**",
            stdout=new_io
        )
        u = User.objects.get(username="******")
        self.assertEqual(u.email, '*****@*****.**')
        self.assertFalse(u.has_usable_password())
Example #13
0
 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.assertEqual(
         stdout.getvalue(),
         """[{"pk": %d, "model": "fixtures_regress.widget", "fields": {"name": "grommet"}}]"""
         % widget.pk
         )
Example #14
0
    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()
Example #15
0
class InvalidModelTestCase(unittest.TestCase):
    """Import an appliation with invalid models and test the exceptions."""

    def setUp(self):
        # Make sure sys.stdout is not a tty so that we get errors without
        # coloring attached (makes matching the results easier). We restore
        # sys.stderr afterwards.
        self.old_stdout = sys.stdout
        self.stdout = StringIO()
        sys.stdout = self.stdout

        # This test adds dummy applications to the app cache. These
        # need to be removed in order to prevent bad interactions
        # with the flush operation in other tests.
        self.old_app_models = copy.deepcopy(cache.app_models)
        self.old_app_store = copy.deepcopy(cache.app_store)

    def tearDown(self):
        cache.app_models = self.old_app_models
        cache.app_store = self.old_app_store
        cache._get_models_cache = {}
        sys.stdout = self.old_stdout

    def test_invalid_models(self):

        try:
            module = load_app("modeltests.invalid_models.invalid_models")
        except Exception:
            self.fail("Unable to load invalid model module")

        count = get_validation_errors(self.stdout, module)
        self.stdout.seek(0)
        error_log = self.stdout.read()
        actual = error_log.split("\n")
        expected = module.model_errors.split("\n")

        unexpected = [err for err in actual if err not in expected]
        missing = [err for err in expected if err not in actual]
        self.assertFalse(unexpected, "Unexpected Errors: " + "\n".join(unexpected))
        self.assertFalse(missing, "Missing Errors: " + "\n".join(missing))
Example #16
0
    def setUp(self):
        # Make sure sys.stdout is not a tty so that we get errors without
        # coloring attached (makes matching the results easier). We restore
        # sys.stderr afterwards.
        self.old_stdout = sys.stdout
        self.stdout = StringIO()
        sys.stdout = self.stdout

        # This test adds dummy applications to the app cache. These
        # need to be removed in order to prevent bad interactions
        # with the flush operation in other tests.
        self.old_app_models = copy.deepcopy(cache.app_models)
        self.old_app_store = copy.deepcopy(cache.app_store)
Example #17
0
class MultiDBChangepasswordManagementCommandTestCase(TestCase):
    multi_db = True

    def setUp(self):
        self.user = models.User.objects.db_manager('other').create_user(username='******', password='******')
        self.stdout = StringIO()

    def tearDown(self):
        self.stdout.close()

    def test_that_changepassword_command_with_database_option_uses_given_db(self):
        """
        Executing the changepassword management command with a database option
        should operate on the specified DB
        """
        self.assertTrue(self.user.check_password('qwerty'))
        command = changepassword.Command()
        command._get_pass = lambda *args: 'not qwerty'

        command.execute("joe", database='other', stdout=self.stdout)
        command_output = self.stdout.getvalue().strip()

        self.assertEqual(command_output, "Changing password for user 'joe'\nPassword changed successfully for user 'joe'")
        self.assertTrue(models.User.objects.using('other').get(username="******").check_password("not qwerty"))
Example #18
0
 def setUp(self):
     self.user = models.User.objects.db_manager('other').create_user(username='******', password='******')
     self.stdout = StringIO()
Example #19
0
 def setUp(self):
     self.old_DJANGO_AUTO_COMPLETE = os.environ.get('DJANGO_AUTO_COMPLETE')
     os.environ['DJANGO_AUTO_COMPLETE'] = '1'
     self.output = StringIO()
     self.old_stdout = sys.stdout
     sys.stdout = self.output
Example #20
0
 def test_sequence_creation(self):
     "Check that sequences on an m2m_through are created for the through model, not a phantom auto-generated m2m table. Refs #11107"
     out = StringIO()
     management.call_command("dumpdata", "m2m_through_regress", format="json", stdout=out)
     self.assertEqual(out.getvalue().strip(), """[{"pk": 1, "model": "m2m_through_regress.usermembership", "fields": {"price": 100, "group": 1, "user": 1}}, {"pk": 1, "model": "m2m_through_regress.person", "fields": {"name": "Guido"}}, {"pk": 1, "model": "m2m_through_regress.group", "fields": {"name": "Python Core Group"}}]""")
Example #21
0
 def setUp(self):
     self.user = models.User.objects.create_user(username='******', password='******')
     self.stdout = StringIO()
     self.stderr = StringIO()
Example #22
0
def templatize(src, origin=None):
    """
    Turns a Django template into something that is understood by xgettext. It
    does so by translating the Django translation tags into standard gettext
    function invocations.
    """
    from djangocg.conf import settings
    from djangocg.template import Lexer, TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK, TOKEN_COMMENT, TRANSLATOR_COMMENT_MARK

    src = force_text(src, settings.FILE_CHARSET)
    out = StringIO()
    message_context = None
    intrans = False
    inplural = False
    singular = []
    plural = []
    incomment = False
    comment = []
    for t in Lexer(src, origin).tokenize():
        if incomment:
            if t.token_type == TOKEN_BLOCK and t.contents == "endcomment":
                content = "".join(comment)
                translators_comment_start = None
                for lineno, line in enumerate(content.splitlines(True)):
                    if line.lstrip().startswith(TRANSLATOR_COMMENT_MARK):
                        translators_comment_start = lineno
                for lineno, line in enumerate(content.splitlines(True)):
                    if translators_comment_start is not None and lineno >= translators_comment_start:
                        out.write(" # %s" % line)
                    else:
                        out.write(" #\n")
                incomment = False
                comment = []
            else:
                comment.append(t.contents)
        elif intrans:
            if t.token_type == TOKEN_BLOCK:
                endbmatch = endblock_re.match(t.contents)
                pluralmatch = plural_re.match(t.contents)
                if endbmatch:
                    if inplural:
                        if message_context:
                            out.write(
                                " npgettext(%r, %r, %r,count) " % (message_context, "".join(singular), "".join(plural))
                            )
                        else:
                            out.write(" ngettext(%r, %r, count) " % ("".join(singular), "".join(plural)))
                        for part in singular:
                            out.write(blankout(part, "S"))
                        for part in plural:
                            out.write(blankout(part, "P"))
                    else:
                        if message_context:
                            out.write(" pgettext(%r, %r) " % (message_context, "".join(singular)))
                        else:
                            out.write(" gettext(%r) " % "".join(singular))
                        for part in singular:
                            out.write(blankout(part, "S"))
                    message_context = None
                    intrans = False
                    inplural = False
                    singular = []
                    plural = []
                elif pluralmatch:
                    inplural = True
                else:
                    filemsg = ""
                    if origin:
                        filemsg = "file %s, " % origin
                    raise SyntaxError(
                        "Translation blocks must not include other block tags: %s (%sline %d)"
                        % (t.contents, filemsg, t.lineno)
                    )
            elif t.token_type == TOKEN_VAR:
                if inplural:
                    plural.append("%%(%s)s" % t.contents)
                else:
                    singular.append("%%(%s)s" % t.contents)
            elif t.token_type == TOKEN_TEXT:
                contents = one_percent_re.sub("%%", t.contents)
                if inplural:
                    plural.append(contents)
                else:
                    singular.append(contents)
        else:
            if t.token_type == TOKEN_BLOCK:
                imatch = inline_re.match(t.contents)
                bmatch = block_re.match(t.contents)
                cmatches = constant_re.findall(t.contents)
                if imatch:
                    g = imatch.group(1)
                    if g[0] == '"':
                        g = g.strip('"')
                    elif g[0] == "'":
                        g = g.strip("'")
                    g = one_percent_re.sub("%%", g)
                    if imatch.group(2):
                        # A context is provided
                        context_match = context_re.match(imatch.group(2))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                        out.write(" pgettext(%r, %r) " % (message_context, g))
                        message_context = None
                    else:
                        out.write(" gettext(%r) " % g)
                elif bmatch:
                    for fmatch in constant_re.findall(t.contents):
                        out.write(" _(%s) " % fmatch)
                    if bmatch.group(1):
                        # A context is provided
                        context_match = context_re.match(bmatch.group(1))
                        message_context = context_match.group(1)
                        if message_context[0] == '"':
                            message_context = message_context.strip('"')
                        elif message_context[0] == "'":
                            message_context = message_context.strip("'")
                    intrans = True
                    inplural = False
                    singular = []
                    plural = []
                elif cmatches:
                    for cmatch in cmatches:
                        out.write(" _(%s) " % cmatch)
                elif t.contents == "comment":
                    incomment = True
                else:
                    out.write(blankout(t.contents, "B"))
            elif t.token_type == TOKEN_VAR:
                parts = t.contents.split("|")
                cmatch = constant_re.match(parts[0])
                if cmatch:
                    out.write(" _(%s) " % cmatch.group(1))
                for p in parts[1:]:
                    if p.find(":_(") >= 0:
                        out.write(" %s " % p.split(":", 1)[1])
                    else:
                        out.write(blankout(p, "F"))
            elif t.token_type == TOKEN_COMMENT:
                out.write(" # %s" % t.contents)
            else:
                out.write(blankout(t.contents, "X"))
    return force_str(out.getvalue())
Example #23
0
 def test_command(self):
     out = StringIO()
     management.call_command('dance', stdout=out)
     self.assertEqual(out.getvalue(),
         "I don't feel like dancing Rock'n'Roll.\n")
Example #24
0
class BashCompletionTests(unittest.TestCase):
    """
    Testing the Python level bash completion code.
    This requires setting up the environment as if we got passed data
    from bash.
    """

    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

    def tearDown(self):
        sys.stdout = self.old_stdout
        if self.old_DJANGO_AUTO_COMPLETE:
            os.environ['DJANGO_AUTO_COMPLETE'] = self.old_DJANGO_AUTO_COMPLETE
        else:
            del os.environ['DJANGO_AUTO_COMPLETE']

    def _user_input(self, input_str):
        os.environ['COMP_WORDS'] = input_str
        os.environ['COMP_CWORD'] = str(len(input_str.split()) - 1)
        sys.argv = input_str.split(' ')

    def _run_autocomplete(self):
        util = ManagementUtility(argv=sys.argv)
        try:
            util.autocomplete()
        except SystemExit:
            pass
        return self.output.getvalue().strip().split('\n')

    def test_django_admin_py(self):
        "django_admin.py will autocomplete option flags"
        self._user_input('django-admin.py sqlall --v')
        output = self._run_autocomplete()
        self.assertEqual(output, ['--verbosity='])

    def test_manage_py(self):
        "manage.py will autocomplete option flags"
        self._user_input('manage.py sqlall --v')
        output = self._run_autocomplete()
        self.assertEqual(output, ['--verbosity='])

    def test_custom_command(self):
        "A custom command can autocomplete option flags"
        self._user_input('django-admin.py test_command --l')
        output = self._run_autocomplete()
        self.assertEqual(output, ['--list'])

    def test_subcommands(self):
        "Subcommands can be autocompleted"
        self._user_input('django-admin.py sql')
        output = self._run_autocomplete()
        self.assertEqual(output, ['sql sqlall sqlclear sqlcustom sqlflush sqlindexes sqlinitialdata sqlsequencereset'])

    def test_help(self):
        "No errors, just an empty list if there are no autocomplete options"
        self._user_input('django-admin.py help --')
        output = self._run_autocomplete()
        self.assertEqual(output, [''])

    def test_runfcgi(self):
        "Command arguments will be autocompleted"
        self._user_input('django-admin.py runfcgi h')
        output = self._run_autocomplete()
        self.assertEqual(output, ['host='])

    def test_app_completion(self):
        "Application names will be autocompleted for an AppCommand"
        self._user_input('django-admin.py sqlall a')
        output = self._run_autocomplete()
        app_labels = [name.split('.')[-1] for name in settings.INSTALLED_APPS]
        self.assertEqual(output, sorted(label for label in app_labels if label.startswith('a')))
Example #25
0
 def _dumpdata_assert(self, args, output, format="json"):
     new_io = StringIO()
     management.call_command("dumpdata", *args, **{"format": format, "stdout": new_io})
     command_output = new_io.getvalue().strip()
     self.assertEqual(command_output, output)
Example #26
0
 def test_command_style(self):
     out = StringIO()
     management.call_command('dance', style='Jive', stdout=out)
     self.assertEqual(out.getvalue(),
         "I don't feel like dancing Jive.\n")