Skip to content

Instantly share code, notes, and snippets.

@evandrocoan
Last active August 30, 2022 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evandrocoan/69aeaee3e16ad77fc5c889cfd55fc698 to your computer and use it in GitHub Desktop.
Save evandrocoan/69aeaee3e16ad77fc5c889cfd55fc698 to your computer and use it in GitHub Desktop.
Simple python program example to run tests together with your code using pytest.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import timeit
import datetime
import argparse
import pathlib
from pathlib import Path
from typing import Optional
try:
import pytest
except:
print('Disabling tests as pytest is not installed.')
class Struct(object): pass
pytest = Struct()
pytest.mark = Struct()
pytest.mark.parametrize = lambda x, y: lambda z: None
g_start_time = timeit.default_timer()
SCRIPT_DIRECTORY = pathlib.Path(__file__).parent.resolve()
# Call it without the start parameter to print the time since the last call
def print_time(start=None):
global g_start_time
start = g_start_time if start is None else start
end = timeit.default_timer()
print("Time elapsed %s... " % datetime.timedelta(seconds=end-start), end="\n", file=sys.stderr)
g_start_time = end
def run_algorithm(somepath, someparameter, someotherparameter):
print_time()
return [someparameter + someotherparameter]
# Use a "struct" to not keep using global keyword everywhere
class Struct(object): pass
s = Struct()
s.somesetting = 'some'
s.someothersetting = 'other'
@pytest.mark.parametrize('tests', [
(SCRIPT_DIRECTORY / 'some.txt', [
'someother',
]),
(SCRIPT_DIRECTORY / 'someother.txt', [
'someother',
]),
])
def test_name(tests):
file_path, expected = tests
results = run_algorithm(file_path, s.somesetting, s.someothersetting)
assert results == expected
def main() -> Optional[int]:
argumentsNamespace = g_argumentParser.parse_args()
if argumentsNamespace.help:
g_argumentParser.print_help()
return
run_tests = argumentsNamespace.run_tests
if isinstance(run_tests, list):
args = [sys.argv[0], '-vv', '-rP']
if run_tests:
args.extend(run_tests)
print('Running tests %s' % args)
return pytest.main(args)
directory = argumentsNamespace.directory
if directory:
for file_path in sorted(Path(directory).resolve().glob('*.txt')):
run_algorithm(file_path, 'some', 'other')
return
g_argumentParser = argparse.ArgumentParser(
description = \
"""
Single test and main file example.
Run your code and your tests with a single file.
""",
formatter_class=argparse.RawTextHelpFormatter,
add_help=False,
)
# https://stackoverflow.com/questions/35847084/customize-argparse-help-message
g_argumentParser.add_argument( "-h", "--help", action="store_true",
help= """
Show this help message and exits.
""" )
g_argumentParser.add_argument( "-t", "--run-tests", action="store", nargs=argparse.REMAINDER, default=None,
help=
"""
Run unit tests and exit (used only by developers). To run all tests: python3 main.py -t
To run a single test:
1. python3 main.py -t -s -k test_name
2. python3 main.py -t -s -k test_name[testes0]
""" )
g_argumentParser.add_argument( "-d", "--directory", action="store", default=None,
help=
"""
Run the algorithm for all files in a directory.
""" )
if __name__ == '__main__':
start = timeit.default_timer()
code = main()
print_time(start)
sys.exit(code if code else 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment