Coverage for tests/test_dead_code_core.py: 100%

1"""Tests for dead code detection."""

2

3 from __future__ import annotations

4

5 from pathlib import Path

6

7 from parsers.python import parse

8 from dead_code.parsers.python import PythonDeadCodeParser

9

10

11 def test_extract_imports():

12 code = """

13 import os

14 import sys as system

15 from os.path import join, exists

16 from typing import List

17"""

18 parser = PythonDeadCodeParser()

19 root = parse(code)

20 imports = parser.extract_imports(root, code)

21

22 assert len(imports) >= 3

23 import_names = [imp.name for imp in imports]

24 assert "os" in import_names

25 assert "system" in import_names or "sys" in import_names

26 assert "join" in import_names or "exists" in import_names

27

28

29 def test_extract_definitions():

30 code = """

31 def foo():

32 pass

33

34 class Bar:

35 pass

36"""

37 parser = PythonDeadCodeParser()

38 root = parse(code)

39 defs = parser.extract_definitions(root, code)

40

41 assert len(defs) == 2

42 def_names = [d.name for d in defs]

43 assert "foo" in def_names

44 assert "Bar" in def_names

45

46

47 def test_extract_references():

48 code = """

49 def foo(x):

50 return x

51

52 y = foo(1)

53 bar = y

54"""

55 parser = PythonDeadCodeParser()

56 root = parse(code)

57 refs = parser.extract_references(root, code)

58

59 ref_names = [r.name for r in refs]

60 assert "x" in ref_names

61 assert "foo" in ref_names

62 assert "y" in ref_names

63 assert "bar" in ref_names

64

65

66 def test_unused_import():

67 from dead_code.core import build_cross_reference_graph, find_unused_imports

68

69 code = """

70 import os

71 def foo():

72 return 1

73"""

74 root = parse(code)

75 parser = PythonDeadCodeParser()

76

77 imports = parser.extract_imports(root, code)

78 refs = parser.extract_references(root, code)

79

80 assert len(imports) == 1

81 assert len(refs) > 0