django.utils.six.moves.StringIO

Here are the examples of the python api django.utils.six.moves.StringIO taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

48 Examples 7

Example 1

Project: reviewboard
Source File: test_bitbucket.py
View license
    def test_authorize_with_bad_credentials(self):
        """Testing Bitbucket authorization with bad credentials"""
        def _http_get(service, url, *args, **kwargs):
            raise HTTPError(url, 401, '', {}, StringIO(''))

        account = self._get_hosting_account()
        service = account.service

        self.spy_on(service.client.http_get, call_fake=_http_get)

        self.assertFalse(service.is_authorized())

        self.assertRaisesMessage(
            AuthorizationError,
            'Invalid Bitbucket username or password',
            lambda: service.authorize('myuser', 'abc123', None))

        self.assertNotIn('password', account.data)
        self.assertFalse(service.is_authorized())

Example 2

View license
    def _run_command(self, **options):
        """Run the profile command with the given options on the diffsettings command and capture the output"""
        output = StringIO()
        options = options.copy()
        options['backend'] = 'cProfile'
        options['testing'] = True
        for option in ('fraction', 'max_calls', 'path', 'pattern', 'sort'):
            if option not in options:
                options[option] = None
        call_command('profile', 'diffsettings', stdout=output, **options)
        text = output.getvalue()
        assert 'INSTALLED_APPS' in text
        return text

Example 3

View license
    def test_parse(self):
        """ Make sure the `QueryDict` works OK """
        parser = FormParser()

        stream = StringIO(self.string)
        data = parser.parse(stream)

        self.assertEqual(Form(data).is_valid(), True)

Example 4

Project: cadasta-platform
Source File: renderers.py
View license
    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Renders *obj* into serialized XML.
        """
        # if data is None:
        #     return ''
        # elif isinstance(data, six.string_types):
        #     return data

        stream = StringIO()

        xml = SimplerXMLGenerator(stream, self.charset)
        xml.startDocument()
        xml.startElement(self.root_node, {'xmlns': self.xmlns})

        self._to_xml(xml, data)
        xml.endElement(self.root_node)
        xml.endDocument()
        return stream.getvalue()

Example 5

Project: django-mysql
Source File: test_dbparams.py
View license
    @mock.patch(command_connections, full_db)
    def test_mysql_full(self):
        out = StringIO()
        call_command('dbparams', stdout=out, skip_checks=True)
        output = out.getvalue()
        assert (
            output ==
            "--defaults-file=/tmp/defaults.cnf --user=ausername "
            "--password=apassword --host=ahost.example.com --port=12345 "
            "--ssl-ca=/tmp/mysql.cert mydatabase"
        )

Example 6

Project: django-mysql
Source File: test_dbparams.py
View license
    @mock.patch(command_connections, socket_db)
    def test_mysql_socket(self):
        out = StringIO()
        call_command('dbparams', stdout=out, skip_checks=True)
        output = out.getvalue()
        assert output == "--socket=/etc/mydb.sock"

Example 7

Project: django-mysql
Source File: test_dbparams.py
View license
    @mock.patch(command_connections, full_db)
    def test_dsn_full(self):
        out = StringIO()
        err = StringIO()
        call_command('dbparams', 'default', dsn=True,
                     stdout=out, stderr=err, skip_checks=True)
        output = out.getvalue()
        assert (
            output ==
            "F=/tmp/defaults.cnf,u=ausername,p=apassword,h=ahost.example.com,"
            "P=12345,D=mydatabase"
        )

        errors = err.getvalue()
        assert "SSL params can't be" in errors

Example 8

Project: django-mysql
Source File: test_dbparams.py
View license
    @mock.patch(command_connections, socket_db)
    def test_dsn_socket(self):
        out = StringIO()
        err = StringIO()
        call_command('dbparams', dsn=True,
                     stdout=out, stderr=err, skip_checks=True)

        output = out.getvalue()
        assert output == 'S=/etc/mydb.sock'

        errors = err.getvalue()
        assert errors == ""

Example 9

View license
def run_it(*args, **kwargs):
    run_args = ['fix_datetime_columns']
    run_args.extend(args)

    out = StringIO()
    run_kwargs = {'stdout': out, 'skip_checks': True}
    run_kwargs.update(kwargs)

    call_command(*run_args, **run_kwargs)

    return out.getvalue()

Example 10

Project: django-mysql
Source File: test_cache.py
View license
    def test_mysql_cache_migration_alias(self):
        out = StringIO()
        call_command('mysql_cache_migration', 'default', stdout=out)
        output = out.getvalue()

        num_run_sqls = (len(output.split('RunSQL')) - 1)
        assert num_run_sqls == 1

Example 11

Project: django-mysql
Source File: test_cache.py
View license
    @override_cache_settings(
        BACKEND='django.core.cache.backends.dummy.DummyCache'
    )
    def test_mysql_cache_migration_no_mysql_caches(self):
        err = StringIO()
        call_command('mysql_cache_migration', stderr=err)
        assert "No MySQLCache instances in CACHES" in err.getvalue()

Example 12

Project: django-mysql
Source File: test_cache.py
View license
    def test_cull_mysql_caches_named_cache(self):
        cache.set('key', 'value', 0.1)
        time.sleep(0.2)
        assert self.table_count() == 1

        out = StringIO()
        call_command('cull_mysql_caches', 'default', verbosity=1, stdout=out)
        output = out.getvalue()
        assert (
            output.strip() ==
            "Deleting from cache 'default'... 1 entries deleted."
        )
        assert self.table_count() == 0

Example 13

Project: django-cms
Source File: test_docs.py
View license
    @skipIf(has_no_internet(), "No internet")
    def test_html(self):
        status = StringIO()
        with TemporaryDirectory() as OUT_DIR:
            app = Sphinx(
                srcdir=DOCS_DIR,
                confdir=DOCS_DIR,
                outdir=OUT_DIR,
                doctreedir=OUT_DIR,
                buildername="html",
                warningiserror=True,
                status=status,
            )
            try:
                app.build()
            except:
                print(status.getvalue())
                raise

Example 14

Project: django-cms
Source File: test_management.py
View license
    @override_settings(INSTALLED_APPS=TEST_INSTALLED_APPS)
    def test_list_apphooks(self):
        with apphooks(SampleApp):
            out = StringIO()
            create_page('Hello Title', "nav_playground.html", "en", apphook=APPHOOK)
            self.assertEqual(Page.objects.filter(application_urls=APPHOOK).count(), 1)
            management.call_command(
                "cms",
                "list",
                "apphooks",
                interactive=False,
                stdout=out,
            )
            self.assertEqual(out.getvalue(), "SampleApp (draft)\n")

Example 15

Project: django-cms
Source File: test_management.py
View license
    def test_uninstall_apphooks_without_apphook(self):
        with apphooks():
            out = StringIO()
            management.call_command(
                "cms",
                "uninstall",
                "apphooks",
                APPHOOK,
                interactive=False,
                stdout=out,
            )
            self.assertEqual(out.getvalue(), "no 'SampleApp' apphooks found\n")

Example 16

Project: django-cms
Source File: test_management.py
View license
    def test_fix_tree(self):
        create_page("home", "nav_playground.html", "en")
        page1 = create_page("page", "nav_playground.html", "en")
        page1.depth = 3
        page1.numchild = 4
        page1.path = "00100010"
        page1.save()
        out = StringIO()
        management.call_command('cms', 'fix-tree', interactive=False, stdout=out)
        self.assertEqual(out.getvalue(), 'fixing page tree\nfixing plugin tree\nall done\n')
        page1 = page1.reload()
        self.assertEqual(page1.path, "0002")
        self.assertEqual(page1.depth, 1)
        self.assertEqual(page1.numchild, 0)

Example 17

Project: django-cms
Source File: test_management.py
View license
    @override_settings(INSTALLED_APPS=TEST_INSTALLED_APPS)
    def test_uninstall_apphooks_with_apphook(self):
        with apphooks(SampleApp):
            out = StringIO()
            create_page('Hello Title', "nav_playground.html", "en", apphook=APPHOOK)
            self.assertEqual(Page.objects.filter(application_urls=APPHOOK).count(), 1)
            management.call_command(
                "cms",
                "uninstall",
                "apphooks",
                APPHOOK,
                interactive=False,
                stdout=out,
            )
            self.assertEqual(out.getvalue(), "1 'SampleApp' apphooks uninstalled\n")
            self.assertEqual(Page.objects.filter(application_urls=APPHOOK).count(), 0)

Example 18

Project: django-cms
Source File: test_management.py
View license
    @override_settings(INSTALLED_APPS=TEST_INSTALLED_APPS)
    def test_uninstall_plugins_with_plugin(self):
        out = StringIO()
        placeholder = Placeholder.objects.create(slot="test")
        add_plugin(placeholder, TextPlugin, "en", body="en body")
        self.assertEqual(CMSPlugin.objects.filter(plugin_type=PLUGIN).count(), 1)
        management.call_command('cms', 'uninstall', 'plugins', PLUGIN, interactive=False, stdout=out)
        self.assertEqual(out.getvalue(), "1 'TextPlugin' plugins uninstalled\n")
        self.assertEqual(CMSPlugin.objects.filter(plugin_type=PLUGIN).count(), 0)

Example 19

Project: django-cms
Source File: test_management.py
View license
    def test_copy_from_non_existing_lang(self):
        """
        If an existing title in the target language has plugins in a placeholder
        and the command is called with *force-copy*, the plugins are copied on
        top of the existing one
        """
        site = 1
        out = StringIO()
        management.call_command(
            'cms', 'copy', 'lang', '--from-lang=de', '--to-lang=fr', verbosity=3,
            interactive=False, stdout=out
        )
        text = out.getvalue()
        page_count = Page.objects.on_site(site).drafts().count() + 1
        for idx in range(1, page_count):
            self.assertTrue("Skipping page page%d, language de not defined" % idx in text)

Example 20

Project: django-cms
Source File: test_management.py
View license
    def test_copy_bad_languages(self):
        out = StringIO()
        with self.assertRaises(CommandError) as command_error:
            management.call_command(
                'cms', 'copy', 'lang', '--from-lang=it', '--to-lang=fr', interactive=False,
                stdout=out
            )

        self.assertEqual(str(command_error.exception), 'Both languages have to be present in settings.LANGUAGES and settings.CMS_LANGUAGES')

Example 21

Project: django-pyscss
Source File: compiler.py
View license
    def compile_string(self, string, filename=None):
        compilation = self.make_compilation()
        if filename is not None:
            f = StringIO(string)
            filename = PurePath(filename)
            source = SourceFile.from_file(f, origin=filename.parent, relpath=PurePath(filename.name))
        else:
            source = SourceFile.from_string(string)
        compilation.add_source(source)
        return self.call_and_catch_errors(compilation.run)

Example 22

View license
    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Renders `data` into serialized XML.
        """
        if data is None:
            return ''

        stream = StringIO()

        xml = SimplerXMLGenerator(stream, self.charset)
        xml.startDocument()
        xml.startElement(self.root_tag_name, {})

        self._to_xml(xml, data)

        xml.endElement(self.root_tag_name)
        xml.endDocument()
        return stream.getvalue()

Example 23

View license
    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Renders `data` into serialized XML.
        """
        if data is None:
            return ''

        stream = StringIO()

        xml = SimplerXMLGenerator(stream, self.charset)
        xml.startDocument()
        xml.startElement(self.root_tag_name, {})

        self._to_xml(xml, data)

        xml.endElement(self.root_tag_name)
        xml.endDocument()
        return stream.getvalue()

Example 24

View license
    @unittest.skipUnless(etree, 'defusedxml not installed')
    def test_render_and_parse_complex_data(self):
        """
        Test XML rendering.
        """
        renderer = XMLRenderer()
        content = StringIO(renderer.render(self._complex_data, 'application/xml'))

        parser = XMLParser()
        complex_data_out = parser.parse(content)
        error_msg = "complex data differs!IN:\n %s \n\n OUT:\n %s" % (repr(self._complex_data), repr(complex_data_out))
        self.assertEqual(self._complex_data, complex_data_out, error_msg)

Example 25

View license
    @unittest.skipUnless(etree, 'defusedxml not installed')
    def test_render_and_parse_complex_data(self):
        """
        Test XML rendering.
        """
        renderer = XMLRenderer()
        content = StringIO(renderer.render(self._complex_data, 'application/xml'))

        parser = XMLParser()
        complex_data_out = parser.parse(content)
        error_msg = "complex data differs!IN:\n %s \n\n OUT:\n %s" % (repr(self._complex_data), repr(complex_data_out))
        self.assertEqual(self._complex_data, complex_data_out, error_msg)

Example 26

Project: reviewboard
Source File: test_codebasehq.py
View license
    def _test_get_file(self, tool_name, expect_git_blob_url=False,
                       file_exists=True):
        def _http_get(service, url, *args, **kwargs):
            if expect_git_blob_url:
                self.assertEqual(
                    url,
                    'https://api3.codebasehq.com/myproj/myrepo/blob/123')
            else:
                self.assertEqual(
                    url,
                    'https://api3.codebasehq.com/myproj/myrepo/blob/123/'
                    'myfile')

            if file_exists:
                return b'My data\n', {}
            else:
                raise HTTPError(url, 404, '', {}, StringIO())

        account = self._get_hosting_account()
        service = account.service
        repository = Repository(hosting_account=account,
                                tool=Tool.objects.get(name=tool_name))
        repository.extra_data = {
            'codebasehq_project_name': 'myproj',
            'codebasehq_repo_name': 'myrepo',
        }

        self._authorize(service)

        self.spy_on(service.client.http_get, call_fake=_http_get)

        if file_exists:
            result = service.get_file(repository, 'myfile', '123')
            self.assertEqual(result, 'My data\n')
        else:
            with self.assertRaises(FileNotFoundError):
                service.get_file(repository, 'myfile', '123')

        self.assertTrue(service.client.http_get.called)

Example 27

Project: reviewboard
Source File: test_codebasehq.py
View license
    def _test_get_file_exists(self, tool_name, expect_git_blob_url=False,
                              file_exists=True):
        def _http_get(service, url, *args, **kwargs):
            if expect_git_blob_url:
                self.assertEqual(
                    url,
                    'https://api3.codebasehq.com/myproj/myrepo/blob/123')
            else:
                self.assertEqual(
                    url,
                    'https://api3.codebasehq.com/myproj/myrepo/blob/123/'
                    'myfile')

            if file_exists:
                return b'{}', {}
            else:
                raise HTTPError(url, 404, '', {}, StringIO())

        account = self._get_hosting_account()
        service = account.service
        repository = Repository(hosting_account=account,
                                tool=Tool.objects.get(name=tool_name))
        repository.extra_data = {
            'codebasehq_project_name': 'myproj',
            'codebasehq_repo_name': 'myrepo',
        }

        self._authorize(service)

        self.spy_on(service.client.http_get, call_fake=_http_get)

        result = service.get_file_exists(repository, 'myfile', '123')
        self.assertTrue(service.client.http_get.called)
        self.assertEqual(result, file_exists)

Example 28

Project: reviewboard
Source File: test_github.py
View license
    def test_get_remote_repository_invalid(self, **kwargs):
        """Testing GitHub.get_remote_repository with invalid repository ID"""
        def _http_get(service, url, *args, **kwargs):
            self.assertEqual(
                url,
                'https://api.github.com/repos/myuser/invalid'
                '?access_token=123')

            payload = {
                'message': 'Not Found',
            }

            raise HTTPError(url, 404, '', {}, StringIO(json.dumps(payload)))

        account = self._get_hosting_account()
        account.data['authorization'] = {
            'token': '123',
        }

        service = account.service
        self.spy_on(service.client.http_get, call_fake=_http_get)

        self.assertRaises(ObjectDoesNotExist,
                          service.get_remote_repository, 'myuser/invalid')

Example 29

Project: reviewboard
Source File: test_github.py
View license
    def _test_check_repository_error(self, http_status, payload,
                                     expected_error, **kwargs):
        def _http_get(service, url, *args, **kwargs):
            if http_status == 200:
                return payload, {}
            else:
                raise HTTPError(url, http_status, '', {}, StringIO(payload))

        account = self._get_hosting_account()
        service = account.service
        self.spy_on(service.client.http_get, call_fake=_http_get)
        account.data['authorization'] = {
            'token': '123',
        }

        try:
            service.check_repository(**kwargs)
            saw_exception = False
        except Exception as e:
            self.assertEqual(six.text_type(e), expected_error)
            saw_exception = True

        self.assertTrue(saw_exception)

Example 30

View license
def output_results(profiler, options, stdout):
    """Generate the profiler output in the desired format.  Implemented as a
    separate function so it can be run as an exit handler (because management
    commands often call exit() directly, bypassing the rest of the profile
    command's handle() method)."""
    profiler.create_stats()

    if not options['sort']:
        if not which('dot'):
            stdout.write('Could not find "dot" from Graphviz; please install Graphviz to enable call graph generation')
            return
        if not which('gprof2dot.py'):
            stdout.write('Could not find gprof2dot.py, which should have been installed by yet-another-django-profiler')
            return
        return_code, output = run_gprof2dot(profiler)
        if return_code:
            stdout.write('gprof2dot/dot exited with {}'.format(return_code))
            return
        path = options['path']
        with open(path, 'wb') as pdf_file:
            pdf_file.write(output)
            stdout.write('Wrote call graph to {}'.format(path))
    else:
        sort = options['sort']
        if sort == 'file':
            # Work around bug on Python versions >= 2.7.4
            sort = 'fil'
        out = StringIO()
        stats = pstats.Stats(profiler, stream=out)
        with mock.patch('pstats.func_strip_path') as mock_func_strip_path:
            mock_func_strip_path.side_effect = func_strip_path
            stats.strip_dirs()
        restrictions = []
        if options['pattern']:
            restrictions.append(options['pattern'])
        if options['fraction']:
            restrictions.append(float(options['fraction']))
        elif options['max_calls']:
            restrictions.append(int(options['max_calls']))
        elif not options['pattern']:
            restrictions.append(.2)
        stats.sort_stats(sort).print_stats(*restrictions)
        if options['path']:
            path = options['path']
            with open(path, 'w') as text_file:
                text_file.write(out.getvalue())
                stdout.write('Wrote profiling statistics to {}'.format(path))
        else:
            stdout.write(out.getvalue())

Example 31

View license
    def process_response(self, request, response):
        if self.profile_parameter is not None:
            if self.error:
                return text_response(response, self.error)
            self.profiler.create_stats()
            mode = self.profile_parameter
            if mode == 'file':
                # Work around bug on Python versions >= 2.7.4
                mode = 'fil'
            if not mode:
                if not which('dot'):
                    return text_response(response, _('Could not find "dot" from Graphviz; please install Graphviz to enable call graph generation'))
                if not which('gprof2dot.py'):
                    return text_response(response, _('Could not find gprof2dot.py, which should have been installed by yet-another-django-profiler'))
                return_code, output = run_gprof2dot(self.profiler)
                if return_code:
                    raise Exception(_('gprof2dot.py exited with {return_code}').format(return_code=return_code))
                set_content(response, output)
                response['Content-Type'] = 'application/pdf'
                return response
            elif mode == 'help':
                return text_response(response, ProfilerMiddleware.__doc__)
            else:
                out = StringIO()
                stats = pstats.Stats(self.profiler, stream=out)

                with mock.patch('pstats.func_strip_path') as mock_func_strip_path:
                    mock_func_strip_path.side_effect = func_strip_path
                    stats.strip_dirs()
                restrictions = []
                if self.pattern_parameter is not None:
                    restrictions.append(self.pattern_parameter)
                if self.fraction_parameter is not None:
                    restrictions.append(float(self.fraction_parameter))
                elif self.max_calls_parameter is not None:
                    restrictions.append(int(self.max_calls_parameter))
                elif self.pattern_parameter is None:
                    restrictions.append(.2)
                stats.sort_stats(mode).print_stats(*restrictions)
                return text_response(response, out.getvalue())
        return response

Example 32

Project: django-mysql
Source File: test_cache.py
View license
    def test_mysql_cache_migration_non_existent(self):
        out = StringIO()
        with pytest.raises(CommandError):
            call_command('mysql_cache_migration', 'nonexistent', stdout=out)

Example 33

Project: django-mysql
Source File: test_cache.py
View license
    def test_mysql_cache_migration(self):
        out = StringIO()
        call_command('mysql_cache_migration', stdout=out)
        output = out.getvalue()

        # Lint it
        errors = flake8_code(output)
        assert errors == [], (
            "Encountered {} errors whilst trying to lint the mysql cache "
            "migration.\nMigration:\n\n{}\n\nLint errors:\n\n{}"
            .format(len(errors), output, '\n'.join(errors))
        )

        # Dynamic import and check
        migration_mod = imp.new_module('0001_add_cache_tables')
        six.exec_(output, migration_mod.__dict__)
        assert hasattr(migration_mod, 'Migration')
        migration = migration_mod.Migration
        assert hasattr(migration, 'dependencies')
        assert hasattr(migration, 'operations')

        # Since they all have the same table name, there should only be one
        # operation
        assert len(migration.operations) == 1

        # Now run the migration forwards and backwards to check it works
        operation = migration.operations[0]
        assert not self.table_exists(self.table_name)

        state = ProjectState()
        new_state = state.clone()
        with connection.schema_editor() as editor:
            operation.database_forwards("testapp", editor,
                                        state, new_state)
        assert self.table_exists(self.table_name)

        new_state = state.clone()
        with connection.schema_editor() as editor:
            operation.database_backwards("testapp", editor,
                                         new_state, state)
        assert not self.table_exists(self.table_name)

Example 34

Project: django-cms
Source File: test_docs.py
View license
    @skipIf(has_no_internet(), "No internet")
    @skipIf(enchant is None, "Enchant not installed")
    @skipUnless(django.VERSION[:2] == (1, 8)
                and sys.version_info[:2] == (3, 4)
                and os.environ.get('DATABASE_URL') == 'sqlite://localhost/:memory:',
                'Skipping for simplicity')
    def test_spelling(self):
        status = StringIO()
        with TemporaryDirectory() as OUT_DIR:
            with tmp_list_append(sys.argv, 'spelling'):
                try:
                    app = Sphinx(
                        srcdir=DOCS_DIR,
                        confdir=DOCS_DIR,
                        outdir=OUT_DIR,
                        doctreedir=OUT_DIR,
                        buildername="spelling",
                        warningiserror=True,
                        status=status,
                        confoverrides={
                            'extensions': [
                                'djangocms',
                                'sphinx.ext.intersphinx',
                                'sphinxcontrib.spelling'
                            ]
                        }
                    )
                    app.build()
                    self.assertEqual(app.statuscode, 0, status.getvalue())
                except SphinxWarning:
                    # while normally harmless, causes a test failure
                    pass
                except:
                    print(status.getvalue())
                    raise

Example 35

Project: django-cms
Source File: test_management.py
View license
    def test_fix_tree_regression_5641(self):
        # ref: https://github.com/divio/django-cms/issues/5641
        alpha = create_page("Alpha", "nav_playground.html", "en", published=True)
        beta = create_page("Beta", "nav_playground.html", "en", published=False)
        gamma = create_page("Gamma", "nav_playground.html", "en", published=False)
        delta = create_page("Delta", "nav_playground.html", "en", published=True)
        theta = create_page("Theta", "nav_playground.html", "en", published=True)

        beta.move_page(alpha, position='last-child')
        gamma.move_page(beta.reload(), position='last-child')
        delta.move_page(gamma.reload(), position='last-child')
        theta.move_page(delta.reload(), position='last-child')

        out = StringIO()
        management.call_command('cms', 'fix-tree', interactive=False, stdout=out)

        alpha = alpha.reload()
        beta = beta.reload()
        gamma = gamma.reload()
        delta = delta.reload()
        theta = theta.reload()

        tree = [
            (alpha, '0001'),
            (beta, '00010001'),
            (gamma, '000100010001'),
            (delta, '0001000100010001'),
            (theta, '00010001000100010001'),
            (alpha.publisher_public, '0002'),
            (delta.publisher_public, '0006'),
            (theta.publisher_public, '00060001'),
        ]

        for page, path in tree:
            self.assertEqual(page.path, path)

Example 36

Project: django-cms
Source File: test_management.py
View license
    @override_settings(INSTALLED_APPS=TEST_INSTALLED_APPS)
    def test_list_plugins(self):
        out = StringIO()
        placeholder = Placeholder.objects.create(slot="test")
        add_plugin(placeholder, TextPlugin, "en", body="en body")
        add_plugin(placeholder, TextPlugin, "en", body="en body")
        link_plugin = add_plugin(placeholder, "LinkPlugin", "en",
                                 name="A Link", url="https://www.django-cms.org")
        self.assertEqual(
            CMSPlugin.objects.filter(plugin_type=PLUGIN).count(),
            2)
        self.assertEqual(
            CMSPlugin.objects.filter(plugin_type="LinkPlugin").count(),
            1)

        # create a CMSPlugin with an unsaved instance
        instanceless_plugin = CMSPlugin(language="en", plugin_type="TextPlugin")
        instanceless_plugin.save()

        # create a bogus CMSPlugin to simulate one which used to exist but
        # is no longer installed
        bogus_plugin = CMSPlugin(language="en", plugin_type="BogusPlugin")
        bogus_plugin.save()

        management.call_command('cms', 'list', 'plugins', interactive=False, stdout=out)
        report = plugin_report()

        # there should be reports for three plugin types
        self.assertEqual(
            len(report),
            3)

        # check the bogus plugin
        bogus_plugins_report = report[0]
        self.assertEqual(
            bogus_plugins_report["model"],
            None)

        self.assertEqual(
            bogus_plugins_report["type"],
            u'BogusPlugin')

        self.assertEqual(
            bogus_plugins_report["instances"][0],
            bogus_plugin)

        # check the link plugin
        link_plugins_report = report[1]
        self.assertEqual(
            link_plugins_report["model"],
            link_plugin.__class__)

        self.assertEqual(
            link_plugins_report["type"],
            u'LinkPlugin')

        self.assertEqual(
            link_plugins_report["instances"][0].get_plugin_instance()[0],
            link_plugin)

        # check the text plugins
        text_plugins_report = report[2]
        self.assertEqual(
            text_plugins_report["model"],
            TextPlugin.model)

        self.assertEqual(
            text_plugins_report["type"],
            u'TextPlugin')

        self.assertEqual(
            len(text_plugins_report["instances"]),
            3)

        self.assertEqual(
            text_plugins_report["instances"][2],
            instanceless_plugin)

        self.assertEqual(
            text_plugins_report["unsaved_instances"],
            [instanceless_plugin])

Example 37

Project: django-cms
Source File: test_management.py
View license
    @override_settings(INSTALLED_APPS=TEST_INSTALLED_APPS)
    def test_delete_orphaned_plugins(self):
        placeholder = Placeholder.objects.create(slot="test")
        add_plugin(placeholder, TextPlugin, "en", body="en body")
        add_plugin(placeholder, TextPlugin, "en", body="en body")
        add_plugin(placeholder, "LinkPlugin", "en",
                   name="A Link", url="https://www.django-cms.org")

        instanceless_plugin = CMSPlugin(
            language="en", plugin_type="TextPlugin")
        instanceless_plugin.save()

        # create a bogus CMSPlugin to simulate one which used to exist but
        # is no longer installed
        bogus_plugin = CMSPlugin(language="en", plugin_type="BogusPlugin")
        bogus_plugin.save()

        report = plugin_report()

        # there should be reports for three plugin types
        self.assertEqual(
            len(report),
            3)

        # check the bogus plugin
        bogus_plugins_report = report[0]
        self.assertEqual(
            len(bogus_plugins_report["instances"]),
            1)

        # check the link plugin
        link_plugins_report = report[1]
        self.assertEqual(
            len(link_plugins_report["instances"]),
            1)

        # check the text plugins
        text_plugins_report = report[2]
        self.assertEqual(
            len(text_plugins_report["instances"]),
            3)

        self.assertEqual(
            len(text_plugins_report["unsaved_instances"]),
            1)

        out = StringIO()
        management.call_command('cms', 'delete-orphaned-plugins', interactive=False, stdout=out)
        report = plugin_report()

        # there should be reports for two plugin types (one should have been deleted)
        self.assertEqual(
            len(report),
            2)

        # check the link plugin
        link_plugins_report = report[0]
        self.assertEqual(
            len(link_plugins_report["instances"]),
            1)

        # check the text plugins
        text_plugins_report = report[1]
        self.assertEqual(
            len(text_plugins_report["instances"]),
            2)

        self.assertEqual(
            len(text_plugins_report["unsaved_instances"]),
            0)

Example 38

Project: django-cms
Source File: test_management.py
View license
    def test_uninstall_plugins_without_plugin(self):
        out = StringIO()
        management.call_command('cms', 'uninstall', 'plugins', PLUGIN, interactive=False, stdout=out)
        self.assertEqual(out.getvalue(), "no 'TextPlugin' plugins found\n")

Example 39

Project: django-cms
Source File: test_management.py
View license
    def test_copy_langs(self):
        """
        Various checks here:

         * plugins are exactly doubled, half per language with no orphaned plugin
         * the bottom-most plugins in the nesting chain maintain the same position and the same content
         * the top-most plugin are of the same type
        """
        site = 1
        number_start_plugins = CMSPlugin.objects.all().count()

        out = StringIO()
        management.call_command(
            'cms', 'copy', 'lang', '--from-lang=en', '--to-lang=de', interactive=False, stdout=out
        )
        pages = Page.objects.on_site(site).drafts()
        for page in pages:
            self.assertEqual(set((u'en', u'de')), set(page.get_languages()))
        # These asserts that no orphaned plugin exists
        self.assertEqual(CMSPlugin.objects.all().count(), number_start_plugins*2)
        self.assertEqual(CMSPlugin.objects.filter(language='en').count(), number_start_plugins)
        self.assertEqual(CMSPlugin.objects.filter(language='de').count(), number_start_plugins)

        root_page = Page.objects.on_site(site).get_home()
        root_plugins = CMSPlugin.objects.filter(placeholder=root_page.placeholders.get(slot="body"))

        first_plugin_en, _ = root_plugins.get(language='en', parent=None).get_plugin_instance()
        first_plugin_de, _ = root_plugins.get(language='de', parent=None).get_plugin_instance()

        self.assertEqual(first_plugin_en.plugin_type, first_plugin_de.plugin_type)

        link_en, _ = root_plugins.get(language='en', plugin_type='LinkPlugin').get_plugin_instance()
        link_de, _ = root_plugins.get(language='de', plugin_type='LinkPlugin').get_plugin_instance()

        self.assertEqual(link_en.url, link_de.url)
        self.assertEqual(link_en.get_position_in_placeholder(), link_de.get_position_in_placeholder())

        stack_plugins = CMSPlugin.objects.filter(placeholder=StaticPlaceholder.objects.order_by('?')[0].draft)

        stack_text_en, _ = stack_plugins.get(language='en', plugin_type='TextPlugin').get_plugin_instance()
        stack_text_de, _ = stack_plugins.get(language='de', plugin_type='TextPlugin').get_plugin_instance()

        self.assertEqual(stack_text_en.plugin_type, stack_text_de.plugin_type)
        self.assertEqual(stack_text_en.body, stack_text_de.body)

Example 40

Project: django-cms
Source File: test_management.py
View license
    def test_copy_langs_no_content(self):
        """
        Various checks here:

         * page structure is copied
         * no plugin is copied
        """
        site = 1
        number_start_plugins = CMSPlugin.objects.all().count()

        out = StringIO()
        management.call_command(
            'cms', 'copy', 'lang', '--from-lang=en', '--to-lang=de', '--skip-content',
            interactive=False, stdout=out
        )
        pages = Page.objects.on_site(site).drafts()
        for page in pages:
            self.assertEqual(set((u'en', u'de')), set(page.get_languages()))
        # These asserts that no orphaned plugin exists
        self.assertEqual(CMSPlugin.objects.all().count(), number_start_plugins)
        self.assertEqual(CMSPlugin.objects.filter(language='en').count(), number_start_plugins)
        self.assertEqual(CMSPlugin.objects.filter(language='de').count(), 0)

        root_page = Page.objects.on_site(site).get_home()
        root_plugins = CMSPlugin.objects.filter(
            placeholder=root_page.placeholders.get(slot="body"))

        first_plugin_en, _ = root_plugins.get(language='en', parent=None).get_plugin_instance()
        first_plugin_de = None
        with self.assertRaises(CMSPlugin.DoesNotExist):
            first_plugin_de, _ = root_plugins.get(language='de', parent=None).get_plugin_instance()

        self.assertIsNone(first_plugin_de)

        stack_plugins = CMSPlugin.objects.filter(
            placeholder=StaticPlaceholder.objects.order_by('?')[0].draft)

        stack_text_en, _ = stack_plugins.get(language='en',
                                             plugin_type='TextPlugin').get_plugin_instance()
        with self.assertRaises(CMSPlugin.DoesNotExist):
            stack_text_de, _ = stack_plugins.get(language='de',
                                                 plugin_type='TextPlugin').get_plugin_instance()

Example 41

Project: django-cms
Source File: test_management.py
View license
    def test_copy_sites(self):
        """
        Various checks here:

         * plugins are exactly doubled, half per site with no orphaned plugin
         * the bottom-most plugins in the nesting chain maintain the same position and the same content
         * the top-most plugin are of the same type
        """
        site_1_pk = 1
        site_2 = Site.objects.create(name='site 2')
        site_2_pk = site_2.pk
        phs = []
        for page in Page.objects.on_site(site_1_pk).drafts():
            phs.extend(page.placeholders.values_list('pk', flat=True))
        number_start_plugins = CMSPlugin.objects.filter(placeholder__in=phs).count()

        out = StringIO()
        management.call_command(
            'cms', 'copy', 'site', '--from-site=%s' % site_1_pk, '--to-site=%s' % site_2_pk,
            stdout=out
        )
        for page in Page.objects.on_site(site_1_pk).drafts():
            page.publish('en')
        for page in Page.objects.on_site(site_2_pk).drafts():
            page.publish('en')
        pages_1 = list(Page.objects.on_site(site_1_pk).drafts())
        pages_2 = list(Page.objects.on_site(site_2_pk).drafts())
        for index, page in enumerate(pages_1):
            self.assertEqual(page.get_title('en'), pages_2[index].get_title('en'))
            self.assertEqual(page.depth, pages_2[index].depth)

        phs_1 = []
        phs_2 = []
        for page in Page.objects.on_site(site_1_pk).drafts():
            phs_1.extend(page.placeholders.values_list('pk', flat=True))
        for page in Page.objects.on_site(site_2_pk).drafts():
            phs_2.extend(page.placeholders.values_list('pk', flat=True))

        # These asserts that no orphaned plugin exists
        self.assertEqual(CMSPlugin.objects.filter(placeholder__in=phs_1).count(), number_start_plugins)
        self.assertEqual(CMSPlugin.objects.filter(placeholder__in=phs_2).count(), number_start_plugins)

        root_page_1 = Page.objects.on_site(site_1_pk).get_home(site_1_pk)
        root_page_2 = Page.objects.on_site(site_2_pk).get_home(site_2_pk)
        root_plugins_1 = CMSPlugin.objects.filter(placeholder=root_page_1.placeholders.get(slot="body"))
        root_plugins_2 = CMSPlugin.objects.filter(placeholder=root_page_2.placeholders.get(slot="body"))

        first_plugin_1, _ = root_plugins_1.get(language='en', parent=None).get_plugin_instance()
        first_plugin_2, _ = root_plugins_2.get(language='en', parent=None).get_plugin_instance()

        self.assertEqual(first_plugin_1.plugin_type, first_plugin_2.plugin_type)

        link_1, _ = root_plugins_1.get(language='en', plugin_type='LinkPlugin').get_plugin_instance()
        link_2, _ = root_plugins_2.get(language='en', plugin_type='LinkPlugin').get_plugin_instance()

        self.assertEqual(link_1.url, link_2.url)
        self.assertEqual(link_1.get_position_in_placeholder(), link_2.get_position_in_placeholder())

Example 42

Project: django-cms
Source File: test_management.py
View license
    def test_copy_existing_title(self):
        """
        Even if a title already exists the copy is successfull, the original
        title remains untouched
        """
        site = 1
        number_start_plugins = CMSPlugin.objects.all().count()

        # create an empty title language
        root_page = Page.objects.on_site(site).get_home()
        create_title("de", "root page de", root_page)

        out = StringIO()
        management.call_command(
            'cms', 'copy', 'lang', '--from-lang=en', '--to-lang=de', interactive=False, stdout=out
        )
        pages = Page.objects.on_site(site).drafts()
        for page in pages:
            self.assertEqual(set((u'en', u'de')), set(page.get_languages()))

        # Original Title untouched
        self.assertEqual("root page de", Page.objects.on_site(site).get_home().get_title("de"))

        # Plugins still copied
        self.assertEqual(CMSPlugin.objects.all().count(), number_start_plugins*2)
        self.assertEqual(CMSPlugin.objects.filter(language='en').count(), number_start_plugins)
        self.assertEqual(CMSPlugin.objects.filter(language='de').count(), number_start_plugins)

Example 43

Project: django-cms
Source File: test_management.py
View license
    def test_copy_filled_placeholder(self):
        """
        If an existing title in the target language has plugins in a placeholder
        that placeholder is skipped
        """
        site = 1
        number_start_plugins = CMSPlugin.objects.all().count()

        # create an empty title language
        root_page = Page.objects.on_site(site).get_home()
        create_title("de", "root page de", root_page)
        ph = root_page.placeholders.get(slot="body")
        add_plugin(ph, "TextPlugin", "de", body="Hello World")

        out = StringIO()
        management.call_command(
            'cms', 'copy', 'lang', '--from-lang=en', '--to-lang=de', interactive=False, stdout=out
        )

        self.assertEqual(CMSPlugin.objects.filter(language='en').count(), number_start_plugins)
        # one placeholder (with 7 plugins) is skipped, so the difference must be 6
        self.assertEqual(CMSPlugin.objects.filter(language='de').count(), number_start_plugins-6)

Example 44

Project: django-cms
Source File: test_management.py
View license
    def test_copy_filled_placeholder_force_copy(self):
        """
        If an existing title in the target language has plugins in a placeholder
        and the command is called with *force-copy*, the plugins are copied on
        top of the existing one
        """
        site = 1
        number_start_plugins = CMSPlugin.objects.all().count()

        # create an empty title language
        root_page = Page.objects.on_site(site).get_home()
        create_title("de", "root page de", root_page)
        ph = root_page.placeholders.get(slot="body")
        add_plugin(ph, "TextPlugin", "de", body="Hello World")

        root_plugins = CMSPlugin.objects.filter(placeholder=ph)
        text_de_orig, _ = root_plugins.get(language='de', plugin_type='TextPlugin').get_plugin_instance()

        out = StringIO()
        management.call_command(
            'cms', 'copy', 'lang', '--from-lang=en', '--to-lang=de', '--force', interactive=False,
            stdout=out
        )

        CMSPlugin.objects.filter(placeholder=root_page.placeholders.get(slot="body"))

        self.assertEqual(CMSPlugin.objects.filter(language='en').count(), number_start_plugins)
        # we have an existing plugin in one placeholder, so we have one more
        self.assertEqual(CMSPlugin.objects.filter(language='de').count(), number_start_plugins+1)

Example 45

Project: django-cms
Source File: test_management.py
View license
    def test_copy_site_safe(self):
        """
        Check that copy of languages on one site does not interfere with other
        sites
        """
        site_other = 1
        site_active = 2
        origina_site1_langs = {}

        number_start_plugins = CMSPlugin.objects.all().count()
        site_obj = Site.objects.create(domain="sample2.com", name="sample2.com", pk=site_active)

        for page in Page.objects.on_site(1).drafts():
            origina_site1_langs[page.pk] = set(page.get_languages())

        p1 = create_page('page1', published=True, in_navigation=True, language='de', template='nav_playground.html', site=site_obj)
        create_page('page4', published=True, in_navigation=True, language='de', template='nav_playground.html', site=site_obj)
        create_page('page2', published=True, in_navigation=True, parent=p1, language='de', template='nav_playground.html', site=site_obj)

        for page in Page.objects.on_site(site_active).drafts():
            self._fill_page_body(page, 'de')

        number_site2_plugins = CMSPlugin.objects.all().count() - number_start_plugins

        out = StringIO()
        management.call_command(
            'cms', 'copy', 'lang', '--from-lang=de', '--to-lang=fr', '--site=%s' % site_active,
            interactive=False, stdout=out
        )

        for page in Page.objects.on_site(site_other).drafts():
            self.assertEqual(origina_site1_langs[page.pk], set(page.get_languages()))

        for page in Page.objects.on_site(site_active).drafts():
            self.assertEqual(set(('de', 'fr')), set(page.get_languages()))

        # plugins for site 1
        self.assertEqual(CMSPlugin.objects.filter(language='en').count(), number_start_plugins)
        # plugins for site 2 de
        self.assertEqual(CMSPlugin.objects.filter(language='de').count(), number_site2_plugins)
        # plugins for site 2 fr
        self.assertEqual(CMSPlugin.objects.filter(language='fr').count(), number_site2_plugins)
        # global number of plugins
        self.assertEqual(CMSPlugin.objects.all().count(), number_start_plugins + number_site2_plugins*2)

Example 46

Project: django-cms
Source File: context_managers.py
View license
    def __init__(self, std='out', buffer=None):
        self.std = std
        self.buffer = buffer or StringIO()

Example 47

View license
    def setUp(self):
        self._input = StringIO(
            '<?xml version="1.0" encoding="utf-8"?>'
            '<root>'
            '<field_a>121.0</field_a>'
            '<field_b>dasd</field_b>'
            '<field_c></field_c>'
            '<field_d>2011-12-25 12:45:00</field_d>'
            '</root>'
        )
        self._data = {
            'field_a': 121,
            'field_b': 'dasd',
            'field_c': None,
            'field_d': datetime.datetime(2011, 12, 25, 12, 45, 00)
        }
        self._complex_data_input = StringIO(
            '<?xml version="1.0" encoding="utf-8"?>'
            '<root>'
            '<creation_date>2011-12-25 12:45:00</creation_date>'
            '<sub_data_list>'
            '<list-item><sub_id>1</sub_id><sub_name>first</sub_name></list-item>'
            '<list-item><sub_id>2</sub_id><sub_name>second</sub_name></list-item>'
            '</sub_data_list>'
            '<name>name</name>'
            '</root>'
        )
        self._complex_data = {
            "creation_date": datetime.datetime(2011, 12, 25, 12, 45, 00),
            "name": "name",
            "sub_data_list": [
                {
                    "sub_id": 1,
                    "sub_name": "first"
                },
                {
                    "sub_id": 2,
                    "sub_name": "second"
                }
            ]
        }

Example 48

View license
    def setUp(self):
        self._input = StringIO(
            '<?xml version="1.0" encoding="utf-8"?>'
            '<root>'
            '<field_a>121.0</field_a>'
            '<field_b>dasd</field_b>'
            '<field_c></field_c>'
            '<field_d>2011-12-25 12:45:00</field_d>'
            '</root>'
        )
        self._data = {
            'field_a': 121,
            'field_b': 'dasd',
            'field_c': None,
            'field_d': datetime.datetime(2011, 12, 25, 12, 45, 00)
        }
        self._complex_data_input = StringIO(
            '<?xml version="1.0" encoding="utf-8"?>'
            '<root>'
            '<creation_date>2011-12-25 12:45:00</creation_date>'
            '<sub_data_list>'
            '<list-item><sub_id>1</sub_id><sub_name>first</sub_name></list-item>'
            '<list-item><sub_id>2</sub_id><sub_name>second</sub_name></list-item>'
            '</sub_data_list>'
            '<name>name</name>'
            '</root>'
        )
        self._complex_data = {
            "creation_date": datetime.datetime(2011, 12, 25, 12, 45, 00),
            "name": "name",
            "sub_data_list": [
                {
                    "sub_id": 1,
                    "sub_name": "first"
                },
                {
                    "sub_id": 2,
                    "sub_name": "second"
                }
            ]
        }