NRLMMD-GEOIPS / geoips

Main Geolocated Information Processing System code base with basic functionality enabled.
https://nrlmmd-geoips.github.io/geoips/
Other
13 stars 10 forks source link

Speed up the CLI via monkeypatching #585

Closed jsolbrig closed 3 weeks ago

jsolbrig commented 1 month ago

Requested Update

Description

The current CLI unit tests work well and provide good coverage, but are slow. The slowness arises from calling the CLI using subprocess.Popen() for every test. This takes about 0.5 seconds for every test which adds up when there are hundreds of tests.

We can make use of pytest's monkeypatch feature to change the CLI arguments on the fly, without needing to re-initialize the CLI. Here is an example of monkeypatch from ChatGPT:

import pytest
import sys

@pytest.mark.parametrize("args", [
    ["--option1", "value1"],
    ["--option2", "value2"],
    ["--option3", "value3"]
])
def test_function(monkeypatch, args):
    # Backup the original sys.argv
    original_argv = sys.argv

    # Set sys.argv to the new value
    monkeypatch.setattr(sys, 'argv', [sys.argv[0]] + args)

    # Your test code here
    print(f"Testing with arguments: {sys.argv[1:]}")

    # Restore the original sys.argv
    sys.argv = original_argv

    assert True  # Replace with actual assertions

To use this, we would do something like this:

import pytest
import sys

@pytest.mark.parametrize("args", [
    ["--option1", "value1"],
    ["--option2", "value2"],
    ["--option3", "value3"]
])
def test_function(monkeypatch, args):
    # Backup the original sys.argv
    original_argv = sys.argv

    # Set sys.argv to the new value
    monkeypatch.setattr(sys, 'argv', [sys.argv[0]] + args)

    # Initialize and call the CLI
    geoips_cli = GeoipsCLI()
    geoips_cli.execute_command()

    # Restore the original sys.argv
    sys.argv = original_argv

    assert True  # Replace with actual assertions

This could also be simplified by moving the call to parse_args() in the GeoipsCLI class to the execute_command() function rather than __init__(). This would allow initializing the CLI once, then calling it multiple times with different arguments as specified by mock. So, in the above test we could remove the line geoips_cli = GeoipsCLI() and, instead, initialize it outside of the tests or in a fixture.

Background and Motivation

Alternative Solutions

Environment

Code to demonstrate issue

Checklist for Completion