Skip to content
Snippets Groups Projects
Unverified Commit 321aa0a9 authored by ulif's avatar ulif Committed by GitHub
Browse files

Merge pull request #44 from bhavin192/infile-check

Handle FileNotFoundError. Closes #44
parents 738db8d0 5bc7030c
No related branches found
No related tags found
No related merge requests found
......@@ -18,6 +18,8 @@
import argparse
import pkg_resources
import sys
import logging
from errno import ENOENT
from random import SystemRandom
from diceware.config import get_config_dict
from diceware.logger import configure
......@@ -208,4 +210,12 @@ def main(args=None):
if options.version:
print_version()
raise SystemExit(0)
print(get_passphrase(options))
try:
print(get_passphrase(options))
except (OSError, IOError) as infile_error:
if getattr(infile_error, 'errno', 0) == ENOENT:
logging.getLogger('ulif.diceware').error(
"The file '%s' does not exist." % infile_error.filename)
raise SystemExit(1)
else:
raise
......@@ -111,6 +111,7 @@ class WordList(object):
"""
def __init__(self, path):
self.path = path
self.fd = None
if self.path == "-":
self.fd = tempfile.SpooledTemporaryFile(
max_size=MAX_IN_MEM_SIZE, mode="w+")
......@@ -121,7 +122,7 @@ class WordList(object):
self.signed = self.is_signed()
def __del__(self):
if self.path != "-":
if self.path != "-" and self.fd is not None:
self.fd.close()
def __iter__(self):
......
......@@ -5,6 +5,7 @@ import pytest
import re
import sys
from io import StringIO
from errno import EISDIR
from diceware import (
get_wordlists_dir, SPECIAL_CHARS, insert_special_char, get_passphrase,
handle_options, main, __version__, print_version, get_random_sources,
......@@ -317,6 +318,25 @@ class TestDicewareModule(object):
out, err = capsys.readouterr()
assert out == 'Word1Word1\n'
def test_main_infile_nonexisting(self, argv_handler, capsys):
# main() prints error if file does not exist
# raises the exception if it's other that file not exist
sys.argv = ['diceware', 'nonexisting']
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 1
out, err = capsys.readouterr()
assert "The file 'nonexisting' does not exist." in err
def test_main_infile_not_a_file(self, argv_handler, tmpdir):
# give directory as input
tmpdir.mkdir("wordlist")
tmpdir.chdir()
sys.argv = ['diceware', 'wordlist']
with pytest.raises(IOError) as infile_error:
main()
assert infile_error.value.errno == EISDIR
def test_main_delimiters(self, argv_handler, capsys):
# delimiters are respected on calls to main
sys.stdin = StringIO("word1\n")
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment