Skip to content

Commit

Permalink
Merge pull request #263 from vmuriart/clean-tests
Browse files Browse the repository at this point in the history
Clean-up tests. Fully migrate to Py.test
  • Loading branch information
vmuriart authored Jun 23, 2016
2 parents c56652e + 85349e6 commit 78fb204
Show file tree
Hide file tree
Showing 10 changed files with 1,367 additions and 1,361 deletions.
12 changes: 5 additions & 7 deletions sqlparse/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@ def create_parser():

def _error(msg):
"""Print msg and optionally exit with return code exit_."""
sys.stderr.write('[ERROR] %s\n' % msg)
sys.stderr.write('[ERROR] {0}\n'.format(msg))
return 1


def main(args=None):
Expand All @@ -137,24 +138,21 @@ def main(args=None):
# TODO: Needs to deal with encoding
data = ''.join(open(args.filename).readlines())
except IOError as e:
_error('Failed to read %s: %s' % (args.filename, e))
return 1
return _error('Failed to read {0}: {1}'.format(args.filename, e))

if args.outfile:
try:
stream = open(args.outfile, 'w')
except IOError as e:
_error('Failed to open %s: %s' % (args.outfile, e))
return 1
return _error('Failed to open {0}: {1}'.format(args.outfile, e))
else:
stream = sys.stdout

formatter_opts = vars(args)
try:
formatter_opts = sqlparse.formatter.validate_options(formatter_opts)
except SQLParseError as e:
_error('Invalid options: %s' % e)
return 1
return _error('Invalid options: {0}'.format(e))

s = sqlparse.format(data, **formatter_opts)
if PY2:
Expand Down
41 changes: 41 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# -*- coding: utf-8 -*-

"""Helpers for testing."""

import io
import os

import pytest

DIR_PATH = os.path.dirname(__file__)
FILES_DIR = os.path.join(DIR_PATH, 'files')


@pytest.fixture()
def filepath():
"""Returns full file path for test files."""

def make_filepath(filename):
# http://stackoverflow.com/questions/18011902/parameter-to-a-fixture
# Alternate solution is to use paramtrization `inderect=True`
# http://stackoverflow.com/a/33879151
# Syntax is noisy and requires specific variable names
return os.path.join(FILES_DIR, filename)

return make_filepath


@pytest.fixture()
def load_file(filepath):
"""Opens filename with encoding and return its contents."""

def make_load_file(filename, encoding='utf-8'):
# http://stackoverflow.com/questions/18011902/parameter-to-a-fixture
# Alternate solution is to use paramtrization `inderect=True`
# http://stackoverflow.com/a/33879151
# Syntax is noisy and requires specific variable names
# And seems to be limited to only 1 argument.
with io.open(filepath(filename), encoding=encoding) as f:
return f.read()

return make_load_file
49 changes: 41 additions & 8 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
# -*- coding: utf-8 -*-

import os
import subprocess
import sys

import pytest

import sqlparse
import sqlparse.__main__
from tests.utils import FILES_DIR

path = os.path.join(FILES_DIR, 'function.sql')


def test_cli_main_empty():
Expand All @@ -31,12 +26,50 @@ def test_main_help():
assert exinfo.value.code == 0


def test_valid_args():
def test_valid_args(filepath):
# test doesn't abort
path = filepath('function.sql')
assert sqlparse.cli.main([path, '-r']) is not None


def test_invalid_choise(filepath):
path = filepath('function.sql')
with pytest.raises(SystemExit):
sqlparse.cli.main([path, '-l', 'spanish'])


def test_invalid_args(filepath, capsys):
path = filepath('function.sql')
sqlparse.cli.main([path, '-r', '--indent_width', '0'])
_, err = capsys.readouterr()
assert err == ("[ERROR] Invalid options: indent_width requires "
"a positive integer\n")


def test_invalid_infile(filepath, capsys):
path = filepath('missing.sql')
sqlparse.cli.main([path, '-r'])
_, err = capsys.readouterr()
assert err[:22] == "[ERROR] Failed to read"


def test_invalid_outfile(filepath, capsys):
path = filepath('function.sql')
outpath = filepath('/missing/function.sql')
sqlparse.cli.main([path, '-r', '-o', outpath])
_, err = capsys.readouterr()
assert err[:22] == "[ERROR] Failed to open"


def test_stdout(filepath, load_file, capsys):
path = filepath('begintag.sql')
expected = load_file('begintag.sql')
sqlparse.cli.main([path])
out, _ = capsys.readouterr()
assert out == expected


def test_script():
# Call with the --help option as a basic sanity check.
cmdl = "{0:s} -m sqlparse.cli --help".format(sys.executable)
assert subprocess.call(cmdl.split()) == 0
cmd = "{0:s} -m sqlparse.cli --help".format(sys.executable)
assert subprocess.call(cmd.split()) == 0
Loading

0 comments on commit 78fb204

Please sign in to comment.