diff --git a/pgpasslib.py b/pgpasslib.py index 3cfd221..ab5b82b 100644 --- a/pgpasslib.py +++ b/pgpasslib.py @@ -70,12 +70,15 @@ def getpass(host=DEFAULT_HOST, port=DEFAULT_PORT, dbname=DEFAULT_DBNAME, :raises: InvalidEntry """ + if not isinstance(port, int): port = int(port) for entry in _get_entries(): if entry.match(host, port, dbname, user): return entry.password - return None + + raise NoMatchingEntry("host=%s; port=%i; dbname=%s; user=%s" + % (host, port, dbname, user)) class PgPassException(Exception): @@ -94,6 +97,14 @@ class FileNotFound(PgPassException): MESSAGE = 'No such file "{0}"' +class NoMatchingEntry(PgPassException): + """Raised when the password file doesn't contain a match for the specified + connection parameters. + + """ + MESSAGE = 'No match for connection entry "{0}"' + + class InvalidEntry(PgPassException): """Raised when the password file can not be parsed properly due to errors in the entry format. diff --git a/tests.py b/tests.py index f4f68cd..5101fa6 100644 --- a/tests.py +++ b/tests.py @@ -242,11 +242,19 @@ def test_getpass_returns_expected_result(self): class GetPassNoMatchTest(unittest.TestCase): - - def test_getpass_returns_expected_result(self): + def test_path_matches_expectation(self): with mock.patch('pgpasslib._read_file') as read_file: read_file.return_value = MOCK_CONTENT - self.assertIsNone(pgpasslib.getpass('fail', '5432', 'foo', 'bar')) + self.assertRaises(pgpasslib.NoMatchingEntry, + lambda: pgpasslib.getpass('fail', '5432', 'foo', + 'bar')) + + +class NoMatchingEntryStrFormatting(unittest.TestCase): + def test_str_matches_expectation(self): + msg = "host=fail; port=5432; dbname=foo; user=bar" + self.assertEqual(str(pgpasslib.NoMatchingEntry(msg)), + 'No match for connection entry "%s"' % msg) class FileNotFoundStrFormatting(unittest.TestCase):