Skip to content

Commit

Permalink
Moved plugin into package, introduced an custom exception, and moved …
Browse files Browse the repository at this point in the history
…parsing of variables to a hook
  • Loading branch information
davehunt committed Feb 28, 2017
1 parent 5d0ef20 commit 0e83f44
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 21 deletions.
Empty file added pytest_variables/__init__.py
Empty file.
8 changes: 8 additions & 0 deletions pytest_variables/errors.py
@@ -0,0 +1,8 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.


class ValueError(Exception):
"""pytest-variables usage error."""
pass
30 changes: 21 additions & 9 deletions pytest_variables.py → pytest_variables/plugin.py
Expand Up @@ -4,8 +4,11 @@

import os.path
import sys

import pytest

from pytest_variables import errors


def default(module, path):
return module.load(path)
Expand Down Expand Up @@ -38,18 +41,27 @@ def pytest_addoption(parser):
help='path to variables file.')


@pytest.fixture(scope='session')
def variables(request):
"""Provide test variables from a specified file"""
data = {}
for path in request.config.getoption('variables'):
def pytest_configure(config):
config._variables = {}
for path in config.getoption('variables'):
ext = os.path.splitext(path)[1][1:].lower() or 'json'
with open(path) as f:
try:
data.update(import_parser(f, *parser_table[ext]))
except (TypeError, KeyError, ValueError):
variables = import_parser(f, *parser_table[ext])
print(variables)
config._variables.update(variables)
except KeyError:
print("Could not find a parser for the file extension '{0}'. "
'Supported extensions are: {1}'.format(
ext, ', '.join(sorted(parser_table.keys()))))
data.update(import_parser(f, *parser_table['json']))
return data
config._variables.update(
import_parser(f, *parser_table['json']))
except ValueError as e:
raise errors.ValueError('Unable to parse {0}: {1}'.format(
path, e))


@pytest.fixture(scope='session')
def variables(pytestconfig):
"""Provide test variables from a specified file"""
return pytestconfig._variables
4 changes: 2 additions & 2 deletions setup.py
Expand Up @@ -7,8 +7,8 @@
author='Dave Hunt',
author_email='dhunt@mozilla.com',
url='https://github.com/pytest-dev/pytest-variables',
py_modules=['pytest_variables'],
entry_points={'pytest11': ['variables = pytest_variables']},
packages=['pytest_variables'],
entry_points={'pytest11': ['variables = pytest_variables.plugin']},
install_requires=['pytest>=2.4.2'],
extras_require={
'hjson': ['hjson'],
Expand Down
17 changes: 7 additions & 10 deletions test_variables.py
Expand Up @@ -14,17 +14,17 @@ def pytest_generate_tests(metafunc):
metafunc.parametrize('file_format', ['json', 'hjson', 'yaml'])


def run(testdir, file_format='json', variables=None):
def run(testdir, file_format='json', variables=None, raw=False):
variables = variables or [{"foo": "bar"}]
args = []
for i, v in enumerate(variables):
if file_format == 'hjson':
if file_format == 'hjson' and not raw:
hjson = pytest.importorskip('hjson')
v = hjson.dumps(v)
elif file_format == 'yaml':
elif file_format == 'yaml' and not raw:
yaml = pytest.importorskip('yaml')
v = yaml.dump(v)
else:
elif not raw:
import json
v = json.dumps(v)
args.append('--variables')
Expand Down Expand Up @@ -75,12 +75,9 @@ def test(variables):

def test_invalid_format(testdir, file_format):
testdir.makepyfile('def test(variables): pass')
result = run(testdir, file_format, ['invalid'])
assert result.ret == 1
if sys.version_info < (3, 5, 0):
result.stdout.fnmatch_lines(['*ValueError: *'])
else:
result.stdout.fnmatch_lines(['*JSONDecodeError: *'])
result = run(testdir, file_format, ['invalid'], raw=True)
assert result.ret == 3
result.stderr.fnmatch_lines(['*ValueError: Unable to parse*'])


def test_key_error(testdir, file_format):
Expand Down

0 comments on commit 0e83f44

Please sign in to comment.