Browse Source

`patatools cache` improvements

- Better handling of arguments
- Tests
pull/189/head
Louis 9 years ago
parent
commit
bdb033c20b
  1. 7
      patacrep/songbook/__main__.py
  2. 9
      patacrep/tools/__main__.py
  3. 18
      patacrep/tools/cache/__main__.py
  4. 44
      test/test_patatools/test_cache.py

7
patacrep/songbook/__main__.py

@ -113,9 +113,8 @@ def argument_parser(args):
return options return options
def main(): def main(args):
"""Main function:""" """Main function:"""
# set script locale to match user's # set script locale to match user's
try: try:
locale.setlocale(locale.LC_ALL, '') locale.setlocale(locale.LC_ALL, '')
@ -123,7 +122,7 @@ def main():
# Locale is not installed on user's system, or wrongly configured. # Locale is not installed on user's system, or wrongly configured.
LOGGER.error("Locale error: {}\n".format(str(error))) LOGGER.error("Locale error: {}\n".format(str(error)))
options = argument_parser(sys.argv[1:]) options = argument_parser(args[1:])
try: try:
songbook = patacrep.songbook.open_songbook(options.book[-1]) songbook = patacrep.songbook.open_songbook(options.book[-1])
@ -152,4 +151,4 @@ def main():
sys.exit(0) sys.exit(0)
if __name__ == '__main__': if __name__ == '__main__':
main() main(sys.argv)

9
patacrep/tools/__main__.py

@ -104,12 +104,11 @@ def commandline_parser():
return parser return parser
def main(): def main(args):
"""Main function""" """Main function"""
parser = commandline_parser() parser = commandline_parser()
args = parser.parse_args() args = parser.parse_args(args[1:])
args.function(args.remainder) args.function(["patatools-{}".format(args.subcommand)] + args.remainder)
if __name__ == "__main__": if __name__ == "__main__":
main() main(sys.argv)

18
patacrep/tools/cache/__main__.py

@ -37,32 +37,32 @@ def commandline_parser():
) )
subparsers.required = True subparsers.required = True
clear = subparsers.add_parser( clean = subparsers.add_parser(
"clear", "clean",
description="Delete cache.", description="Delete cache.",
help="Delete cache.", help="Delete cache.",
) )
clear.add_argument( clean.add_argument(
'songbook', 'songbook',
metavar="SONGBOOK", metavar="SONGBOOK",
help=textwrap.dedent("""Songbook file to be used to look for cache path."""), help=textwrap.dedent("""Songbook file to be used to look for cache path."""),
type=filename, type=filename,
) )
clear.set_defaults(command=do_clear) clean.set_defaults(command=do_clean)
return parser return parser
def do_clear(namespace): def do_clean(namespace):
"""Execute the `patatools cache clear` command.""" """Execute the `patatools cache clean` command."""
for datadir in songbook.open_songbook(namespace.songbook)['datadir']: for datadir in songbook.open_songbook(namespace.songbook)['datadir']:
cachedir = os.path.join(datadir, ".cache") cachedir = os.path.join(datadir, ".cache")
LOGGER.info("Deleting cache directory '{}'...".format(cachedir)) LOGGER.info("Deleting cache directory '{}'...".format(cachedir))
if os.path.isdir(cachedir): if os.path.isdir(cachedir):
shutil.rmtree(cachedir) shutil.rmtree(cachedir)
def main(args=None): def main(args):
"""Main function: run from command line.""" """Main function: run from command line."""
options = commandline_parser().parse_args(args) options = commandline_parser().parse_args(args[1:])
try: try:
options.command(options) options.command(options)
except errors.SongbookError as error: except errors.SongbookError as error:
@ -70,4 +70,4 @@ def main(args=None):
sys.exit(1) sys.exit(1)
if __name__ == "__main__": if __name__ == "__main__":
main() main(sys.argv)

44
test/test_patatools/test_cache.py

@ -6,9 +6,12 @@ import os
import shutil import shutil
import unittest import unittest
from patacrep.tools import convert from patacrep.files import chdir
from patacrep.tools.__main__ import main as tools_main
from patacrep.tools.cache.__main__ import main as cache_main
from patacrep.songbook.__main__ import main as songbook_main
CACHEDIR = os.path.join(os.path.dirname(__file__), "test_cache_datadir", "songs", ".cache") CACHEDIR = os.path.join(os.path.dirname(__file__), "test_cache_datadir", ".cache")
class TestCache(unittest.TestCase): class TestCache(unittest.TestCase):
"""Test of the "patatools cache" subcommand""" """Test of the "patatools cache" subcommand"""
@ -16,26 +19,49 @@ class TestCache(unittest.TestCase):
def setUp(self): def setUp(self):
"""Remove cache.""" """Remove cache."""
self._remove_cache() self._remove_cache()
self.assertFalse(os.path.exists(CACHEDIR))
def tearDown(self): def tearDown(self):
"""Remove cache.""" """Remove cache."""
self._remove_cache() self._remove_cache()
self.assertFalse(os.path.exists(CACHEDIR))
def _remove_cache(self): @staticmethod
def _remove_cache():
"""Delete cache.""" """Delete cache."""
shutil.rmtree(CACHEDIR, ignore_errors=True) shutil.rmtree(CACHEDIR, ignore_errors=True)
def test_clean(self): def _system(self, main, args):
"""Test of the "patatools cache clean" subcommand""" with chdir(os.path.dirname(__file__)):
# Cache does not exist try:
self.assertFalse(os.path.exists(CACHEDIR)) main(args)
except SystemExit as systemexit:
self.assertEqual(systemexit.code, 0)
def test_clean_exists(self):
"""Test of the "patatools cache clean" subcommand"""
for main, args in [
(tools_main, ["patatools", "cache", "clean", "test_cache.sb"]),
(cache_main, ["patatools-cache", "clean", "test_cache.sb"]),
]:
with self.subTest(main=main, args=args):
# First compilation. Ensure that cache exists afterwards # First compilation. Ensure that cache exists afterwards
TODO self._system(songbook_main, ["songbook", "test_cache.sb"])
self.assertTrue(os.path.exists(CACHEDIR)) self.assertTrue(os.path.exists(CACHEDIR))
# Clean cache # Clean cache
TODO self._system(main, args)
# Ensure that cache does not exist # Ensure that cache does not exist
self.assertFalse(os.path.exists(CACHEDIR)) self.assertFalse(os.path.exists(CACHEDIR))
def test_clean_not_exists(self):
"""Test of the "patatools cache clean" subcommand"""
# Clean non-existent cache
for main, args in [
(tools_main, ["patatools", "cache", "clean", "test_cache.sb"]),
(cache_main, ["patatools-cache", "clean", "test_cache.sb"]),
]:
with self.subTest(main=main, args=args):
# Clean cache
self._system(main, args)

Loading…
Cancel
Save