Skip to content

Commit

Permalink
fix main, tests of scripts (not done)
Browse files Browse the repository at this point in the history
  • Loading branch information
hmpf committed Nov 17, 2023
1 parent 2f7ffce commit 34f9aa7
Show file tree
Hide file tree
Showing 11 changed files with 62 additions and 47 deletions.
18 changes: 12 additions & 6 deletions python/nav/bin/collect_active_ip.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,11 @@
_logger = logging.getLogger('nav.ipcollector')


def main(days=None):
def main(args=None):
"""Controller"""
if args == None:
args = get_parser().parse_args()
days = args.days or None
exit_if_already_running()
init_generic_logging(logfile=LOGFILE, stderr=False)
run(days)
Expand All @@ -62,15 +65,18 @@ def run(days):
_logger.info('Done in %.2f seconds', time.time() - starttime)


if __name__ == '__main__':
_parser = argparse.ArgumentParser()
_parser.add_argument(
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
"-d",
"--days",
default=None,
type=int,
help="days back in time to start collecting from",
)

_args = _parser.parse_args()
main(_args.days)
return parser


if __name__ == '__main__':
main()
6 changes: 4 additions & 2 deletions python/nav/bin/emailreports.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,10 @@
_logger = logging.getLogger('emailreports')


def main(args):
def main(args=None):
"""Send all reports"""
if args == None:
args = get_parser().parse_args()
init_generic_logging(logfile=LOGFILE, stderr=False)
send_reports(args.period)

Expand All @@ -50,4 +52,4 @@ def get_parser():


if __name__ == '__main__':
main(get_parser().parse_args())
main()
13 changes: 7 additions & 6 deletions python/nav/bin/nav.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@
import os.path
import argparse
import textwrap
from nav import colors

from .. import colors
try:
from nav.startstop import ServiceRegistry, CommandFailedError, CrontabError
from ..startstop import ServiceRegistry, CommandFailedError, CrontabError
except ImportError:
print(
"Fatal error: Could not find the nav.startstop module.\nIs your "
Expand All @@ -45,10 +45,11 @@
sys.exit(1)


def main(args):
def main(args=None):
"""Main execution point"""
parser = make_argparser()
args = parser.parse_args()
if args == None:
parser = make_argparser()
args = parser.parse_args()
try:
args.func(args)
except AttributeError:
Expand Down Expand Up @@ -330,4 +331,4 @@ def command_config_install(args):
# begin here #
##############
if __name__ == '__main__':
main(sys.argv[1:])
main()
18 changes: 10 additions & 8 deletions python/nav/bin/radiusparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,15 @@
my_logfile = "./radiusparser.log" # Location of this program's debug log file


def main(args):
def main(args=None):
# If script is already running, abort
if pid_running():
sys.exit(1)
else:
print("Running instance of script not found. Starting...")

if args == None:
args = sys.argv[1:]

try:
db_params = (dbhost, dbport, dbname, dbuser, dbpasswd)
Expand Down Expand Up @@ -460,10 +468,4 @@ def iter_lines(file):
###########

if __name__ == '__main__':
# If script is already running, abort
if pid_running():
sys.exit(1)
else:
print("Running instance of script not found. Starting...")

main(sys.argv[1:])
main()
10 changes: 6 additions & 4 deletions python/nav/bin/servicemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,12 @@ def signalhandler(self, signum, _):
_logger.info("Caught %s. Resuming operation.", signum)


def main(foreground):
def main(args=None):
"""Daemon main entry point"""
os.umask(0o0002)
if args == None:
args = parse_args()
foreground = args.foreground
conf = config.serviceconf()
pidfilename = conf.get("pidfile", "servicemon.pid")

Expand Down Expand Up @@ -174,6 +178,4 @@ def parse_args():


if __name__ == '__main__':
os.umask(0o0002)
args = parse_args()
main(args.foreground)
main()
10 changes: 7 additions & 3 deletions python/nav/bin/sortedstats_cacher.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
_logger = logging.getLogger('nav.sortedstats_cacher')


def main(timeframe, config):
def run(timeframe, config):
_logger.info("Running for timeframe %s", timeframe)
reports = config.get_reports(timeframe)
for report_name, report in reports.items():
Expand Down Expand Up @@ -48,11 +48,15 @@ def exit_if_running(pidfile):
exit(1)


if __name__ == '__main__':
def main():
init_generic_logging(logfile=LOGFILE, stderr=False, read_config=True)
timeframe = get_parser().parse_args().timeframe
pidfile = f"sortedstats_cacher_{timeframe}.pid"
exit_if_running(pidfile)
writepidfile(pidfile)
config = SortedStatsConfig()
main(timeframe, config)
run(timeframe, config)


if __name__ == '__main__':
main()
8 changes: 5 additions & 3 deletions python/nav/bin/start_arnold.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,12 @@
_logger = logging.getLogger('nav.start_arnold')


def main(args):
def main(args=None):
"""Main controller"""

if args == None:
args = parse_command_options()

init_generic_logging(logfile=LOG_FILE, stderr=False, read_config=True)

if args.listblocktypes:
Expand Down Expand Up @@ -316,5 +319,4 @@ def valid_profile(detention_profile_id):


if __name__ == '__main__':
_args = parse_command_options()
main(_args)
main()
8 changes: 0 additions & 8 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,12 @@
from setuptools.command.build import build


def find_scripts():
for candidate in glob('bin/*'):
with open(candidate) as handle:
if handle.readline().startswith("#!"):
yield candidate


# Ensure CSS files are built every time build is invoked
build.sub_commands = [('build_sass', None)] + build.sub_commands


setup(
setup_requires=['libsass', 'setuptools_scm'],
scripts=list(find_scripts()),
sass_manifests={
'nav.web': {
'sass_path': 'sass',
Expand Down
8 changes: 4 additions & 4 deletions tests/docker/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

# MAIN EXECUTION POINT
cd "$WORKSPACE"
tox
tox -e integration-py37-django32 -- tests/integration/bin_test.py

# Code analysis steps
tox -e pylint
/count-lines-of-code.sh
# # Code analysis steps
# tox -e pylint
# /count-lines-of-code.sh

echo "test.sh done"
7 changes: 5 additions & 2 deletions tests/integration/bin_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
import subprocess


BINDIR = './python/nav/bin'


def test_binary_runs(binary):
"""Verifies that a command runs with a zero exit code"""
proc = subprocess.Popen(binary, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
Expand All @@ -23,7 +26,7 @@ def test_naventity_runs_without_error_with_arguments(localhost, snmpsim):
Added in regards to: https://github.com/Uninett/nav/issues/2433
"""
proc = subprocess.Popen(
["./bin/naventity", localhost.ip, "-p", "1024"],
[BINDIR + "/naventity.py", localhost.ip, "-p", "1024"],
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE,
)
Expand All @@ -45,7 +48,7 @@ def test_nav_runs_without_error_without_arguments():
Added in regards to: https://github.com/Uninett/nav/issues/2601
"""
proc = subprocess.Popen(
["./bin/nav"],
[BINDIR + "/nav.py"],
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE,
)
Expand Down
3 changes: 2 additions & 1 deletion tests/integration/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def stop_gunicorn():
r'^# +-\*-\s*testargs:\s*(?P<args>.*?)\s*(-\*-)?\s*$', re.MULTILINE
)
NOTEST_PATTERN = re.compile(r'^# +-\*-\s*notest\s*(-\*-)?\s*$', re.MULTILINE)
BINDIR = './bin'
BINDIR = './python/nav/bin'


def pytest_generate_tests(metafunc):
Expand Down Expand Up @@ -119,6 +119,7 @@ def _is_excluded(filename):
return (
filename.endswith('~')
or filename.startswith('.')
or filename.startswith('__')
or filename.startswith('Makefile')
)

Expand Down

0 comments on commit 34f9aa7

Please sign in to comment.