Skip to content

Instantly share code, notes, and snippets.

@gavinsykes
Last active February 17, 2022 12:14
Show Gist options
  • Save gavinsykes/35bff9e7459d89029b404b601f9a1dc4 to your computer and use it in GitHub Desktop.
Save gavinsykes/35bff9e7459d89029b404b601f9a1dc4 to your computer and use it in GitHub Desktop.
Example of a Python Project Euler testing script (commented)
from json import loads
from os import path
from problem_1 import euler_1 as euler_function
# This allows for a bit more portability, rather than changing the name of the function every time I import this file to a new problem, just run euler_function each time.
def main():
# Get the expected answers and load them into a list
with open(path.dirname(__file__) + '/problem_1_expected_answers.json','r') as expected_answers_file:
expected_answers_data = expected_answers_file.read()
expected_answers = loads(expected_answers_data)
# Initialise the successful test counter, and create an empty list for the failed tests, so that any failed tests can print their input, expected value and actual value
successful_tests = 0
failed_tests = []
for expected_answer in expected_answers:
print(f"Input of {expected_answer['input']} should yield {expected_answer['expected_answer']}")
success = False
# For those unfamiliar with colouring your text in the terminal, this turns it bold (1) and red (31)
format_character = '\033[1;31m'
# And when colouring text in the terminal, always use this to finish it off!
# Remember your mum telling you if you make a funny face it will stay that way? Well here it's actually true.
closing_format_character = '\033[0m'
answer = euler_function(expected_answer['input'])
if answer == expected_answer['expected_answer']:
successful_tests += 1
success = True
format_character = '\033[1;32m' # This makes it green instead of red
else:
failed_tests.append({'input':expected_answer['input'],'expected_answer':expected_answer['expected_answer'],'actual_answer':answer})
print(f"{format_character}Input of {expected_answer['input']} yields {answer}{closing_format_character}")
# This should also match the number of entries in your JSON. Note to self: add in that check
total_tests = successful_tests + len(failed_tests)
print(f"\033[1mTotal tests: {total_tests}\033[0m")
print(f"\033[1;32mSuccessful tests: {successful_tests} ({successful_tests * 100 / total_tests}%)\033[0m")
if len(failed_tests) > 0:
print(f"\033[1;31mFailed tests: {len(failed_tests)} ({len(failed_tests) * 100 / total_tests}%)\033[0m")
for test in failed_tests:
# This is why failed tests was a list, so that we can try and see what has gone wrong and where
print(f"\033[1;31mInput of {test['input']} should have yielded {test['expected_answer']} but yields {test['actual_answer']}\033[0m")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment