Example #1
0
 def _test(stem, leafs, expected):
     statement = ImportStatement(
         list(),
         stem,
         list(map(ImportLeaf, leafs))
     )
     self.assertEqual(statement.as_string(), expected)
Example #2
0
    def test_all_line_numbers(self) -> None:
        s2 = ImportStatement("b", line_numbers=[2, 7])
        s1 = ImportStatement("a", line_numbers=[1, 2])

        group = BaseImportGroup(statements=[s1, s2])

        assert group.all_line_numbers() == [1, 2, 7]
Example #3
0
 def test_should_add_statement(self) -> None:
     assert self.group(group_config=GroupConfig(
         type="packages", packages=["foo"])).should_add_statement(
             ImportStatement("foo.bar"))
     assert not self.group(group_config=GroupConfig(
         type="packages", packages=["foo"])).should_add_statement(
             ImportStatement("os.path"))
Example #4
0
    def test_init(self):
        actual = ImportStatement(mock.sentinel.line_numbers, 'foo')
        self.assertEqual(actual.line_numbers, mock.sentinel.line_numbers)
        self.assertEqual(actual.stem, 'foo')
        self.assertIsNone(actual.as_name)
        self.assertEqual(actual.leafs, [])

        actual = ImportStatement(mock.sentinel.line_numbers, 'foo as bar')
        self.assertEqual(actual.line_numbers, mock.sentinel.line_numbers)
        self.assertEqual(actual.stem, 'foo')
        self.assertEqual(actual.as_name, 'bar')
        self.assertEqual(actual.leafs, [])

        actual = ImportStatement(mock.sentinel.line_numbers, 'foo as foo')
        self.assertEqual(actual.line_numbers, mock.sentinel.line_numbers)
        self.assertEqual(actual.stem, 'foo')
        self.assertIsNone(actual.as_name)
        self.assertEqual(actual.leafs, [])

        actual = ImportStatement(mock.sentinel.line_numbers, 'foo',
                                 mock.sentinel.leafs)
        self.assertEqual(actual.line_numbers, mock.sentinel.line_numbers)
        self.assertEqual(actual.stem, 'foo')
        self.assertEqual(actual.leafs, mock.sentinel.leafs)

        actual = ImportStatement(mock.sentinel.line_numbers, 'foo as bar',
                                 mock.sentinel.leafs)
        self.assertEqual(actual.line_numbers, mock.sentinel.line_numbers)
        self.assertEqual(actual.stem, 'foo')
        self.assertIsNone(actual.as_name)
        self.assertEqual(actual.leafs, mock.sentinel.leafs)
Example #5
0
 def _test(
     stem: str,
     leafs: typing.List[typing.Union[typing.Tuple[str], typing.Tuple[str, str]]],
     expected: str,
 ) -> None:
     statement = ImportStatement(stem, leafs=[ImportLeaf(*i) for i in leafs])
     assert statement.as_string() == expected
     assert str(statement) == expected
Example #6
0
    def test_add_statement_to_group_priority(self):
        groups = ImportGroups()
        groups.extend([RemainderGroup(), LocalGroup()])

        groups.add_statement_to_group(ImportStatement([], ".a"))

        self.assertListEqual(groups[0].statements, [])
        self.assertListEqual(groups[1].statements, [ImportStatement([], ".a")])
Example #7
0
 def _test(stem, leafs, expected):
     statement = ImportStatement(
         list(),
         stem,
         list(map(ImportLeaf, leafs))
     )
     self.assertEqual(statement.formatted(),
                      '\n'.join(expected))
Example #8
0
    def test_all_line_numbers(self):
        s2 = ImportStatement([2, 7], 'b')
        s1 = ImportStatement([1, 2], 'a')

        group = BaseImportGroup()
        group.statements = [s1, s2]

        self.assertListEqual(group.all_line_numbers(), [1, 2, 7])
Example #9
0
    def test_as_string_with_artifacts(self) -> None:
        group = BaseImportGroup(
            statements=[ImportStatement("b"),
                        ImportStatement("a")],
            artifacts=Artifacts(sep="\r\n"),
        )

        assert str(group.as_string()) == "import a\r\nimport b"
Example #10
0
 def test_all_line_numbers(self) -> None:
     assert ImportGroups().all_line_numbers() == []
     assert ImportGroups([
         BaseImportGroup(
             statements=[ImportStatement("foo", line_numbers=[2, 7])]),
         BaseImportGroup(
             statements=[ImportStatement("bar", line_numbers=[1, 2])]),
     ]).all_line_numbers() == [1, 2, 7]
Example #11
0
    def test_add_statement(self) -> None:
        groups = ImportGroups([LocalGroup()])

        with pytest.raises(ValueError):
            groups.add_statement(ImportStatement("a"))

        groups.add_statement(ImportStatement(".a"))

        assert groups.groups[0].statements == [ImportStatement(".a")]
Example #12
0
 def _test(stem, leafs, stem2, leafs2, greater=True):
     statement = ImportStatement(list(), stem,
                                 list(map(ImportLeaf, leafs)))
     statement2 = ImportStatement(list(), stem2,
                                  list(map(ImportLeaf, leafs2)))
     if greater:
         self.assertGreater(statement2, statement)
     else:
         self.assertLess(statement2, statement)
Example #13
0
    def test_as_string_with_artifacts(self):
        group = BaseImportGroup(file_artifacts={'sep': '\r\n'})
        group.statements = [ImportStatement([], 'b'),
                            ImportStatement([], 'a')]

        self.assertEqual(
            group.as_string(),
            'import a\r\n'
            'import b'
        )
Example #14
0
    def test_add_statement_to_group_one(self):
        groups = ImportGroups()
        groups.extend([LocalGroup()])

        with self.assertRaises(ValueError):
            groups.add_statement_to_group(ImportStatement([], 'a'))

        groups.add_statement_to_group(ImportStatement([], '.a'))

        self.assertListEqual(groups[0].statements, [ImportStatement([], '.a')])
Example #15
0
    def test_unique_statements_special(self) -> None:
        group = BaseImportGroup(statements=[
            ImportStatement("b", leafs=[ImportLeaf("c")]),
            ImportStatement("a", leafs=[ImportLeaf("*")]),
        ])

        assert sorted(group.unique_statements) == [
            ImportStatement("a", leafs=[ImportLeaf("*")]),
            ImportStatement("b", leafs=[ImportLeaf("c")]),
        ]
Example #16
0
 def _test(
     stem: str,
     leafs: typing.List[str],
     stem2: str,
     leafs2: typing.List[str],
     greater: bool = True,
 ) -> None:
     statement = ImportStatement(stem, leafs=list(map(ImportLeaf, leafs)))
     statement2 = ImportStatement(stem2, leafs=list(map(ImportLeaf, leafs2)))
     assert (statement2 > statement) == greater
Example #17
0
    def test_as_string(self):
        group = BaseImportGroup()
        group.statements = [ImportStatement([], 'b'),
                            ImportStatement([], 'a')]

        self.assertEqual(
            group.as_string(),
            'import a\n'
            'import b'
        )
Example #18
0
    def test_formatted(self) -> None:
        stem = "b" * 80
        group = BaseImportGroup(statements=[
            ImportStatement(stem, leafs=[ImportLeaf("c"),
                                         ImportLeaf("d")]),
            ImportStatement("a"),
        ])

        assert group.formatted() == "\n".join(
            [f"import a", f"from {stem} import (", f"    c,", f"    d,", f")"])
Example #19
0
    def test_merged_statements_special(self):
        group = BaseImportGroup()
        group.statements = [ImportStatement([], 'a', [ImportLeaf('*')]),
                            ImportStatement([], 'b', [ImportLeaf('c')])]

        actual = group.merged_statements

        self.assertListEqual(sorted(actual), [
            ImportStatement([], 'a', [ImportLeaf('*')]),
            ImportStatement([], 'b', [ImportLeaf('c')]),
        ])
Example #20
0
    def test_formatted(self):
        group = BaseImportGroup()
        group.statements = [
            ImportStatement([], 'b' * 80,
                            [ImportLeaf('c'), ImportLeaf('d')]),
            ImportStatement([], 'a')
        ]

        self.assertEqual(
            group.formatted(),
            'import a\n' + 'from {} import (\n'.format('b' * 80) + '    c,\n' +
            '    d,\n' + ')')
Example #21
0
 def _test(self, stem, leafs, expected, sep='\n', comments=None, **kwargs):
     """Facilitate the output tests of formatters"""
     statement = ImportStatement(
         [],
         stem,
         list(
             map((lambda i: i
                  if isinstance(i, ImportLeaf) else ImportLeaf(i)), leafs)),
         comments=comments,
         **kwargs)
     self.assertEqual(statement.formatted(formatter=self.formatter),
                      sep.join(expected))
Example #22
0
    def test_init(self):
        actual = ImportStatement(mock.sentinel.line_numbers,
                                 mock.sentinel.stem)
        self.assertEqual(actual.line_numbers, mock.sentinel.line_numbers)
        self.assertEqual(actual.stem, mock.sentinel.stem)
        self.assertEqual(actual.leafs, [])

        actual = ImportStatement(mock.sentinel.line_numbers,
                                 mock.sentinel.stem, mock.sentinel.leafs)
        self.assertEqual(actual.line_numbers, mock.sentinel.line_numbers)
        self.assertEqual(actual.stem, mock.sentinel.stem)
        self.assertEqual(actual.leafs, mock.sentinel.leafs)
Example #23
0
    def test_add(self):
        with self.assertRaises(AssertionError):
            ImportStatement([], 'a') + ImportStatement([], 'b')

        actual = (ImportStatement([1, 2], 'a', [ImportLeaf('b')]) +
                  ImportStatement([3, 4], 'a', [ImportLeaf('c')]))

        self.assertEqual(
            actual,
            ImportStatement([1, 2, 3, 4], 'a',
                            [ImportLeaf('b'), ImportLeaf('c')]))
        self.assertListEqual(actual.line_numbers, [1, 2, 3, 4])
Example #24
0
    def test_add(self) -> None:
        with pytest.raises(AssertionError):
            ImportStatement("a") + ImportStatement("b")

        actual = ImportStatement(
            "a", leafs=[ImportLeaf("b")], line_numbers=[1, 2]
        ) + ImportStatement("a", leafs=[ImportLeaf("c")], line_numbers=[3, 4])

        assert actual == ImportStatement(
            "a", leafs=[ImportLeaf("b"), ImportLeaf("c")], line_numbers=[1, 2, 3, 4]
        )
        assert actual.line_numbers == [1, 2, 3, 4]
Example #25
0
    def test_formatted(self):
        group = BaseImportGroup()
        group.statements = [
            ImportStatement([], "b" * 80,
                            [ImportLeaf("c"), ImportLeaf("d")]),
            ImportStatement([], "a"),
        ]

        self.assertEqual(
            group.formatted(),
            "import a\n" + "from {} import (\n".format("b" * 80) + "    c,\n" +
            "    d,\n" + ")",
        )
Example #26
0
 def _test(self, stem, leafs, expected, sep='\n', comments=None, **kwargs):
     """Facilitate the output tests of formatters"""
     statement = ImportStatement(
         [],
         stem,
         list(map((lambda i:
                   i if isinstance(i, ImportLeaf)
                   else ImportLeaf(i)),
                  leafs)),
         comments=comments,
         **kwargs
     )
     self.assertEqual(statement.formatted(formatter=self.formatter),
                      sep.join(expected))
Example #27
0
    def test_formatted_with_artifacts(self):
        artifacts = {'sep': '\r\n'}
        group = BaseImportGroup(file_artifacts=artifacts)
        group.statements = [
            ImportStatement(list(),
                            'b' * 80,
                            [ImportLeaf('c'), ImportLeaf('d')],
                            file_artifacts=artifacts),
            ImportStatement([], 'a', file_artifacts=artifacts)
        ]

        self.assertEqual(
            group.formatted(),
            'import a\r\n' + 'from {} import (\r\n'.format('b' * 80) +
            '    c,\r\n' + '    d,\r\n' + ')')
Example #28
0
    def test_formatted_with_artifacts(self) -> None:
        artifacts = Artifacts(sep="\r\n")

        groups = ImportGroups(
            [
                RemainderGroup(artifacts=artifacts),
                LocalGroup(artifacts=artifacts)
            ],
            artifacts=artifacts,
        )

        groups.add_statement(ImportStatement(".a"))
        groups.add_statement(ImportStatement("foo"))

        assert groups.formatted() == "import foo\r\n\r\nimport .a"
Example #29
0
    def test_merged_statements_special(self):
        group = BaseImportGroup()
        group.statements = [
            ImportStatement([], "a", [ImportLeaf("*")]),
            ImportStatement([], "b", [ImportLeaf("c")]),
        ]

        actual = group.merged_statements

        self.assertListEqual(
            sorted(actual),
            [
                ImportStatement([], "a", [ImportLeaf("*")]),
                ImportStatement([], "b", [ImportLeaf("c")]),
            ],
        )
Example #30
0
 def test_eq(self) -> None:
     assert ImportStatement("a", leafs=[ImportLeaf("a")]) == ImportStatement(
         "a", leafs=[ImportLeaf("a")]
     )
     assert ImportStatement("a", leafs=[ImportLeaf("a")]) == ImportStatement(
         "a", leafs=[ImportLeaf("a"), ImportLeaf("a")]
     )
     assert ImportStatement("a", leafs=[ImportLeaf("a")]) != ImportStatement(
         "a", leafs=[ImportLeaf("b")]
     )
     assert ImportStatement(
         "a", leafs=[ImportLeaf("a")], standalone_comments=["comment"]
     ) == ImportStatement("a", leafs=[ImportLeaf("a"), ImportLeaf("a")])
     assert ImportStatement(
         "a", leafs=[ImportLeaf("a")], standalone_comments=["comment"], strict=True
     ) != ImportStatement("a", leafs=[ImportLeaf("a"), ImportLeaf("a")])
Example #31
0
    def test_plugin(self) -> None:
        activate_plugin("separate_libs")
        try:
            config = Config.default()
            config.add_imports = [
                ImportStatement(
                    "__future__",
                    leafs=[
                        ImportLeaf("absolute_import"),
                        ImportLeaf("print_function"),
                        ImportLeaf("unicode_literals"),
                    ],
                )
            ]

            result = next(
                run_importanize_on_text(
                    self.input_text.read_text(),
                    self.input_text,
                    config,
                    RuntimeConfig(_config=config),
                ))
            assert result.organized == self.output_grouped_separate_libs.read_text(
            )
        finally:
            deactivate_all_plugins()
Example #32
0
 def test_ini(self) -> None:
     Config.from_ini(StdPath("config.ini"),
                     "\n".join(["[importanize]"
                                ])) == Config(StdPath("config.ini"))
     Config.from_ini(
         StdPath("config.ini"),
         "\n".join([
             "[importanize]",
             "after_imports_new_lines=5",
             "length=100",
             "formatter=lines",
             "groups=",
             "   stdlib",
             "   packages:mypackage",
             "exclude=exclude",
             "add_imports=",
             "   import foo",
             "allow_plugins=false",
         ]),
     ) == Config(
         path=StdPath("config.json"),
         after_imports_new_lines=5,
         length=100,
         formatter=LinesFormatter,
         groups=[
             GroupConfig(type="stdlib"),
             GroupConfig(type="packages", packages=["foo"]),
         ],
         exclude=["exclude"],
         add_imports=[ImportStatement("foo")],
         are_plugins_allowed=False,
     )
Example #33
0
    def test_formatted_with_artifacts(self):
        artifacts = {'sep': '\r\n'}

        groups = ImportGroups(file_artifacts=artifacts)
        groups.extend([
            RemainderGroup(file_artifacts=artifacts),
            LocalGroup(file_artifacts=artifacts),
        ])

        groups.add_statement_to_group(
            ImportStatement([], '.a', file_artifacts=artifacts))
        groups.add_statement_to_group(
            ImportStatement([], 'foo', file_artifacts=artifacts))

        self.assertEqual(groups.formatted(), 'import foo\r\n'
                         '\r\n'
                         'import .a')
Example #34
0
 def test_str(self):
     statement = ImportStatement([], 'a')
     self.assertEqual(
         statement.as_string(),
         six.text_type(statement),
     )