-
-
Notifications
You must be signed in to change notification settings - Fork 74
[WIP] Change tests to pytest format. #639
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
2dd32c0
Move to pytest.
tillahoffmann f1031b1
Fix import order for pylint.
tillahoffmann 55a3802
Fix type annotation for `check_present`.
tillahoffmann caf946b
Use `session` scope for removing artifacts.
tillahoffmann 87f0747
Fix skip decorators and Windows path test.
tillahoffmann 04e6c4d
Remove precompiled executable in `test_compile_with_includes`.
tillahoffmann File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,6 +4,5 @@ pytest | |
pytest-cov | ||
pytest-order | ||
mypy | ||
testfixtures | ||
tqdm | ||
xarray |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,81 +1,69 @@ | ||
"""Testing utilities for CmdStanPy.""" | ||
|
||
import contextlib | ||
import os | ||
import sys | ||
import unittest | ||
import logging | ||
import platform | ||
import re | ||
from typing import List, Type | ||
from unittest import mock | ||
from importlib import reload | ||
from io import StringIO | ||
import pytest | ||
|
||
|
||
class CustomTestCase(unittest.TestCase): | ||
# pylint: disable=invalid-name | ||
@contextlib.contextmanager | ||
def assertRaisesRegexNested(self, exc, msg): | ||
"""A version of assertRaisesRegex that checks the full traceback. | ||
mark_windows_only = pytest.mark.skipif( | ||
platform.system() != 'Windows', reason='only runs on windows' | ||
) | ||
mark_not_windows = pytest.mark.skipif( | ||
platform.system() == 'Windows', reason='does not run on windows' | ||
) | ||
|
||
Useful for when an exception is raised from another and you wish to | ||
inspect the inner exception. | ||
""" | ||
with self.assertRaises(exc) as ctx: | ||
yield | ||
exception = ctx.exception | ||
exn_string = str(ctx.exception) | ||
while exception.__cause__ is not None: | ||
exception = exception.__cause__ | ||
exn_string += "\n" + str(exception) | ||
self.assertRegex(exn_string, msg) | ||
|
||
@contextlib.contextmanager | ||
def without_import(self, library, module): | ||
with unittest.mock.patch.dict('sys.modules', {library: None}): | ||
reload(module) | ||
yield | ||
reload(module) | ||
# pylint: disable=invalid-name | ||
@contextlib.contextmanager | ||
def raises_nested(expected_exception: Type[Exception], match: str) -> None: | ||
"""A version of assertRaisesRegex that checks the full traceback. | ||
|
||
# recipe modified from https://stackoverflow.com/a/36491341 | ||
@contextlib.contextmanager | ||
def replace_stdin(self, target: str): | ||
orig = sys.stdin | ||
sys.stdin = StringIO(target) | ||
Useful for when an exception is raised from another and you wish to | ||
inspect the inner exception. | ||
""" | ||
with pytest.raises(expected_exception) as ctx: | ||
yield | ||
sys.stdin = orig | ||
|
||
# recipe from https://stackoverflow.com/a/34333710 | ||
@contextlib.contextmanager | ||
def modified_environ(self, *remove, **update): | ||
""" | ||
Temporarily updates the ``os.environ`` dictionary in-place. | ||
|
||
The ``os.environ`` dictionary is updated in-place so that | ||
the modification is sure to work in all situations. | ||
exception: Exception = ctx.value | ||
lines = [] | ||
while exception: | ||
lines.append(str(exception)) | ||
exception = exception.__cause__ | ||
text = "\n".join(lines) | ||
assert re.search(match, text), f"pattern `{match}` does not match `{text}`" | ||
|
||
:param remove: Environment variables to remove. | ||
:param update: Dictionary of environment variables and values to | ||
add/update. | ||
""" | ||
env = os.environ | ||
update = update or {} | ||
remove = remove or [] | ||
|
||
# List of environment variables being updated or removed. | ||
stomped = (set(update.keys()) | set(remove)) & set(env.keys()) | ||
# Environment variables and values to restore on exit. | ||
update_after = {k: env[k] for k in stomped} | ||
# Environment variables and values to remove on exit. | ||
remove_after = frozenset(k for k in update if k not in env) | ||
@contextlib.contextmanager | ||
def without_import(library, module): | ||
with mock.patch.dict('sys.modules', {library: None}): | ||
reload(module) | ||
yield | ||
reload(module) | ||
|
||
try: | ||
env.update(update) | ||
for k in remove: | ||
env.pop(k, None) | ||
yield | ||
finally: | ||
env.update(update_after) | ||
for k in remove_after: | ||
env.pop(k) | ||
|
||
# pylint: disable=invalid-name | ||
def assertPathsEqual(self, path1, path2): | ||
"""Assert paths are equal after normalization""" | ||
self.assertTrue(os.path.samefile(path1, path2)) | ||
def check_present( | ||
caplog: pytest.LogCaptureFixture, | ||
*conditions: List[tuple], | ||
clear: bool = True, | ||
) -> None: | ||
""" | ||
Check that all desired records exist. | ||
""" | ||
for condition in conditions: | ||
logger, level, message = condition | ||
if isinstance(level, str): | ||
level = getattr(logging, level) | ||
found = any( | ||
logger == logger_ and level == level_ and message.match(message_) | ||
if isinstance(message, re.Pattern) | ||
else message == message_ | ||
for logger_, level_, message_ in caplog.record_tuples | ||
) | ||
if not found: | ||
raise ValueError(f"logs did not contain the record {condition}") | ||
if clear: | ||
caplog.clear() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -9,3 +9,6 @@ | |
*.testbak | ||
*.bak-* | ||
!return_one.hpp | ||
# Ignore temporary files created as part of compilation. | ||
*.o | ||
*.o.tmp |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.