Skip to content

Commit

Permalink
Merge pull request #226 from cs50/stdout_numbers
Browse files Browse the repository at this point in the history
int and float support for run.stdout
  • Loading branch information
Jelleas committed Jul 14, 2020
2 parents c0bed9c + c08e758 commit fd93e0d
Show file tree
Hide file tree
Showing 3 changed files with 115 additions and 6 deletions.
3 changes: 2 additions & 1 deletion check50/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ def _setup_translation():
exists,
hash,
include,
regex,
run,
log, _log,
hidden,
Expand All @@ -48,5 +49,5 @@ def _setup_translation():
from .runner import check
from pexpect import EOF

__all__ = ["import_checks", "data", "exists", "hash", "include",
__all__ = ["import_checks", "data", "exists", "hash", "include", "regex",
"run", "log", "Failure", "Mismatch", "check", "EOF"]
50 changes: 45 additions & 5 deletions check50/_api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import hashlib
import functools
import numbers
import os
import re
import shlex
import shutil
import signal
Expand Down Expand Up @@ -135,6 +137,35 @@ def import_checks(path):
return mod


class regex:
@staticmethod
def decimal(number):
"""
Create a regular expression to match the number exactly:
In case of a positive number:
(?<![\d\-])number(?!(\.?\d))
In case of a negative number:
number(?!(\.?\d))
(?<![\d\-]) = negative lookbehind, \
asserts that there are no digits and no - in front of the number.
(?!(\.?\d)) = negative lookahead, \
asserts that there are no digits and no additional . followed by digits after the number.
:param number: the number to match in the regex
:type number: any numbers.Number (such as int, float, ...)
:rtype: str
Example usage::
# Check that 7.0000 is printed with 5 significant figures
check50.run("./prog").stdout(check50.regex.decimal("7.0000"))
"""
negative_lookbehind = fr"(?<![\d\-])" if number >= 0 else ""
return fr"{negative_lookbehind}{re.escape(str(number))}(?!(\.?\d))"


class run:
"""
Run a command.
Expand Down Expand Up @@ -214,8 +245,11 @@ def stdout(self, output=None, str_output=None, regex=True, timeout=3):
it returns ``self``.
:param output: optional output to be expected from stdout, raises \
:class:`check50.Failure` if no match
:type output: str
:class:`check50.Failure` if no match \
In case output is a float or int, the check50.number_regex \
is used to match just that number". \
In case output is a stream its contents are used via output.read().
:type output: str, int, float, stream
:param str_output: what will be displayed as expected output, a human \
readable form of ``output``
:type str_output: str
Expand All @@ -239,15 +273,21 @@ def stdout(self, output=None, str_output=None, regex=True, timeout=3):
self._wait(timeout)
return self.process.before.replace("\r\n", "\n").lstrip("\n")

# In case output is a stream (file-like object), read from it
try:
output = output.read()
except AttributeError:
pass

expect = self.process.expect if regex else self.process.expect_exact

if str_output is None:
str_output = output
str_output = str(output)

# In case output is an int/float, use a regex to match exactly that int/float
if isinstance(output, numbers.Number):
regex = True
output = globals()["regex"].decimal(output)

expect = self.process.expect if regex else self.process.expect_exact

if output == EOF:
log(_("checking for EOF..."))
Expand Down
68 changes: 68 additions & 0 deletions tests/api_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,74 @@ def test_out_no_regex(self):
self.process.stdout(".o.", regex=False)
self.assertFalse(self.process.process.isalive())

def test_int(self):
self.write("print(123)")
self.runpy()
with self.assertRaises(check50.Failure):
self.process.stdout(1)

self.write("print(21)")
self.runpy()
with self.assertRaises(check50.Failure):
self.process.stdout(1)

self.write("print(1.0)")
self.runpy()
with self.assertRaises(check50.Failure):
self.process.stdout(1)

self.write("print('a1b')")
self.runpy()
self.process.stdout(1)

self.write("print(1)")
self.runpy()
self.process.stdout(1)

def test_float(self):
self.write("print(1.01)")
self.runpy()
with self.assertRaises(check50.Failure):
self.process.stdout(1.0)

self.write("print(21.0)")
self.runpy()
with self.assertRaises(check50.Failure):
self.process.stdout(1.0)

self.write("print(1)")
self.runpy()
with self.assertRaises(check50.Failure):
self.process.stdout(1.0)

self.write("print('a1.0b')")
self.runpy()
self.process.stdout(1.0)

self.write("print(1.0)")
self.runpy()
self.process.stdout(1.0)

def test_negative_number(self):
self.write("print(1)")
self.runpy()
with self.assertRaises(check50.Failure):
self.process.stdout(-1)

self.write("print(-1)")
self.runpy()
with self.assertRaises(check50.Failure):
self.process.stdout(1)

self.write("print('2-1')")
self.runpy()
self.process.stdout(-1)

self.write("print(-1)")
self.runpy()
self.process.stdout(-1)


class TestProcessStdoutFile(Base):
def setUp(self):
super().setUp()
Expand Down

0 comments on commit fd93e0d

Please sign in to comment.