Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _wait(self, timeout=5):
try:
self.process.expect(EOF, timeout=timeout)
except TIMEOUT:
raise Failure(_("timed out while waiting for program to exit")) from TIMEOUT(timeout)
except UnicodeDecodeError:
raise Failure(_("output not valid ASCII text"))
self.kill()
if self.process.signalstatus == signal.SIGSEGV:
raise Failure(_("failed to execute program due to segmentation fault"))
self.exitcode = self.process.exitstatus
return self
"""
Check that the process survives for timeout. Useful for checking whether program is waiting on input.
:param timeout: number of seconds to wait
:type timeout: int / float
:raises check50.Failure: if process ends before ``timeout``
"""
log(_("checking that input was rejected..."))
try:
self._wait(timeout)
except Failure as e:
if not isinstance(e.__cause__, TIMEOUT):
raise
else:
raise Failure(_("expected program to reject input, but it did not"))
return self
if output == EOF:
log(_("checking for EOF..."))
else:
output = output.replace("\n", "\r\n")
log(_("checking for output \"{}\"...").format(str_output))
try:
expect(output, timeout=timeout)
except EOF:
result = self.process.before + self.process.buffer
if self.process.after != EOF:
result += self.process.after
raise Mismatch(str_output, result.replace("\r\n", "\n"))
except TIMEOUT:
raise Failure(_("did not find {}").format(_raw(str_output)))
except UnicodeDecodeError:
raise Failure(_("output not valid ASCII text"))
except Exception:
raise Failure(_("check50 could not verify output"))
# If we expected EOF and we still got output, report an error.
if output == EOF and self.process.before:
raise Mismatch(EOF, self.process.before.replace("\r\n", "\n"))
return self
def _search_page(self, output, str_output, content, match_fn, **kwargs):
if output is None:
return content
if str_output is None:
str_output = output
log(_("checking that \"{}\" is in page").format(str_output))
regex = re.compile(output)
if not match_fn(regex, content):
raise Failure(
_("expected to find \"{}\" in page, but it wasn't found").format(str_output))
return self
def exists(*paths):
"""
Assert that all given paths exist.
:params paths: files/directories to be checked for existence
:raises check50.Failure: if any ``path in paths`` does not exist
Example usage::
check50.exists("foo.c", "foo.h")
"""
for path in paths:
log(_("checking that {} exists...").format(path))
if not os.path.exists(path):
raise Failure(_("{} not found").format(path))
def _send(self, method, route, data, params, **kwargs):
"""Send request of type `method` to `route`."""
route = self._fmt_route(route, params)
log(_("sending {} request to {}").format(method.upper(), route))
try:
self.response = getattr(self._client, method.lower())(route, data=data, **kwargs)
except BaseException as e: # Catch all exceptions thrown by app
log(_("exception raised in application: {}: {}").format(type(e).__name__, e))
raise Failure(_("application raised an exception (rerun with --log for more details)"))
return self
out = check50.run("./cash").stdin("4.2").stdout()
if 10 not in out:
help = None
if 11 in out:
help = "did you forget to round your result?"
raise check50.Failure("Expected a different result", help=help)
"""
def __init__(self, rationale, help=None):
self.payload = {"rationale": rationale, "help": help}
def __str__(self):
return self.payload["rationale"]
class Mismatch(Failure):
"""
Exception signifying check failure due to a mismatch in expected and actual outputs.
:param expected: the expected value
:param actual: the actual value
:param help: optional help message to be displayed
:type help: str
Example usage::
from re import match
expected = "[Hh]ello, world!?\\n"
actual = check50.run("./hello").stdout()
if not match(expected, actual):
help = None
if match(expected[:-1], actual):
def __init__(self, path="application.py", app_name="app"):
path = pathlib.Path(path).resolve()
# Add directory of flask app to sys.path so we can import it properly
prevpath = sys.path[0]
try:
sys.path[0] = str(path.parent)
mod = internal.import_file(path.stem, path.name)
except FileNotFoundError:
raise Failure(_("could not find {}").format(path.name))
finally:
# Restore sys.path
sys.path[0] = prevpath
try:
app = getattr(mod, app_name)
except AttributeError:
raise Failure(_("{} does not contain an app").format(file))
app.testing = True
# Initialize flask client
self._client = app.test_client()
self.response = None
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except Failure:
raise Failure(failure_rationale)
finally:
_log.clear()
return wrapper