Skip to content

Commit

Permalink
Advertise support for the string parser to also work on bytes.
Browse files Browse the repository at this point in the history
Note that this already worked, except the type annotation was wrong
and there were no tests.
  • Loading branch information
jap committed Feb 29, 2024
1 parent a0c5d9a commit be1cbc0
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
7 changes: 5 additions & 2 deletions src/parsy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import re
from dataclasses import dataclass
from functools import wraps
from typing import Any, Callable, FrozenSet
from typing import Any, AnyStr, Callable, FrozenSet

__version__ = "2.1"

Expand Down Expand Up @@ -529,13 +529,16 @@ def fail(expected: str) -> Parser:
return Parser(lambda _, index: Result.failure(index, expected))


def string(expected_string: str, transform: Callable[[str], str] = noop) -> Parser:
def string(expected_string: AnyStr, transform: Callable[[AnyStr], AnyStr] = noop) -> Parser:
"""
Returns a parser that expects the ``expected_string`` and produces
that string value.
Optionally, a transform function can be passed, which will be used on both
the expected string and tested string.
This parser can also be instantiated with a bytes value, in which case it can
should be applied to a stream of bytes.
"""

slen = len(expected_string)
Expand Down
17 changes: 15 additions & 2 deletions tests/test_parsy.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@


class TestParser(unittest.TestCase):
def test_string(self):
def test_string_str(self):
parser = string("x")
self.assertEqual(parser.parse("x"), "x")

self.assertRaises(ParseError, parser.parse, "y")

def test_string_transform(self):
def test_string_transform_str(self):
parser = string("x", transform=lambda s: s.lower())
self.assertEqual(parser.parse("x"), "x")
self.assertEqual(parser.parse("X"), "x")
Expand All @@ -53,6 +53,19 @@ def test_string_transform_2(self):

self.assertRaises(ParseError, parser.parse, "dog")

def test_string_bytes(self):
parser = string(b"x")
self.assertEqual(parser.parse(b"x"), b"x")

self.assertRaises(ParseError, parser.parse, b"y")

def test_string_transform_bytes(self):
parser = string(b"x", transform=lambda s: s.lower())
self.assertEqual(parser.parse(b"x"), b"x")
self.assertEqual(parser.parse(b"X"), b"x")

self.assertRaises(ParseError, parser.parse, b"y")

def test_regex_str(self):
parser = regex(r"[0-9]")

Expand Down

0 comments on commit be1cbc0

Please sign in to comment.