|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import inspect |
| 4 | +import typing as t |
| 5 | +from unittest.mock import MagicMock |
| 6 | + |
| 7 | +import pytest |
| 8 | +from sqlmesh.core.model import Model |
| 9 | +from sqlmesh.core.linter.rule import Rule, RuleViolation |
| 10 | + |
| 11 | + |
| 12 | +class TestRule(Rule): |
| 13 | + """A test rule for testing the get_definition_location method.""" |
| 14 | + |
| 15 | + def check_model(self, model: Model) -> t.Optional[RuleViolation]: |
| 16 | + """The evaluation function that'll check for a violation of this rule.""" |
| 17 | + return None |
| 18 | + |
| 19 | + |
| 20 | +def test_get_definition_location(): |
| 21 | + """Test the get_definition_location method returns correct file and line information.""" |
| 22 | + # Create a mock context |
| 23 | + mock_context = MagicMock() |
| 24 | + rule = TestRule(mock_context) |
| 25 | + |
| 26 | + # Get the expected location using the inspect module |
| 27 | + expected_file = inspect.getfile(TestRule) |
| 28 | + expected_source, expected_start_line = inspect.getsourcelines(TestRule) |
| 29 | + expected_end_line = expected_start_line + len(expected_source) - 1 |
| 30 | + |
| 31 | + # Get the location using the Rule method |
| 32 | + location = rule.get_definition_location() |
| 33 | + |
| 34 | + # Assert the file path matches |
| 35 | + assert location["file_path"] == expected_file |
| 36 | + |
| 37 | + # Assert the line numbers match |
| 38 | + assert location["start_line"] == expected_start_line |
| 39 | + assert location["end_line"] == expected_end_line |
| 40 | + |
| 41 | + # Test the fallback case for a class without source |
| 42 | + with pytest.MonkeyPatch.context() as mp: |
| 43 | + # Mock inspect.getsourcelines to raise an exception |
| 44 | + def mock_getsourcelines(*args, **kwargs): |
| 45 | + raise IOError("Mock error") |
| 46 | + |
| 47 | + mp.setattr(inspect, "getsourcelines", mock_getsourcelines) |
| 48 | + |
| 49 | + # Get the location with the mocked function |
| 50 | + fallback_location = rule.get_definition_location() |
| 51 | + |
| 52 | + # It should still have the file path |
| 53 | + assert "file_path" in fallback_location |
| 54 | + assert fallback_location["file_path"] == expected_file |
| 55 | + |
| 56 | + # But not the line numbers |
| 57 | + assert "start_line" not in fallback_location |
| 58 | + assert "end_line" not in fallback_location |
0 commit comments