Skip to content
This repository was archived by the owner on May 17, 2024. It is now read-only.

Commit fc36c70

Browse files
committed
Improved remove_password_from_url(), added tests
1 parent 4d43d79 commit fc36c70

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

data_diff/utils.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,18 @@ def number_to_human(n):
5454
return "{:.0f}{}".format(n / 10 ** (3 * millidx), millnames[millidx])
5555

5656

57-
def remove_password_from_url(url, replace_with="***"):
57+
def _join_if_any(sym, args):
58+
args = list(args)
59+
if not args:
60+
return ''
61+
return sym.join(str(a) for a in args if a)
62+
63+
def remove_password_from_url(url: str, replace_with: str="***") -> str:
5864
parsed = urlparse(url)
59-
replaced = parsed._replace(netloc="{}:{}@{}".format(parsed.username, replace_with, parsed.hostname or ""))
65+
account = parsed.username or ''
66+
if parsed.password:
67+
account += ':' + replace_with
68+
host = _join_if_any(":", filter(None, [parsed.hostname, parsed.port]))
69+
netloc = _join_if_any("@", filter(None, [account, host]))
70+
replaced = parsed._replace(netloc=netloc)
6071
return replaced.geturl()

tests/test_config.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import unittest
22

33
from data_diff.config import apply_config_from_string, ConfigParseError
4+
from data_diff.utils import remove_password_from_url
45

56

67
class TestConfig(unittest.TestCase):
@@ -41,3 +42,20 @@ def test_basic(self):
4142
res = apply_config_from_string(config, "pg_pg", {"update_column": "foo", "table2": "bar"})
4243
assert res["update_column"] == "foo"
4344
assert res["table2"] == "bar"
45+
46+
def test_remove_password(self):
47+
replace_with = "*****"
48+
urls = [
49+
'd://host/',
50+
'd://host:123/',
51+
'd://user@host:123/',
52+
'd://user:PASS@host:123/',
53+
'd://:PASS@host:123/',
54+
'd://:PASS@host:123/path',
55+
'd://:PASS@host:123/path?whatever#blabla',
56+
]
57+
for url in urls:
58+
removed = remove_password_from_url(url, replace_with)
59+
expected = url.replace('PASS', replace_with)
60+
removed = remove_password_from_url(url, replace_with)
61+
self.assertEqual(removed, expected)

0 commit comments

Comments
 (0)