Python textwrap.dedent() Examples

The following are 30 code examples of textwrap.dedent(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module textwrap , or try the search function .
Example #1
Source File: ez_setup.py    From iAI with MIT License 6 votes vote down vote up
def _conflict_bail(VC_err, version):
    """
    Setuptools was imported prior to invocation, so it is
    unsafe to unload it. Bail out.
    """
    conflict_tmpl = textwrap.dedent("""
        The required version of setuptools (>={version}) is not available,
        and can't be installed while this script is running. Please
        install a more recent version first, using
        'easy_install -U setuptools'.

        (Currently using {VC_err.args[0]!r})
        """)
    msg = conflict_tmpl.format(**locals())
    sys.stderr.write(msg)
    sys.exit(2) 
Example #2
Source File: cmd_utils.py    From godot-mono-builds with MIT License 6 votes vote down vote up
def build_arg_parser(description, env_vars={}):
    from argparse import ArgumentParser, RawDescriptionHelpFormatter
    from textwrap import dedent

    base_env_vars = {
        'MONO_SOURCE_ROOT': 'Overrides default value for --mono-sources',
    }

    env_vars_text = '\n'.join(['    %s: %s' % (var, desc) for var, desc in env_vars.items()])
    base_env_vars_text = '\n'.join(['    %s: %s' % (var, desc) for var, desc in base_env_vars.items()])

    epilog=dedent('''\
environment variables:
%s
%s
''' % (env_vars_text, base_env_vars_text))

    return ArgumentParser(
        description=description,
        formatter_class=RawDescriptionHelpFormatter,
        epilog=epilog
    ) 
Example #3
Source File: conftest.py    From mutatest with MIT License 6 votes vote down vote up
def augassign_file(tmp_path_factory):
    """A simple python file with the AugAssign attributes."""
    contents = dedent(
        """\
    def my_func(a, b):
        a += 6
        b -= 4
        b /= 2
        b *= 3

        return a, b
    """
    )

    fn = tmp_path_factory.mktemp("augassign") / "augassign.py"

    with open(fn, "w") as output_fn:
        output_fn.write(contents)

    yield fn

    fn.unlink() 
Example #4
Source File: test_report.py    From mutatest with MIT License 6 votes vote down vote up
def test_build_report_section(mock_Mutant):
    """Simplified report section formatting for the report."""

    title = "Title"
    mutants = [mock_Mutant]

    report = build_report_section(title, mutants)

    expected = dedent(
        """

    Title
    -----
     - src.py: (l: 1, c: 2) - mutation from <class '_ast.Add'> to <class '_ast.Mult'>"""
    )

    assert report == expected 
Example #5
Source File: conftest.py    From mutatest with MIT License 6 votes vote down vote up
def slice_file(tmp_path_factory):
    """A simple python file with the slice attributes."""
    contents = dedent(
        """\
    def my_func(x_list):
        y_list = x_list[:-1]
        z_list = x_list[0:2:-4]
        zz_list = x_list[0::2]
        zzs_list = x_list[-8:-3:2]
        yz_list = y_list[0:]
        a_list = x_list[::]

        return yz_list
    """
    )

    fn = tmp_path_factory.mktemp("slice") / "slice.py"

    with open(fn, "w") as output_fn:
        output_fn.write(contents)

    yield fn

    fn.unlink() 
Example #6
Source File: conftest.py    From mutatest with MIT License 6 votes vote down vote up
def boolop_file(tmp_path_factory):
    """A simple python file with bool op operations."""
    contents = dedent(
        """\
    def equal_test(a, b):
        return a and b

    print(equal_test(1,1))
    """
    )

    fn = tmp_path_factory.mktemp("boolop") / "boolop.py"

    with open(fn, "w") as output_fn:
        output_fn.write(contents)

    yield fn

    fn.unlink() 
Example #7
Source File: conftest.py    From mutatest with MIT License 6 votes vote down vote up
def index_file(tmp_path_factory):
    """A simple python file with the index attributes for list slices."""
    contents = dedent(
        """\
    def my_func(x_list):
        a_list = x_list[-1]
        b_list = x_list[0]
        c_list = x_list[1][2]
    """
    )

    fn = tmp_path_factory.mktemp("index") / "index.py"

    with open(fn, "w") as output_fn:
        output_fn.write(contents)

    yield fn

    fn.unlink() 
Example #8
Source File: conftest.py    From mutatest with MIT License 6 votes vote down vote up
def compare_file(tmp_path_factory):
    """A simple python file with the compare."""
    contents = dedent(
        """\
    def equal_test(a, b):
        return a == b

    def is_test(a, b):
        return a is b

    def in_test(a, b):
        return a in b
    print(equal_test(1,1))
    """
    )

    fn = tmp_path_factory.mktemp("compare") / "compare.py"

    with open(fn, "w") as output_fn:
        output_fn.write(contents)

    yield fn

    fn.unlink() 
Example #9
Source File: test_config.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_config(self):
        from textwrap import dedent

        # variable substitution with [DEFAULT]
        conf = dedent("""
        [DEFAULT]
        dir = "/some/dir"
        my.dir = %(dir)s + "/sub"

        [my]
        my.dir = %(dir)s + "/my/dir"
        my.dir2 = %(my.dir)s + '/dir2'

        """)

        fp = StringIOFromNative(conf)

        cherrypy.config.update(fp)
        self.assertEqual(cherrypy.config['my']['my.dir'], '/some/dir/my/dir')
        self.assertEqual(cherrypy.config['my']
                         ['my.dir2'], '/some/dir/my/dir/dir2') 
Example #10
Source File: test_config.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_call_with_kwargs(self):
        from textwrap import dedent
        conf = dedent("""
        [my]
        value = dict(foo="buzz", **cherrypy._test_dict)
        """)
        test_dict = {
            'foo': 'bar',
            'bar': 'foo',
            'fizz': 'buzz'
        }
        cherrypy._test_dict = test_dict
        fp = StringIOFromNative(conf)
        cherrypy.config.update(fp)
        test_dict['foo'] = 'buzz'
        self.assertEqual(cherrypy.config['my']['value']['foo'], 'buzz')
        self.assertEqual(cherrypy.config['my']['value'], test_dict)
        del cherrypy._test_dict 
Example #11
Source File: test_params.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_syntax(self):
        if sys.version_info < (3,):
            return self.skip('skipped (Python 3 only)')
        code = textwrap.dedent("""
            class Root:
                @cherrypy.expose
                @cherrypy.tools.params()
                def resource(self, limit: int):
                    return type(limit).__name__
            conf = {'/': {'tools.params.on': True}}
            cherrypy.tree.mount(Root(), config=conf)
            """)
        exec(code)

        self.getPage('/resource?limit=0')
        self.assertStatus(200)
        self.assertBody('int') 
Example #12
Source File: conftest.py    From py-solc with MIT License 6 votes vote down vote up
def FOO_SOURCE(supported_solc_version, solc_version):
    if solc_version in Spec('<0.4.17'):
        return textwrap.dedent('''\
            pragma solidity ^0.4.0;

            contract Foo {
                function Foo() {}

                function return13() public returns (uint) {
                    return 13;
                }
            }
            ''')
    else:
        return textwrap.dedent('''\
            pragma solidity ^0.4.17;

            contract Foo {
                function Foo() public {}

                function return13() public pure returns (uint) {
                    return 13;
                }
            }
            ''') 
Example #13
Source File: __init__.py    From syncthingmanager with GNU General Public License v3.0 6 votes vote down vote up
def _folder_list(self):
        """Prints out a formatted list of folders from the configuration."""
        config = self.system.config()
        status = self.system.status()
        for folder in config['folders']:
            devices = []
            sync_status = floor(100 * self.db_folder_sync_fraction(folder['id']))
            for device in folder['devices']:
                if device['deviceID'] == status['myID']:
                    continue
                name = self.device_info(device['deviceID'])['name']
                devices.append(name)
            if folder['label'] == '':
                folderstr = folder['id']
            else:
                folderstr = folder['label']
            outstr = """\
                    {0}     {4}%
                        Shared With:  {1}
                        Folder ID:  {2}
                        Folder Path:    {3}
                    """.format(folderstr, ', '.join(map(str, devices)),
                            folder['id'], folder['path'], str(sync_status))
            print(dedent(outstr)) 
Example #14
Source File: test_cli.py    From mutatest with MIT License 6 votes vote down vote up
def test_read_setup_cfg_missing_mutatest_ini(tmp_path, section, monkeypatch):
    """Setup.cfg will support both [mutatest] and [tool:mutatest] sections."""
    ini_contents = dedent(
        f"""\
    [{section}]
    whitelist = nc su ix"""
    )

    expected = ["nc", "su", "ix"]

    with open(tmp_path / "setup.cfg", "w") as fstream:
        fstream.write(ini_contents)

    monkeypatch.chdir(tmp_path)
    result = cli.cli_args([])
    print(result.__dict__)

    assert len(result.whitelist) == 3
    for r, e in zip(result.whitelist, expected):
        assert r == e 
Example #15
Source File: test_compiler.py    From hiku with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_compiles(dsl_expr, code):
    types = ENV.__types__

    expr, functions = to_expr(dsl_expr)
    env = fn_types(functions)
    env.update(types['__root__'].__field_types__)

    expr = check(expr, types, env)

    # test eval
    lambda_expr = ExpressionCompiler.compile_lambda_expr(expr)
    eval(compile(lambda_expr, '<expr>', 'eval'))

    # test compile
    py_expr = ExpressionCompiler.compile_expr(expr)

    first = astor.to_source(py_expr).strip()
    second = dedent(code).strip()
    if first != second:
        msg = ('Compiled code is not equal:\n\n{}'
               .format('\n'.join(difflib.ndiff(first.splitlines(),
                                               second.splitlines()))))
        raise AssertionError(msg) 
Example #16
Source File: sphinx.py    From gist-alfred with MIT License 6 votes vote down vote up
def __call__(self, wrapped):
        """
        Add the Sphinx directive to your class or function.

        :param wrapped: Wrapped class or function.

        :return: the decorated class or function.
        """
        reason = textwrap.dedent(self.reason).strip()
        reason = '\n'.join(textwrap.fill(line, width=70, initial_indent='   ', subsequent_indent='   ')
                           for line in reason.splitlines()).strip()
        docstring = textwrap.dedent(wrapped.__doc__ or "")
        if docstring:
            docstring += "\n\n"
        if self.version:
            docstring += ".. {directive}:: {version}\n".format(directive=self.directive, version=self.version)
        else:
            docstring += ".. {directive}::\n".format(directive=self.directive)
        if reason:
            docstring += "   {reason}\n".format(reason=reason)
        wrapped.__doc__ = docstring
        return super(SphinxAdapter, self).__call__(wrapped) 
Example #17
Source File: test_config.py    From sanic with MIT License 6 votes vote down vote up
def test_load_from_file(app):
    config = dedent(
        """
    VALUE = 'some value'
    condition = 1 == 1
    if condition:
        CONDITIONAL = 'should be set'
    """
    )
    with temp_path() as config_path:
        config_path.write_text(config)
        app.config.from_pyfile(str(config_path))
        assert "VALUE" in app.config
        assert app.config.VALUE == "some value"
        assert "CONDITIONAL" in app.config
        assert app.config.CONDITIONAL == "should be set"
        assert "condition" not in app.config 
Example #18
Source File: _toVerilog.py    From myhdl with GNU Lesser General Public License v2.1 6 votes vote down vote up
def visit_FunctionDef(self, node):
        self.write("task %s;" % self.tree.name)
        self.indent()
        self.writeInterfaceDeclarations()
        self.writeDeclarations()
        self.dedent()
        self.writeline()
        self.write("begin: %s" % self.returnLabel)
        self.indent()
        self.visit_stmt(node.body)
        self.dedent()
        self.writeline()
        self.write("end")
        self.writeline()
        self.write("endtask")
        self.writeline(2) 
Example #19
Source File: _toVerilog.py    From myhdl with GNU Lesser General Public License v2.1 6 votes vote down vote up
def visit_FunctionDef(self, node):
        self.write("function ")
        self.writeOutputDeclaration()
        self.indent()
        self.writeInputDeclarations()
        self.writeDeclarations()
        self.dedent()
        self.writeline()
        self.write("begin: %s" % self.returnLabel)
        self.indent()
        self.visit_stmt(node.body)
        self.dedent()
        self.writeline()
        self.write("end")
        self.writeline()
        self.write("endfunction")
        self.writeline(2) 
Example #20
Source File: _toVerilog.py    From myhdl with GNU Lesser General Public License v2.1 6 votes vote down vote up
def visit_FunctionDef(self, node):
        self.writeDoc(node)
        w = node.body[-1]
        y = w.body[0]
        if isinstance(y, ast.Expr):
            y = y.value
        assert isinstance(y, ast.Yield)
        self.writeAlwaysHeader()
        self.writeDeclarations()
        # assert isinstance(w.body, astNode.Stmt)
        for stmt in w.body[1:]:
            self.writeline()
            self.visit(stmt)
        self.dedent()
        self.writeline()
        self.write("end")
        self.writeline(2) 
Example #21
Source File: _toVerilog.py    From myhdl with GNU Lesser General Public License v2.1 6 votes vote down vote up
def visit_While(self, node):
        self.labelStack.append(node.breakLabel)
        self.labelStack.append(node.loopLabel)
        if node.breakLabel.isActive:
            self.write("begin: %s" % node.breakLabel)
            self.writeline()
        self.write("while (")
        self.visit(node.test)
        self.write(") begin")
        if node.loopLabel.isActive:
            self.write(": %s" % node.loopLabel)
        self.indent()
        self.visit_stmt(node.body)
        self.dedent()
        self.writeline()
        self.write("end")
        if node.breakLabel.isActive:
            self.writeline()
            self.write("end")
        self.labelStack.pop()
        self.labelStack.pop() 
Example #22
Source File: hmutils.py    From simnibs with GNU General Public License v3.0 6 votes vote down vote up
def write_unity_xfm(output_dir):
    """Write a unity transformation matrix to disk.
    
    PARAMETERS
    ----------
    output_dir : str
        The directory in which to save the generated file. 
    
    RETURNS
    ----------
    Writes the file "unity.xfm" to the specified folder.
    """
    with open(os.path.join(output_dir, "unity.xfm"),"w") as f:
        f.write(textwrap.dedent("""\
        MNI Transform File
        % tkregister2
        
        Transform_Type = Linear;
        Linear_Transform =
        1.0    0.0    0.0  0.0
        0.0    1.0    0.0  0.0
        0.0    0.0    1.0  0.0;""")) 
Example #23
Source File: __init__.py    From syncthingmanager with GNU General Public License v3.0 6 votes vote down vote up
def _print_device_info(self, devicestr):
        config = self.system.config()
        info = self.device_info(devicestr)
        try:
            device = config['devices'][info['index']]
        except TypeError:
            raise SyncthingManagerError("Device not configured: " + devicestr)
        folders = self.device_info(device['deviceID'])['folders']
        outstr = """\
                {0}
                    Addresses:     {1}
                    Folders:    {2}
                    ID:     {3}
                    Introducer?     {4}
                """.format(device['name'], ', '.join(device['addresses']),
                ', '.join(map(str, folders)), device['deviceID'],
                device['introducer'])
        print(dedent(outstr)) 
Example #24
Source File: test_integration_sandbox.py    From django-payfast with MIT License 6 votes vote down vote up
def test_process_empty():  # type: () -> None
    """
    Submitting an empty payment request fails.
    """
    response = post_sandbox_checkout({})
    assert {
        'payment_summary': 'Payment total R ZAR',
        'notice': dedent("""\
            The supplied variables are not according to specification:
            amount : amount is required
            item_name : item_name is required
            merchant_id : merchant_id is required
            merchant_key : merchant_key is required
        """),
    } == parse_payfast_page(response)


# Check for ITN testing configuration: 
Example #25
Source File: support.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def reformat(string):
    return dedent(string) + "\n\n" 
Example #26
Source File: base.py    From verge3d-blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def _write_test_script(self, code, filename='mytestscript.py'):
        """
        Dedents the given code (a multiline string) and writes it out to
        a file in a temporary folder like /tmp/tmpUDCn7x/mytestscript.py.
        """
        if isinstance(code, bytes):
            code = code.decode('utf-8')
        # Be explicit about encoding the temp file as UTF-8 (issue #63):
        with io.open(self.tempdir + filename, 'wt', encoding='utf-8') as f:
            f.write(dedent(code)) 
Example #27
Source File: test_execute_code.py    From sphinx-execute-code with MIT License 5 votes vote down vote up
def test_execute_code_function():
    """ Ensure simple code functions execute """
    code = dedent('''
    print "foo"
    print "bar"
    ''')

    expected_output = dedent('''\
    foo
    bar
    ''')
    results = ExecuteCode.execute_code(code)

    assert expected_output == results 
Example #28
Source File: base.py    From verge3d-blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def reformat_code(code):
    """
    Removes any leading \n and dedents.
    """
    if code.startswith('\n'):
        code = code[1:]
    return dedent(code) 
Example #29
Source File: sortedlist.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __make_cmp(seq_op, symbol, doc):
        "Make comparator method."
        def comparer(self, other):
            "Compare method for sorted list and sequence."
            if not isinstance(other, Sequence):
                return NotImplemented

            self_len = self._len
            len_other = len(other)

            if self_len != len_other:
                if seq_op is eq:
                    return False
                if seq_op is ne:
                    return True

            for alpha, beta in zip(self, other):
                if alpha != beta:
                    return seq_op(alpha, beta)

            return seq_op(self_len, len_other)

        seq_op_name = seq_op.__name__
        comparer.__name__ = '__{0}__'.format(seq_op_name)
        doc_str = """Return true if and only if sorted list is {0} `other`.

        ``sl.__{1}__(other)`` <==> ``sl {2} other``

        Comparisons use lexicographical order as with sequences.

        Runtime complexity: `O(n)`

        :param other: `other` sequence
        :return: true if sorted list is {0} `other`

        """
        comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
        return comparer 
Example #30
Source File: sortedset.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __make_cmp(set_op, symbol, doc):
        "Make comparator method."
        def comparer(self, other):
            "Compare method for sorted set and set."
            if isinstance(other, SortedSet):
                return set_op(self._set, other._set)
            elif isinstance(other, Set):
                return set_op(self._set, other)
            return NotImplemented

        set_op_name = set_op.__name__
        comparer.__name__ = '__{0}__'.format(set_op_name)
        doc_str = """Return true if and only if sorted set is {0} `other`.

        ``ss.__{1}__(other)`` <==> ``ss {2} other``

        Comparisons use subset and superset semantics as with sets.

        Runtime complexity: `O(n)`

        :param other: `other` set
        :return: true if sorted set is {0} `other`

        """
        comparer.__doc__ = dedent(doc_str.format(doc, set_op_name, symbol))
        return comparer