Coverage for src/copytrading_engine/host/self_test/parser.py: 83%

19 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-16 16:55 +0000

1"""Deterministic parser for the published engine self-test fixture.""" 

2 

3import re 

4from decimal import Decimal, InvalidOperation 

5from fractions import Fraction 

6 

7from copytrading_engine.host.errors import UnsupportedSelfTest 

8from copytrading_engine.host.self_test.model import ParsedSelfTest 

9 

10_SIMULATION_TEXT = re.compile( 

11 r"Bought\s+(?P<symbol>[A-Z][A-Z0-9.-]{0,9})\s+" 

12 r"(?P<quantity>\d+(?:/\d+|\.\d+)?)\s+at\s+" 

13 r"(?P<price>\d+(?:\.\d{1,4})?)" 

14) 

15 

16 

17class SelfTestParser: 

18 """Parse the deliberately narrow local self-test grammar without network calls.""" 

19 

20 def parse(self, text: str) -> ParsedSelfTest: 

21 match = _SIMULATION_TEXT.fullmatch(text) 

22 if match is None: 

23 raise UnsupportedSelfTest("unsupported self-test text") 

24 

25 try: 

26 quantity = Fraction(match.group("quantity")) 

27 unit_price = Decimal(match.group("price")) 

28 except (ValueError, ZeroDivisionError, InvalidOperation) as exc: 

29 raise UnsupportedSelfTest("unsupported self-test text") from exc 

30 if quantity <= 0 or unit_price <= 0: 30 ↛ 31line 30 didn't jump to line 31 because the condition on line 30 was never true

31 raise UnsupportedSelfTest("unsupported self-test text") 

32 

33 return ParsedSelfTest( 

34 symbol=match.group("symbol"), 

35 action="buy", 

36 quantity=quantity, 

37 unit_price=unit_price, 

38 )