2023-03-12 09:56:40 +01:00
import re
import pytest
2023-09-15 13:08:14 +02:00
from core import Pattern , Object , Word , String
from core . patterns import expressions
from general . classproperty import classproperty
2023-03-12 09:56:40 +01:00
word = fr ' [ { expressions . alphanumerics } ]* '
words = fr ' [ { expressions . alphanumerics } \ s]* '
2023-09-15 13:08:14 +02:00
class ExtraParameterInPattern ( Object ) :
word1 : Word
word2 : Word
2023-03-12 09:56:40 +01:00
@classproperty
def pattern ( cls ) - > Pattern :
2023-09-15 13:08:14 +02:00
return Pattern ( ' $word1:Word $word2:Word $word3:Word ' )
2023-03-12 09:56:40 +01:00
2023-09-16 16:27:28 +02:00
async def test_typed_parameters ( ) :
2023-09-15 13:08:14 +02:00
p = Pattern ( ' lorem $name:Word dolor ' )
assert p . parameters == { ' name ' : Word }
2023-03-12 09:56:40 +01:00
assert p . compiled == fr ' lorem (?P<name> { word } ) dolor '
2023-09-16 16:27:28 +02:00
m = await p . match ( ' lorem ipsum dolor ' )
2023-03-12 09:56:40 +01:00
assert m
2023-03-16 10:41:45 +01:00
assert m [ 0 ] . substring == ' lorem ipsum dolor '
2023-09-15 13:08:14 +02:00
assert m [ 0 ] . parameters == { ' name ' : Word ( ' ipsum ' ) }
2023-09-16 16:27:28 +02:00
assert not await p . match ( ' lorem ipsum foo dolor ' )
2023-03-12 09:56:40 +01:00
2023-09-15 13:08:14 +02:00
p = Pattern ( ' lorem $name:String dolor ' )
assert p . parameters == { ' name ' : String }
2023-09-16 16:27:28 +02:00
m = await p . match ( ' lorem ipsum foo bar dolor ' )
2023-03-12 09:56:40 +01:00
assert m
2023-03-16 10:41:45 +01:00
assert m [ 0 ] . substring == ' lorem ipsum foo bar dolor '
2023-09-15 13:08:14 +02:00
assert m [ 0 ] . parameters == { ' name ' : String ( ' ipsum foo bar ' ) }
2023-03-12 09:56:40 +01:00
def test_undefined_typed_parameters ( ) :
pattern = ' lorem $name:Lorem dolor '
with pytest . raises ( NameError , match = re . escape ( f ' Unknown type: " Lorem " for parameter: " name " in pattern: " { pattern } " ' ) ) :
Pattern ( pattern )
def test_extra_parameter_in_pattern ( ) :
with pytest . raises ( AssertionError , match = ' Can`t add parameter type " ExtraParameterInPattern " : pattern parameters do not match properties annotated in class ' ) :
Pattern . add_parameter_type ( ExtraParameterInPattern )