File: test_metadata.py

package info (click to toggle)
python-libcst 1.4.0-1.2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,928 kB
  • sloc: python: 76,235; makefile: 10; sh: 2
file content (50 lines) | stat: -rw-r--r-- 1,627 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
from textwrap import dedent

import libcst as cst
from libcst import parse_module
from libcst.codemod import CodemodContext, ContextAwareTransformer, ContextAwareVisitor
from libcst.metadata import PositionProvider
from libcst.testing.utils import UnitTest


class TestingCollector(ContextAwareVisitor):
    METADATA_DEPENDENCIES = (PositionProvider,)

    def visit_Pass(self, node: cst.Pass) -> None:
        position = self.get_metadata(PositionProvider, node)
        self.context.scratch["pass"] = (position.start.line, position.start.column)


class TestingTransform(ContextAwareTransformer):
    METADATA_DEPENDENCIES = (PositionProvider,)

    def visit_FunctionDef(self, node: cst.FunctionDef) -> None:
        position = self.get_metadata(PositionProvider, node)
        self.context.scratch[node.name.value] = (
            position.start.line,
            position.start.column,
        )
        node.visit(TestingCollector(self.context))


class TestMetadata(UnitTest):
    def test_metadata_works(self) -> None:
        code = """
            def foo() -> None:
                pass

            def bar() -> int:
                return 5
        """
        module = parse_module(dedent(code))
        context = CodemodContext()
        transform = TestingTransform(context)
        transform.transform_module(module)
        self.assertEqual(
            context.scratch, {"foo": (2, 0), "pass": (3, 4), "bar": (5, 0)}
        )