diff --git a/diceware/wordlist.py b/diceware/wordlist.py index 5d0ef350c1bb85a4a4d4da4e9f55226d2c6705a9..612825fd768916ae5d69a9ef87688fbaab34f7b0 100644 --- a/diceware/wordlist.py +++ b/diceware/wordlist.py @@ -133,9 +133,19 @@ def get_wordlist_path(name): basename = 'wordlist_%s.txt' % name return os.path.join(WORDLISTS_DIR, basename) +try: + basestring +except NameError: + basestring = str + class WordList(object): """A word list contains words for building passphrases. """ - def __init__(self, opened_file=None, path=None): - pass + def __init__(self, path_or_filelike=None): + self.path = None + if isinstance(path_or_filelike, basestring): + self.path = path_or_filelike + self.fd = open(self.path, "r") + else: + self.fd = path_or_filelike diff --git a/tests/test_wordlist.py b/tests/test_wordlist.py index d1f59571b887424ad214716d37433c120d96e6cc..5c030b6c0b4a34b9a0b11c5da7c299263502a527 100644 --- a/tests/test_wordlist.py +++ b/tests/test_wordlist.py @@ -199,3 +199,21 @@ class TestWordList(object): in_file.write("foo\n") w_list = WordList(str(in_file)) assert w_list is not None + assert hasattr(w_list, "path") + assert hasattr(w_list, "fd") + + def test_create_opens_file(self, tmpdir): + # if we pass-in a path, the file will be opened for reading. + in_file = tmpdir.mkdir("work").join("mywordlist") + in_file.write("foo\n") + w_list = WordList(str(in_file)) + assert w_list.fd is not None + + def test_create_accepts_open_file(self, tmpdir): + # if we pass in an open file, it will be used + in_file = tmpdir.mkdir("work").join("mywordlist") + in_file.write("foo\n") + with open(str(in_file), "w") as my_open_file: + w_list = WordList(my_open_file) + assert w_list.fd is not None + assert w_list.path is None