Cleaned too wide excepts

This commit is contained in:
Phyks 2014-07-01 20:31:19 +02:00
parent a2f7510e3b
commit d4f9af8a53
4 changed files with 105 additions and 33 deletions

View File

@ -36,7 +36,7 @@ def getNewName(src, bibtex, tag='', override_format=None):
new_name = override_format
try:
new_name = new_name.replace("%j", bibtex['journal'])
except:
except KeyError:
pass
elif bibtex['type'] == 'book':
if override_format is None:
@ -47,7 +47,7 @@ def getNewName(src, bibtex, tag='', override_format=None):
new_name = new_name.replace("%t", bibtex['title'])
try:
new_name = new_name.replace("%Y", bibtex['year'])
except:
except KeyError:
pass
new_name = new_name.replace("%f", authors[0].split(',')[0].strip())
new_name = new_name.replace("%l", authors[-1].split(',')[0].strip())
@ -72,7 +72,7 @@ def getNewName(src, bibtex, tag='', override_format=None):
if not os.path.isdir(config.get("folder") + tag):
try:
os.mkdir(config.get("folder") + tag)
except:
except OSError:
tools.warning("Unable to create tag dir " +
config.get("folder")+tag+".")
@ -91,7 +91,7 @@ def bibtexAppend(data):
with open(config.get("folder")+'index.bib', 'a', encoding='utf-8') \
as fh:
fh.write(tools.parsed2Bibtex(data)+"\n")
except Exception as e:
except IOError as e:
raise e
tools.warning("Unable to open index file.")
return False
@ -105,7 +105,7 @@ def bibtexEdit(ident, modifs):
as fh:
bibtex = BibTexParser(fh.read())
bibtex = bibtex.get_entry_dict()
except:
except (IOError, TypeError):
tools.warning("Unable to open index file.")
return False
@ -126,7 +126,7 @@ def bibtexRewrite(data):
with open(config.get("folder")+'index.bib', 'w', encoding='utf-8') \
as fh:
fh.write(bibtex)
except:
except (IOError, TypeError):
tools.warning("Unable to open index file.")
return False
@ -138,7 +138,7 @@ def deleteId(ident):
as fh:
bibtex = BibTexParser(fh.read().decode('utf-8'))
bibtex = bibtex.get_entry_dict()
except:
except (IOError, TypeError):
tools.warning("Unable to open index file.")
return False
@ -147,14 +147,14 @@ def deleteId(ident):
try:
os.remove(bibtex[ident]['file'])
except:
except (KeyError, OSError):
tools.warning("Unable to delete file associated to id "+ident+" : " +
bibtex[ident]['file'])
try:
if not os.listdir(os.path.dirname(bibtex[ident]['file'])):
os.rmdir(os.path.dirname(bibtex[ident]['file']))
except:
except (KeyError, OSError):
tools.warning("Unable to delete empty tag dir " +
os.path.dirname(bibtex[ident]['file']))
@ -174,7 +174,7 @@ def deleteFile(filename):
as fh:
bibtex = BibTexParser(fh.read().decode('utf-8'))
bibtex = bibtex.get_entry_dict()
except:
except (TypeError, IOError):
tools.warning("Unable to open index file.")
return False
@ -185,14 +185,14 @@ def deleteFile(filename):
found = True
try:
os.remove(bibtex[key]['file'])
except:
except (KeyError, OSError):
tools.warning("Unable to delete file associated to id " +
key+" : "+bibtex[key]['file'])
try:
if not os.listdir(os.path.dirname(filename)):
os.rmdir(os.path.dirname(filename))
except:
except OSError:
tools.warning("Unable to delete empty tag dir " +
os.path.dirname(filename))
@ -201,7 +201,7 @@ def deleteFile(filename):
except KeyError:
tools.warning("No associated bibtex entry in index for " +
"file " + bibtex[key]['file'])
except:
except (KeyError, OSError):
pass
if found:
bibtexRewrite(bibtex)
@ -224,7 +224,7 @@ def diffFilesIndex():
as fh:
index = BibTexParser(fh.read())
index_diff = index.get_entry_dict()
except:
except (TypeError, IOError):
tools.warning("Unable to open index file.")
return False
@ -252,7 +252,7 @@ def getBibtex(entry, file_id='both', clean=False):
as fh:
bibtex = BibTexParser(fh.read())
bibtex = bibtex.get_entry_dict()
except:
except (TypeError, IOError):
tools.warning("Unable to open index file.")
return False
@ -284,7 +284,7 @@ def getEntries():
as fh:
bibtex = BibTexParser(fh.read())
bibtex = bibtex.get_entry_dict()
except:
except (TypeError, IOError):
tools.warning("Unable to open index file.")
return False

30
bmc.py
View File

@ -39,12 +39,12 @@ def checkBibtex(filename, bibtex_string):
check = tools.rawInput("Is it correct? [Y/n] ")
except KeyboardInterrupt:
sys.exit()
except:
except (KeyError, AssertionError):
check = 'n'
try:
old_filename = bibtex['file']
except:
except KeyError:
old_filename = False
while check.lower() == 'n':
@ -58,7 +58,7 @@ def checkBibtex(filename, bibtex_string):
bibtex = bibtex.get_entry_dict()
try:
bibtex = bibtex[bibtex.keys()[0]]
except:
except KeyError:
tools.warning("Invalid bibtex entry")
bibtex_string = ''
tools.rawInput("Press Enter to go back to editor.")
@ -83,7 +83,7 @@ def checkBibtex(filename, bibtex_string):
try:
print("Moving file to new location…")
shutil.move(old_filename, bibtex['file'])
except:
except shutil.Error:
tools.warning("Unable to move file "+old_filename+" to " +
bibtex['file']+". You should check it manually.")
@ -205,7 +205,7 @@ def addFile(src, filetype, manual, autoconfirm, tag):
try:
shutil.copy2(src, new_name)
except IOError:
except shutil.Error:
new_name = False
sys.exit("Unable to move file to library dir " +
config.get("folder")+".")
@ -214,7 +214,7 @@ def addFile(src, filetype, manual, autoconfirm, tag):
try:
if 'IOP' in bibtex['publisher'] and bibtex['type'] == 'article':
tearpages.main(new_name)
except:
except (KeyError, shutil.Error, IOError):
pass
backend.bibtexAppend(bibtex)
@ -254,14 +254,14 @@ def editEntry(entry, file_id='both'):
try:
shutil.move(bibtex['file'], new_bibtex['file'])
except:
raise Exception('Unable to move file '+bibtex['file']+' to ' +
new_bibtex['file'] + ' according to tag edit.')
except shutil.Error:
tools.warning('Unable to move file '+bibtex['file']+' to ' +
new_bibtex['file'] + ' according to tag edit.')
try:
if not os.listdir(os.path.dirname(bibtex['file'])):
os.rmdir(os.path.dirname(bibtex['file']))
except:
except OSError:
tools.warning("Unable to delete empty tag dir " +
os.path.dirname(bibtex['file']))
@ -270,7 +270,7 @@ def editEntry(entry, file_id='both'):
as fh:
index = BibTexParser(fh.read())
index = index.get_entry_dict()
except:
except (TypeError, IOError):
tools.warning("Unable to open index file.")
return False
@ -305,7 +305,7 @@ def openFile(ident):
as fh:
bibtex = BibTexParser(fh.read())
bibtex = bibtex.get_entry_dict()
except:
except (TypeError, IOError):
tools.warning("Unable to open index file.")
return False
@ -370,7 +370,7 @@ def resync():
shutil.copy2(filename, new_name)
print("Imported new file "+filename+" for entry " +
entry['id']+".")
except IOError:
except shutil.Error:
new_name = False
sys.exit("Unable to move file to library dir " +
config.get("folder")+".")
@ -388,7 +388,7 @@ def resync():
filetype = tools.getExtension(entry['file'])
try:
os.remove(entry['file'])
except:
except OSError:
tools.warning("Unable to delete file "+entry['file'])
if not addFile(tmp.name, filetype):
tools.warning("Unable to reimport file "+entry['file'])
@ -402,7 +402,7 @@ def resync():
if os.path.isdir(i) and not os.listdir(config.get("folder") + i):
try:
os.rmdir(config.get("folder") + i)
except:
except OSError:
tools.warning("Found empty tag dir "+config.get("folder") + i +
" but could not delete it.")

View File

@ -117,7 +117,7 @@ def isbn2Bib(isbn):
# Default merges results from worldcat.org and google books
try:
return fmtbib('bibtex', isbntools.meta(isbn, 'default'))
except:
except TypeError:
return ''
@ -268,7 +268,7 @@ def arXiv2Bib(arxiv):
fetched_bibtex = fetched_bibtex[fetched_bibtex.keys()[0]]
try:
del(fetched_bibtex['file'])
except:
except KeyError:
pass
return tools.parsed2Bibtex(fetched_bibtex)
return ''

72
tests/test_config.py Normal file
View File

@ -0,0 +1,72 @@
# -*- coding: utf8 -*-
# -----------------------------------------------------------------------------
# "THE NO-ALCOHOL BEER-WARE LICENSE" (Revision 42):
# Phyks (webmaster@phyks.me) wrote this file. As long as you retain this notice
# you can do whatever you want with this stuff (and you can also do whatever
# you want with this stuff without retaining it, but that's not cool...). If we
# meet some day, and you think this stuff is worth it, you can buy me a
# <del>beer</del> soda in return.
# Phyks
# -----------------------------------------------------------------------------
import unittest
from config import Config
import json
import os
import tempfile
import shutil
class TestConfig(unittest.TestCase):
def setUp(self):
self.folder = tempfile.mkdtemp()+"/"
self.default_config = {"folder": os.path.expanduser("~/Papers/"),
"proxies": [''],
"format_articles": "%f_%l-%j-%Y%v",
"format_books": "%a-%t",
"format_custom": [],
"ignore_fields": ["file", "doi", "tag"]}
def tearDown(self):
shutil.rmtree(self.folder)
def test_load_without_file(self):
config = Config(base_config_path=self.folder)
self.assertEqual(config.as_dict(), self.default_config)
with open(self.folder+"bmc.json", 'r') as fh:
read = json.loads(fh.read())
self.assertEqual(read, self.default_config)
def test_load_with_file(self):
config = self.default_config
config["foo"] = "bar"
with open(self.folder+"bmc.json", 'w') as fh:
json.dump(config, fh)
config_read = Config(base_config_path=self.folder)
self.assertEqual(config, config_read.as_dict())
def test_get(self):
config = Config(base_config_path=self.folder)
self.assertEqual(config.get("proxies"), [''])
def test_set(self):
config = Config(base_config_path=self.folder)
config.set("foo", "bar")
self.assertEqual(config.get("foo"), "bar")
def test_save(self):
config = Config(base_config_path=self.folder)
config.set("foo", "bar")
config.save()
with open(self.folder+"bmc.json", 'r') as fh:
read = json.loads(fh.read())
self.assertEqual(read, config.as_dict())
def test_masks(self):
with open(self.folder+"masks.py", 'w') as fh:
fh.write("def f(x): return x")
config = Config(base_config_path=self.folder)
self.assertEqual("foo", config.get("format_custom")[0]("foo"))
if __name__ == '__main__':
unittest.main()