Format all /test files with black

Signed-off-by: Christian König <ckoenig@posteo.de>
This commit is contained in:
Christian König 2022-09-19 14:44:10 +02:00
parent 0932c5c498
commit 0df38cd64e
No known key found for this signature in database
7 changed files with 711 additions and 605 deletions

View file

@ -6,12 +6,12 @@ from textwrap import dedent
SETUPVARS = { SETUPVARS = {
'PIHOLE_INTERFACE': 'eth99', "PIHOLE_INTERFACE": "eth99",
'PIHOLE_DNS_1': '4.2.2.1', "PIHOLE_DNS_1": "4.2.2.1",
'PIHOLE_DNS_2': '4.2.2.2' "PIHOLE_DNS_2": "4.2.2.2",
} }
IMAGE = 'pytest_pihole:test_container' IMAGE = "pytest_pihole:test_container"
tick_box = "[\x1b[1;32m\u2713\x1b[0m]" tick_box = "[\x1b[1;32m\u2713\x1b[0m]"
cross_box = "[\x1b[1;31m\u2717\x1b[0m]" cross_box = "[\x1b[1;31m\u2717\x1b[0m]"
@ -38,132 +38,187 @@ testinfra.backend.docker.DockerBackend.run = run_bash
@pytest.fixture @pytest.fixture
def host(): def host():
# run a container # run a container
docker_id = subprocess.check_output( docker_id = (
['docker', 'run', '-t', '-d', '--cap-add=ALL', IMAGE]).decode().strip() subprocess.check_output(["docker", "run", "-t", "-d", "--cap-add=ALL", IMAGE])
.decode()
.strip()
)
# return a testinfra connection to the container # return a testinfra connection to the container
docker_host = testinfra.get_host("docker://" + docker_id) docker_host = testinfra.get_host("docker://" + docker_id)
yield docker_host yield docker_host
# at the end of the test suite, destroy the container # at the end of the test suite, destroy the container
subprocess.check_call(['docker', 'rm', '-f', docker_id]) subprocess.check_call(["docker", "rm", "-f", docker_id])
# Helper functions # Helper functions
def mock_command(script, args, container): def mock_command(script, args, container):
''' """
Allows for setup of commands we don't really want to have to run for real Allows for setup of commands we don't really want to have to run for real
in unit tests in unit tests
''' """
full_script_path = '/usr/local/bin/{}'.format(script) full_script_path = "/usr/local/bin/{}".format(script)
mock_script = dedent(r'''\ mock_script = dedent(
r"""\
#!/bin/bash -e #!/bin/bash -e
echo "\$0 \$@" >> /var/log/{script} echo "\$0 \$@" >> /var/log/{script}
case "\$1" in'''.format(script=script)) case "\$1" in""".format(
script=script
)
)
for k, v in args.items(): for k, v in args.items():
case = dedent(''' case = dedent(
"""
{arg}) {arg})
echo {res} echo {res}
exit {retcode} exit {retcode}
;;'''.format(arg=k, res=v[0], retcode=v[1])) ;;""".format(
arg=k, res=v[0], retcode=v[1]
)
)
mock_script += case mock_script += case
mock_script += dedent(''' mock_script += dedent(
esac''') """
container.run(''' esac"""
)
container.run(
"""
cat <<EOF> {script}\n{content}\nEOF cat <<EOF> {script}\n{content}\nEOF
chmod +x {script} chmod +x {script}
rm -f /var/log/{scriptlog}'''.format(script=full_script_path, rm -f /var/log/{scriptlog}""".format(
content=mock_script, script=full_script_path, content=mock_script, scriptlog=script
scriptlog=script)) )
)
def mock_command_passthrough(script, args, container): def mock_command_passthrough(script, args, container):
''' """
Per other mock_command* functions, allows intercepting of commands we don't want to run for real Per other mock_command* functions, allows intercepting of commands we don't want to run for real
in unit tests, however also allows only specific arguments to be mocked. Anything not defined will in unit tests, however also allows only specific arguments to be mocked. Anything not defined will
be passed through to the actual command. be passed through to the actual command.
Example use-case: mocking `git pull` but still allowing `git clone` to work as intended Example use-case: mocking `git pull` but still allowing `git clone` to work as intended
''' """
orig_script_path = container.check_output('command -v {}'.format(script)) orig_script_path = container.check_output("command -v {}".format(script))
full_script_path = '/usr/local/bin/{}'.format(script) full_script_path = "/usr/local/bin/{}".format(script)
mock_script = dedent(r'''\ mock_script = dedent(
r"""\
#!/bin/bash -e #!/bin/bash -e
echo "\$0 \$@" >> /var/log/{script} echo "\$0 \$@" >> /var/log/{script}
case "\$1" in'''.format(script=script)) case "\$1" in""".format(
script=script
)
)
for k, v in args.items(): for k, v in args.items():
case = dedent(''' case = dedent(
"""
{arg}) {arg})
echo {res} echo {res}
exit {retcode} exit {retcode}
;;'''.format(arg=k, res=v[0], retcode=v[1])) ;;""".format(
arg=k, res=v[0], retcode=v[1]
)
)
mock_script += case mock_script += case
mock_script += dedent(r''' mock_script += dedent(
r"""
*) *)
{orig_script_path} "\$@" {orig_script_path} "\$@"
;;'''.format(orig_script_path=orig_script_path)) ;;""".format(
mock_script += dedent(''' orig_script_path=orig_script_path
esac''') )
container.run(''' )
mock_script += dedent(
"""
esac"""
)
container.run(
"""
cat <<EOF> {script}\n{content}\nEOF cat <<EOF> {script}\n{content}\nEOF
chmod +x {script} chmod +x {script}
rm -f /var/log/{scriptlog}'''.format(script=full_script_path, rm -f /var/log/{scriptlog}""".format(
content=mock_script, script=full_script_path, content=mock_script, scriptlog=script
scriptlog=script)) )
)
def mock_command_run(script, args, container): def mock_command_run(script, args, container):
''' """
Allows for setup of commands we don't really want to have to run for real Allows for setup of commands we don't really want to have to run for real
in unit tests in unit tests
''' """
full_script_path = '/usr/local/bin/{}'.format(script) full_script_path = "/usr/local/bin/{}".format(script)
mock_script = dedent(r'''\ mock_script = dedent(
r"""\
#!/bin/bash -e #!/bin/bash -e
echo "\$0 \$@" >> /var/log/{script} echo "\$0 \$@" >> /var/log/{script}
case "\$1 \$2" in'''.format(script=script)) case "\$1 \$2" in""".format(
script=script
)
)
for k, v in args.items(): for k, v in args.items():
case = dedent(''' case = dedent(
"""
\"{arg}\") \"{arg}\")
echo {res} echo {res}
exit {retcode} exit {retcode}
;;'''.format(arg=k, res=v[0], retcode=v[1])) ;;""".format(
arg=k, res=v[0], retcode=v[1]
)
)
mock_script += case mock_script += case
mock_script += dedent(''' mock_script += dedent(
esac''') """
container.run(''' esac"""
)
container.run(
"""
cat <<EOF> {script}\n{content}\nEOF cat <<EOF> {script}\n{content}\nEOF
chmod +x {script} chmod +x {script}
rm -f /var/log/{scriptlog}'''.format(script=full_script_path, rm -f /var/log/{scriptlog}""".format(
content=mock_script, script=full_script_path, content=mock_script, scriptlog=script
scriptlog=script)) )
)
def mock_command_2(script, args, container): def mock_command_2(script, args, container):
''' """
Allows for setup of commands we don't really want to have to run for real Allows for setup of commands we don't really want to have to run for real
in unit tests in unit tests
''' """
full_script_path = '/usr/local/bin/{}'.format(script) full_script_path = "/usr/local/bin/{}".format(script)
mock_script = dedent(r'''\ mock_script = dedent(
r"""\
#!/bin/bash -e #!/bin/bash -e
echo "\$0 \$@" >> /var/log/{script} echo "\$0 \$@" >> /var/log/{script}
case "\$1 \$2" in'''.format(script=script)) case "\$1 \$2" in""".format(
script=script
)
)
for k, v in args.items(): for k, v in args.items():
case = dedent(''' case = dedent(
"""
\"{arg}\") \"{arg}\")
echo \"{res}\" echo \"{res}\"
exit {retcode} exit {retcode}
;;'''.format(arg=k, res=v[0], retcode=v[1])) ;;""".format(
arg=k, res=v[0], retcode=v[1]
)
)
mock_script += case mock_script += case
mock_script += dedent(''' mock_script += dedent(
esac''') """
container.run(''' esac"""
)
container.run(
"""
cat <<EOF> {script}\n{content}\nEOF cat <<EOF> {script}\n{content}\nEOF
chmod +x {script} chmod +x {script}
rm -f /var/log/{scriptlog}'''.format(script=full_script_path, rm -f /var/log/{scriptlog}""".format(
content=mock_script, script=full_script_path, content=mock_script, scriptlog=script
scriptlog=script)) )
)
def run_script(Pihole, script): def run_script(Pihole, script):

View file

@ -2,6 +2,6 @@ from setuptools import setup
setup( setup(
py_modules=[], py_modules=[],
setup_requires=['pytest-runner'], setup_requires=["pytest-runner"],
tests_require=['pytest'], tests_require=["pytest"],
) )

File diff suppressed because it is too large Load diff

View file

@ -1,22 +1,27 @@
def test_key_val_replacement_works(host): def test_key_val_replacement_works(host):
''' Confirms addOrEditKeyValPair either adds or replaces a key value pair in a given file ''' """Confirms addOrEditKeyValPair either adds or replaces a key value pair in a given file"""
host.run(''' host.run(
"""
source /opt/pihole/utils.sh source /opt/pihole/utils.sh
addOrEditKeyValPair "./testoutput" "KEY_ONE" "value1" addOrEditKeyValPair "./testoutput" "KEY_ONE" "value1"
addOrEditKeyValPair "./testoutput" "KEY_TWO" "value2" addOrEditKeyValPair "./testoutput" "KEY_TWO" "value2"
addOrEditKeyValPair "./testoutput" "KEY_ONE" "value3" addOrEditKeyValPair "./testoutput" "KEY_ONE" "value3"
addOrEditKeyValPair "./testoutput" "KEY_FOUR" "value4" addOrEditKeyValPair "./testoutput" "KEY_FOUR" "value4"
''') """
output = host.run(''' )
output = host.run(
"""
cat ./testoutput cat ./testoutput
''') """
expected_stdout = 'KEY_ONE=value3\nKEY_TWO=value2\nKEY_FOUR=value4\n' )
expected_stdout = "KEY_ONE=value3\nKEY_TWO=value2\nKEY_FOUR=value4\n"
assert expected_stdout == output.stdout assert expected_stdout == output.stdout
def test_key_addition_works(host): def test_key_addition_works(host):
''' Confirms addKey adds a key (no value) to a file without duplicating it ''' """Confirms addKey adds a key (no value) to a file without duplicating it"""
host.run(''' host.run(
"""
source /opt/pihole/utils.sh source /opt/pihole/utils.sh
addKey "./testoutput" "KEY_ONE" addKey "./testoutput" "KEY_ONE"
addKey "./testoutput" "KEY_ONE" addKey "./testoutput" "KEY_ONE"
@ -24,17 +29,21 @@ def test_key_addition_works(host):
addKey "./testoutput" "KEY_TWO" addKey "./testoutput" "KEY_TWO"
addKey "./testoutput" "KEY_THREE" addKey "./testoutput" "KEY_THREE"
addKey "./testoutput" "KEY_THREE" addKey "./testoutput" "KEY_THREE"
''') """
output = host.run(''' )
output = host.run(
"""
cat ./testoutput cat ./testoutput
''') """
expected_stdout = 'KEY_ONE\nKEY_TWO\nKEY_THREE\n' )
expected_stdout = "KEY_ONE\nKEY_TWO\nKEY_THREE\n"
assert expected_stdout == output.stdout assert expected_stdout == output.stdout
def test_key_removal_works(host): def test_key_removal_works(host):
''' Confirms removeKey removes a key or key/value pair ''' """Confirms removeKey removes a key or key/value pair"""
host.run(''' host.run(
"""
source /opt/pihole/utils.sh source /opt/pihole/utils.sh
addOrEditKeyValPair "./testoutput" "KEY_ONE" "value1" addOrEditKeyValPair "./testoutput" "KEY_ONE" "value1"
addOrEditKeyValPair "./testoutput" "KEY_TWO" "value2" addOrEditKeyValPair "./testoutput" "KEY_TWO" "value2"
@ -42,81 +51,100 @@ def test_key_removal_works(host):
addKey "./testoutput" "KEY_FOUR" addKey "./testoutput" "KEY_FOUR"
removeKey "./testoutput" "KEY_TWO" removeKey "./testoutput" "KEY_TWO"
removeKey "./testoutput" "KEY_FOUR" removeKey "./testoutput" "KEY_FOUR"
''') """
output = host.run(''' )
output = host.run(
"""
cat ./testoutput cat ./testoutput
''') """
expected_stdout = 'KEY_ONE=value1\nKEY_THREE=value3\n' )
expected_stdout = "KEY_ONE=value1\nKEY_THREE=value3\n"
assert expected_stdout == output.stdout assert expected_stdout == output.stdout
def test_getFTLAPIPortFile_default(host): def test_getFTLAPIPortFile_default(host):
''' Confirms getFTLAPIPortFile returns the default API port file path ''' """Confirms getFTLAPIPortFile returns the default API port file path"""
output = host.run(''' output = host.run(
"""
source /opt/pihole/utils.sh source /opt/pihole/utils.sh
getFTLAPIPortFile getFTLAPIPortFile
''') """
expected_stdout = '/run/pihole-FTL.port\n' )
expected_stdout = "/run/pihole-FTL.port\n"
assert expected_stdout == output.stdout assert expected_stdout == output.stdout
def test_getFTLAPIPort_default(host): def test_getFTLAPIPort_default(host):
''' Confirms getFTLAPIPort returns the default API port ''' """Confirms getFTLAPIPort returns the default API port"""
output = host.run(''' output = host.run(
"""
source /opt/pihole/utils.sh source /opt/pihole/utils.sh
getFTLAPIPort "/run/pihole-FTL.port" getFTLAPIPort "/run/pihole-FTL.port"
''') """
expected_stdout = '4711\n' )
expected_stdout = "4711\n"
assert expected_stdout == output.stdout assert expected_stdout == output.stdout
def test_getFTLAPIPortFile_and_getFTLAPIPort_custom(host): def test_getFTLAPIPortFile_and_getFTLAPIPort_custom(host):
''' Confirms getFTLAPIPort returns a custom API port in a custom PORTFILE location ''' """Confirms getFTLAPIPort returns a custom API port in a custom PORTFILE location"""
host.run(''' host.run(
"""
tmpfile=$(mktemp) tmpfile=$(mktemp)
echo "PORTFILE=${tmpfile}" > /etc/pihole/pihole-FTL.conf echo "PORTFILE=${tmpfile}" > /etc/pihole/pihole-FTL.conf
echo "1234" > ${tmpfile} echo "1234" > ${tmpfile}
''') """
output = host.run(''' )
output = host.run(
"""
source /opt/pihole/utils.sh source /opt/pihole/utils.sh
FTL_API_PORT_FILE=$(getFTLAPIPortFile) FTL_API_PORT_FILE=$(getFTLAPIPortFile)
getFTLAPIPort "${FTL_API_PORT_FILE}" getFTLAPIPort "${FTL_API_PORT_FILE}"
''') """
expected_stdout = '1234\n' )
expected_stdout = "1234\n"
assert expected_stdout == output.stdout assert expected_stdout == output.stdout
def test_getFTLPIDFile_default(host): def test_getFTLPIDFile_default(host):
''' Confirms getFTLPIDFile returns the default PID file path ''' """Confirms getFTLPIDFile returns the default PID file path"""
output = host.run(''' output = host.run(
"""
source /opt/pihole/utils.sh source /opt/pihole/utils.sh
getFTLPIDFile getFTLPIDFile
''') """
expected_stdout = '/run/pihole-FTL.pid\n' )
expected_stdout = "/run/pihole-FTL.pid\n"
assert expected_stdout == output.stdout assert expected_stdout == output.stdout
def test_getFTLPID_default(host): def test_getFTLPID_default(host):
''' Confirms getFTLPID returns the default value if FTL is not running ''' """Confirms getFTLPID returns the default value if FTL is not running"""
output = host.run(''' output = host.run(
"""
source /opt/pihole/utils.sh source /opt/pihole/utils.sh
getFTLPID getFTLPID
''') """
expected_stdout = '-1\n' )
expected_stdout = "-1\n"
assert expected_stdout == output.stdout assert expected_stdout == output.stdout
def test_getFTLPIDFile_and_getFTLPID_custom(host): def test_getFTLPIDFile_and_getFTLPID_custom(host):
''' Confirms getFTLPIDFile returns a custom PID file path ''' """Confirms getFTLPIDFile returns a custom PID file path"""
host.run(''' host.run(
"""
tmpfile=$(mktemp) tmpfile=$(mktemp)
echo "PIDFILE=${tmpfile}" > /etc/pihole/pihole-FTL.conf echo "PIDFILE=${tmpfile}" > /etc/pihole/pihole-FTL.conf
echo "1234" > ${tmpfile} echo "1234" > ${tmpfile}
''') """
output = host.run(''' )
output = host.run(
"""
source /opt/pihole/utils.sh source /opt/pihole/utils.sh
FTL_PID_FILE=$(getFTLPIDFile) FTL_PID_FILE=$(getFTLPIDFile)
getFTLPID "${FTL_PID_FILE}" getFTLPID "${FTL_PID_FILE}"
''') """
expected_stdout = '1234\n' )
expected_stdout = "1234\n"
assert expected_stdout == output.stdout assert expected_stdout == output.stdout

View file

@ -8,17 +8,20 @@ from .conftest import (
def test_enable_epel_repository_centos(host): def test_enable_epel_repository_centos(host):
''' """
confirms the EPEL package repository is enabled when installed on CentOS confirms the EPEL package repository is enabled when installed on CentOS
''' """
package_manager_detect = host.run(''' package_manager_detect = host.run(
"""
source /opt/pihole/basic-install.sh source /opt/pihole/basic-install.sh
package_manager_detect package_manager_detect
''') """
expected_stdout = info_box + (' Enabling EPEL package repository ' )
'(https://fedoraproject.org/wiki/EPEL)') expected_stdout = info_box + (
" Enabling EPEL package repository " "(https://fedoraproject.org/wiki/EPEL)"
)
assert expected_stdout in package_manager_detect.stdout assert expected_stdout in package_manager_detect.stdout
expected_stdout = tick_box + ' Installed' expected_stdout = tick_box + " Installed"
assert expected_stdout in package_manager_detect.stdout assert expected_stdout in package_manager_detect.stdout
epel_package = host.package('epel-release') epel_package = host.package("epel-release")
assert epel_package.is_installed assert epel_package.is_installed

View file

@ -6,60 +6,70 @@ from .conftest import (
def mock_selinux_config(state, host): def mock_selinux_config(state, host):
''' """
Creates a mock SELinux config file with expected content Creates a mock SELinux config file with expected content
''' """
# validate state string # validate state string
valid_states = ['enforcing', 'permissive', 'disabled'] valid_states = ["enforcing", "permissive", "disabled"]
assert state in valid_states assert state in valid_states
# getenforce returns the running state of SELinux # getenforce returns the running state of SELinux
mock_command('getenforce', {'*': (state.capitalize(), '0')}, host) mock_command("getenforce", {"*": (state.capitalize(), "0")}, host)
# create mock configuration with desired content # create mock configuration with desired content
host.run(''' host.run(
"""
mkdir /etc/selinux mkdir /etc/selinux
echo "SELINUX={state}" > /etc/selinux/config echo "SELINUX={state}" > /etc/selinux/config
'''.format(state=state.lower())) """.format(
state=state.lower()
)
)
def test_selinux_enforcing_exit(host): def test_selinux_enforcing_exit(host):
''' """
confirms installer prompts to exit when SELinux is Enforcing by default confirms installer prompts to exit when SELinux is Enforcing by default
''' """
mock_selinux_config("enforcing", host) mock_selinux_config("enforcing", host)
check_selinux = host.run(''' check_selinux = host.run(
"""
source /opt/pihole/basic-install.sh source /opt/pihole/basic-install.sh
checkSelinux checkSelinux
''') """
expected_stdout = cross_box + ' Current SELinux: enforcing' )
expected_stdout = cross_box + " Current SELinux: enforcing"
assert expected_stdout in check_selinux.stdout assert expected_stdout in check_selinux.stdout
expected_stdout = 'SELinux Enforcing detected, exiting installer' expected_stdout = "SELinux Enforcing detected, exiting installer"
assert expected_stdout in check_selinux.stdout assert expected_stdout in check_selinux.stdout
assert check_selinux.rc == 1 assert check_selinux.rc == 1
def test_selinux_permissive(host): def test_selinux_permissive(host):
''' """
confirms installer continues when SELinux is Permissive confirms installer continues when SELinux is Permissive
''' """
mock_selinux_config("permissive", host) mock_selinux_config("permissive", host)
check_selinux = host.run(''' check_selinux = host.run(
"""
source /opt/pihole/basic-install.sh source /opt/pihole/basic-install.sh
checkSelinux checkSelinux
''') """
expected_stdout = tick_box + ' Current SELinux: permissive' )
expected_stdout = tick_box + " Current SELinux: permissive"
assert expected_stdout in check_selinux.stdout assert expected_stdout in check_selinux.stdout
assert check_selinux.rc == 0 assert check_selinux.rc == 0
def test_selinux_disabled(host): def test_selinux_disabled(host):
''' """
confirms installer continues when SELinux is Disabled confirms installer continues when SELinux is Disabled
''' """
mock_selinux_config("disabled", host) mock_selinux_config("disabled", host)
check_selinux = host.run(''' check_selinux = host.run(
"""
source /opt/pihole/basic-install.sh source /opt/pihole/basic-install.sh
checkSelinux checkSelinux
''') """
expected_stdout = tick_box + ' Current SELinux: disabled' )
expected_stdout = tick_box + " Current SELinux: disabled"
assert expected_stdout in check_selinux.stdout assert expected_stdout in check_selinux.stdout
assert check_selinux.rc == 0 assert check_selinux.rc == 0

View file

@ -1,13 +1,15 @@
def test_epel_and_remi_not_installed_fedora(host): def test_epel_and_remi_not_installed_fedora(host):
''' """
confirms installer does not attempt to install EPEL/REMI repositories confirms installer does not attempt to install EPEL/REMI repositories
on Fedora on Fedora
''' """
package_manager_detect = host.run(''' package_manager_detect = host.run(
"""
source /opt/pihole/basic-install.sh source /opt/pihole/basic-install.sh
package_manager_detect package_manager_detect
''') """
assert package_manager_detect.stdout == '' )
assert package_manager_detect.stdout == ""
epel_package = host.package('epel-release') epel_package = host.package("epel-release")
assert not epel_package.is_installed assert not epel_package.is_installed