Skip to content

Instantly share code, notes, and snippets.

@thehunmonkgroup
Last active September 8, 2023 23:45
Show Gist options
  • Select an option

  • Save thehunmonkgroup/c24fc8aaf064cd81a79e987fded055d4 to your computer and use it in GitHub Desktop.

Select an option

Save thehunmonkgroup/c24fc8aaf064cd81a79e987fded055d4 to your computer and use it in GitHub Desktop.
Quick and dirty test assertion counter for Python tests (pytest)
#!/usr/bin/env python
# pytest provides no mechanism for counting the number of assertions in tests.
#
# This seems like useful information, and this script provides a *reasonable*
# method to get a count.
#
# Since it's simply counting occurances of the string 'assert', it's not
# guaranteed to be fully accurate, but given that a true assert statement
# usually only has one 'assert' string per line, and given that in a test
# file, it would be unusual to have the string 'assert' that is not actually
# an assertion, this approach should still give pretty solid data.
#
# USAGE:
#
# 1. Drop it in the main pytest 'tests' directory
# 2. Make it executable
# 3. Run without arguments to get total assertion count
# 4. Run with the '-h' argument for help
import os
DEFAULT_TEST_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
def count_asserts_in_file(file_path, debug):
with open(file_path, 'r') as file:
count = file.read().count('assert')
if debug:
print(f"{file_path}: {count} asserts")
return count
def count_asserts_in_directory(directory_path, debug):
total_asserts = 0
for root, dirs, files in os.walk(directory_path):
for file in files:
if file.startswith('test_') and file.endswith('.py'):
total_asserts += count_asserts_in_file(os.path.join(root, file), debug)
return total_asserts
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Count the number of 'assert' statements in test files.")
parser.add_argument('directory', metavar='DIR', type=str, nargs='?', default=DEFAULT_TEST_DIRECTORY,
help='the directory to analyze (default: %(default)s)')
parser.add_argument('--debug', action='store_true', help='Print the number of asserts for each file')
args = parser.parse_args()
directory_path = args.directory
debug = args.debug
total_asserts = count_asserts_in_directory(directory_path, debug)
print(f"Total asserts in {directory_path}: {total_asserts}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment