Coverage for tests/sources/test_base.py: 100%
75 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-22 15:51 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-22 15:51 +0000
1"""Tests the base class of sources."""
3from __future__ import annotations
5import abc
6import dataclasses
7import pathlib
8from collections.abc import Iterator, MutableMapping
9from typing import Any, ClassVar
11import pytest
13import courtpy
14from courtpy import cli, options, parsers
15from courtpy.sources import base
18@dataclasses.dataclass
19class StateCourtTest(base.Source):
20 """Reads a made-up state court's cases, saved as text files.
22 It is defined at the top of the module so that processes that parse
23 with it can import it.
25 """
27 pattern: ClassVar[str] = '*.txt'
29 def read(self, path: pathlib.Path) -> courtpy.Case:
30 text = path.read_text(encoding = 'utf-8')
31 return courtpy.Case(
32 id = path.stem, source = self.name, sections = {'opinion': text},
33 metadata = {'source': self.name}, path = path)
35 def finish(self, row: MutableMapping[str, Any]) -> None:
36 row['state'] = 'Texas'
39@pytest.fixture(autouse = True)
40def restore_sources() -> Iterator[None]:
41 """Removes the sources that a test adds."""
42 sources = dict(base.SOURCES)
43 yield
44 base.SOURCES.clear()
45 base.SOURCES.update(sources)
48@pytest.fixture
49def state_folder(tmp_path: pathlib.Path) -> pathlib.Path:
50 """Returns a folder with two of the made-up state court's cases."""
51 folder = tmp_path / 'state'
52 folder.mkdir()
53 (folder / 'a.txt').write_text('We affirm the judgment.', encoding = 'utf-8')
54 (folder / 'b.txt').write_text('We reverse.', encoding = 'utf-8')
55 hidden = folder / '.courtpy'
56 hidden.mkdir()
57 (hidden / 'place.txt').write_text('not a case', encoding = 'utf-8')
58 return folder
61def test_courtpy_registers_its_own() -> None:
62 assert base.SOURCES['courtlistener'] is courtpy.courtlistener.CourtListenerSource
63 assert base.SOURCES['lexis_nexis'] is courtpy.lexis.LexisNexisSource
64 assert courtpy.Source is base.Source
67def test_sources_name_their_header_rules() -> None:
68 assert base.SOURCES['courtlistener'].header == 'courtlistener_header'
69 assert base.SOURCES['lexis_nexis'].header == 'lexis_nexis_header'
70 # A source with no header rules of its own has those that fit every one.
71 assert StateCourtTest.header == base.Source.header == 'header'
74def test_subclasses_register() -> None:
75 assert base.SOURCES['state_court_test'] is StateCourtTest
77 @dataclasses.dataclass
78 class Middle(base.Source, abc.ABC):
79 """A base class for other sources, which is not added."""
81 assert 'middle' not in base.SOURCES
82 with pytest.raises(ValueError, match = 'source must be one of'):
83 base.find_source('ftp')
86def test_find_files(state_folder: pathlib.Path) -> None:
87 found = base.find_source('state_court_test').find_files(state_folder)
88 assert [p.name for p in found] == ['a.txt', 'b.txt']
89 assert parsers.find_files(state_folder, 'state_court_test') == found
92@pytest.mark.parametrize('workers', [1, 2])
93def test_parse_a_source_of_your_own(
94 state_folder: pathlib.Path,
95 workers: int,
96 monkeypatch: pytest.MonkeyPatch) -> None:
97 monkeypatch.setattr(options, '_CHUNK_SIZE', 1)
98 table = courtpy.parse(state_folder, source = 'state_court_test', workers = workers)
99 assert list(table.index) == ['a', 'b']
100 assert (table['state'] == 'Texas').all()
103def test_parse_paths_and_one_file(state_folder: pathlib.Path) -> None:
104 paths = [state_folder / 'b.txt', state_folder / 'a.txt']
105 table = courtpy.parse(paths, source = 'state_court_test')
106 assert list(table.index) == ['b', 'a']
107 parser = courtpy.Parser.create()
108 case_id, row = parser.parse_file(state_folder / 'a.txt', 'state_court_test')
109 assert case_id == 'a' and row['state'] == 'Texas'
112def test_loader_of_your_own(state_folder: pathlib.Path) -> None:
113 @dataclasses.dataclass
114 class LoadStateCourt(courtpy.SourceLoader):
115 """Loads the made-up state court's cases."""
117 reads: ClassVar[str] = 'state_court_test'
119 dataset = LoadStateCourt().apply(None, source = state_folder, coders = 'none')
120 assert len(dataset.data) == 2
123def test_download_command_needs_courts(capsys: pytest.CaptureFixture[str]) -> None:
124 assert cli.main(['-q', 'download']) == 1
125 assert 'name at least one court' in capsys.readouterr().err