From 7445c5bd7005203b6bcec6b0bd1755eec3ab9eaa Mon Sep 17 00:00:00 2001 From: Bruno Oliveira Date: Sat, 11 Jul 2015 14:13:43 -0300 Subject: [PATCH] Add support for PEP302 get_data API Fix #808 --- CHANGELOG | 5 +++++ _pytest/assertion/rewrite.py | 6 ++++++ testing/test_assertrewrite.py | 15 +++++++++++++++ 3 files changed, 26 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 41381c6d5..3cbd8c10a 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,11 @@ 2.8.0.dev (compared to 2.7.X) ----------------------------- +- fix issue 808: pytest's internal assertion rewrite hook now implements the + optional PEP302 get_data API so tests can access data files next to them. + Thanks xmo-odoo for request and example and Bruno Oliveira for + the PR. + - rootdir and inifile are now displayed during usage errors to help users diagnose problems such as unexpected ini files which add unknown options being picked up by pytest. Thanks to Pavel Savchenko for diff --git a/_pytest/assertion/rewrite.py b/_pytest/assertion/rewrite.py index 62046d146..eeaee6d44 100644 --- a/_pytest/assertion/rewrite.py +++ b/_pytest/assertion/rewrite.py @@ -197,6 +197,12 @@ class AssertionRewritingHook(object): # DefaultProvider is appropriate. pkg_resources.register_loader_type(cls, pkg_resources.DefaultProvider) + def get_data(self, pathname): + """Optional PEP302 get_data API. + """ + with open(pathname, 'rb') as f: + return f.read() + def _write_pyc(state, co, source_stat, pyc): # Technically, we don't have to have the same pyc format as diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index a2900567b..fbac2b9c1 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -664,6 +664,21 @@ class TestAssertionRewriteHookDetails(object): "* 1 passed*", ]) + def test_get_data_support(self, testdir): + """Implement optional PEP302 api (#808). + """ + path = testdir.mkpydir("foo") + path.join("test_foo.py").write(py.code.Source(""" + class Test: + def test_foo(self): + import pkgutil + data = pkgutil.get_data('foo.test_foo', 'data.txt') + assert data == b'Hey' + """)) + path.join('data.txt').write('Hey') + result = testdir.runpytest() + result.stdout.fnmatch_lines('*1 passed*') + def test_issue731(testdir): testdir.makepyfile("""