Skip to content

Commit

Permalink
Handle the entries clean up properly
Browse files Browse the repository at this point in the history
Add test to capture user interfering with /etc/hosts
and to guarantee the /etc/hosts cleanup works as expected
  • Loading branch information
jesusbv committed May 24, 2024
1 parent 0796b68 commit 35ee66a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 9 deletions.
11 changes: 2 additions & 9 deletions lib/cloudregister/registerutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,19 +107,12 @@ def clean_hosts_file(domain_name):
content = hosts_file.readlines()

smt_announce_found = None
smt_domain_found = None
for entry in content:
if b'# Added by SMT' in entry:
smt_announce_found = True
continue
if smt_announce_found and domain_name in entry:
smt_announce_found = False
smt_domain_found = True
continue
if smt_domain_found:
smt_domain_found = False
if b'registry' in entry and domain_name in entry:
# registry entry is optional
if smt_announce_found:
if domain_name in entry:
continue

new_hosts_content.append(entry)
Expand Down
36 changes: 36 additions & 0 deletions tests/test_registerutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,42 @@ def test_clean_host_file_no_empty_bottom_lines():
1.2.3.4 smt-foo.susecloud.net smt-foo
4.3.2.1 another_entry.whatever.com another_entry"""
with mock.patch('builtins.open', mock.mock_open(read_data=hosts_content.encode())) as m: # noqa: E501
utils.clean_hosts_file('susecloud.net')

expected_write_calls = []
expected_lines = expected_cleaned_hosts.split('\n')
for line in expected_lines[:-1]:
line = line + '\n'
expected_write_calls.append(call(line.encode()))
if expected_lines[-1] != '':
expected_write_calls.append(call(expected_lines[-1].encode()))

expected_write_calls.append(call(b'\n'))

assert m().write.mock_calls == expected_write_calls


def test_clean_host_file_no_empty_bottom_lines_user_interfered():
hosts_content = """
# simulates hosts file containing the ipv6 we are looking for in the test
1.2.3.4 smt-foo.susecloud.net smt-foo
# Added by SMT, please, do NOT remove this line
2.3.4.5 smt-entry.susecloud.net smt-entry
1.1.1.1 my.specialhost.us
2.3.4.5 registry-entry.susecloud.net
4.3.2.1 another_entry.whatever.com another_entry"""
expected_cleaned_hosts = """
# simulates hosts file containing the ipv6 we are looking for in the test
1.2.3.4 smt-foo.susecloud.net smt-foo
1.1.1.1 my.specialhost.us
4.3.2.1 another_entry.whatever.com another_entry"""
with mock.patch('builtins.open', mock.mock_open(read_data=hosts_content.encode())) as m: # noqa: E501
utils.clean_hosts_file('susecloud.net')
Expand Down

0 comments on commit 35ee66a

Please sign in to comment.