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()
def test_as_string(self): leaf = ImportLeaf('') leaf.name, leaf.as_name = 'a', None self.assertEqual(leaf.as_string(), 'a') leaf.name, leaf.as_name = 'a', 'b' self.assertEqual(leaf.as_string(), 'a as b')
def test_gt(self): self.assertGreater(ImportLeaf('b'), ImportLeaf('a')) self.assertGreater(ImportLeaf('a_variable'), ImportLeaf('CONSTANT')) self.assertGreater(ImportLeaf('AKlassName'), ImportLeaf('CONSTANT')) self.assertGreater(ImportLeaf('aKlassName'), ImportLeaf('CONSTANT')) self.assertGreater(ImportLeaf('a_variable'), ImportLeaf('aKlassName'))
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")]), ]
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")"])
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')]), ])
def test_init(self): actual = ImportLeaf('a') self.assertEqual(actual.name, 'a') self.assertIsNone(actual.as_name) actual = ImportLeaf('a as b') self.assertEqual(actual.name, 'a') self.assertEqual(actual.as_name, 'b') actual = ImportLeaf('a as a') self.assertEqual(actual.name, 'a') self.assertIsNone(actual.as_name)
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' + ')')
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])
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]
def test_str(self): leaf = ImportLeaf('a') self.assertEqual(six.text_type(leaf), leaf.as_string()) leaf = ImportLeaf('a as b') self.assertEqual(six.text_type(leaf), leaf.as_string()) leaf = ImportLeaf('a as a') self.assertEqual(six.text_type(leaf), leaf.as_string())
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" + ")", )
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' + ')')
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")]), ], )
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
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" + ")", )
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))
def test_eq(self): self.assertTrue( ImportStatement([], 'a', [ImportLeaf('a')]) == ImportStatement( [], 'a', [ImportLeaf('a')])) self.assertTrue( ImportStatement([], 'a', [ImportLeaf('a')]) == ImportStatement( [], 'a', [ImportLeaf('a'), ImportLeaf('a')])) self.assertFalse( ImportStatement([], 'a', [ImportLeaf('a')]) == ImportStatement( [], 'a', [ImportLeaf('b')]))
def test_should_include_leaf(self) -> None: plugin = UnusedImportsPlugin() artifacts = Artifacts.default() typing.cast(UnsusedImportsArtifacts, artifacts).unused_imports = [ "os", "itertools.chain as ichain", ] assert plugin.should_include_leaf( RemainderGroup(artifacts=artifacts), ImportStatement("os", leafs=[ImportLeaf("path")], inline_comments=["noqa"]), ImportLeaf("path"), ) assert plugin.should_include_leaf( RemainderGroup(artifacts=artifacts), ImportStatement( "os", leafs=[ImportLeaf("path", statement_comments=["noqa"])]), ImportLeaf("path", statement_comments=["noqa"]), ) assert not plugin.should_include_leaf( RemainderGroup(artifacts=artifacts), ImportStatement("os", leafs=[ImportLeaf("path")]), ImportLeaf("path"), ) assert plugin.should_include_leaf( RemainderGroup(artifacts=artifacts), ImportStatement("itertools", leafs=[ImportLeaf("chain")]), ImportLeaf("chain"), ) assert not plugin.should_include_leaf( RemainderGroup(artifacts=artifacts), ImportStatement("itertools", leafs=[ImportLeaf("chain", as_name="ichain")]), ImportLeaf("chain", as_name="ichain"), )
def test_formatted(self): # Test one-line imports self._test(module, [], ['import {}'.format(module)]) self._test(module, [obj1], ['from {} import {}'.format(module, obj1)]) self._test(module, [obj1, obj2], ['from {} import {}, {}'.format(module, obj1, obj2)]) self._test(long_module, [long_obj1], ['from {} import {}'.format(long_module, long_obj1)]) # Test multi-lines imports self._test(long_module, [long_obj1, long_obj2], [ 'from {} import ('.format(long_module), ' {},'.format(long_obj1), ' {},'.format(long_obj2), ')' ]) # Test file_artifacts self._test(long_module, [long_obj1, long_obj2], [ 'from {} import ('.format(long_module), ' {},'.format(long_obj1), ' {},'.format(long_obj2), ')' ], sep='\r\n', file_artifacts={'sep': '\r\n'}) # Test imports with comments self._test('foo', [], ['import foo # comment'], comments=[Token('# comment')]) self._test('foo', [ImportLeaf('bar', comments=[Token('#comment')])], ['from foo import bar # comment']) self._test('something', [ImportLeaf('foo'), ImportLeaf('bar')], ['from something import bar, foo # noqa'], comments=[Token('# noqa')]) self._test('foo', [ ImportLeaf('bar', comments=[Token('#hello')]), ImportLeaf('rainbows', comments=[Token('#world')]), ImportLeaf( 'zz', comments=[Token('#and lots of sleep', is_comment_first=True)]) ], [ 'from foo import ( # noqa', ' bar, # hello', ' rainbows, # world', ' # and lots of sleep', ' zz,', ')' ], comments=[Token('#noqa')])
def test_hash_mock(self, mock_as_string): hash(ImportLeaf('a')) mock_as_string.assert_called_once_with()
def test_hash(self): self.assertEqual(hash(ImportLeaf('a')), hash('a')) self.assertEqual(hash(ImportLeaf('a as b')), hash('a as b'))
def test_repr(self): self.assertEqual( repr(ImportLeaf('a')), '<{}.{} object - "a">'.format(ImportLeaf.__module__, ImportLeaf.__name__))
def test_str_mock(self, mock_as_string): self.assertEqual( getattr(ImportLeaf('a'), '__{}__'.format(six.text_type.__name__))(), mock_as_string.return_value)
def test_eq(self): self.assertTrue(ImportLeaf('a') == ImportLeaf('a')) self.assertFalse(ImportLeaf('a') == ImportLeaf('b'))
def test_repr(self) -> None: assert repr(ImportLeaf("a")) == "<ImportLeaf 'a'>"
def test_hash(self) -> None: assert hash(ImportLeaf("a")) == hash("a") assert hash(ImportLeaf("a", "b")) == hash("a as b")
def test_hash(self): self.assertEqual(hash(ImportStatement([], 'a')), hash('import a')) self.assertEqual(hash(ImportStatement([], 'a', [ImportLeaf('b')])), hash('from a import b'))
def test_all_inline_comments(self) -> None: assert ImportStatement( "a", inline_comments=["statement"], leafs=[ImportLeaf("b", statement_comments=["leaf"])], ).all_inline_comments == ["leaf", "statement"]
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")])