<reponame>jock-tanner/magicinvoke
import pytest, six
from cachepath import CachePath, Path

@pytest.fixture
def ctx():
    from invoke import Context
    return Context()

# pytest -k test_this --capture=no

def test_this(ctx):
    # Includes workarounds for --clean and --force-run not working in PY2.
    from textwrap import dedent
    from colorama import Style
    only_print_expected_stdout = dedent(
        """
        print_peoples_ages called
        Tom's age is 39
        Jerry's age is 39
        <NAME>'s age is 39
        Done!
        """
    )
    both_stdout = dedent(
        """
        print_peoples_ages called
        get_peoples_ages called
        Getting age for Tom
        Getting age for Jerry
        Getting age for <NAME>
        Done pulling results!
        Tom's age is 39
        Jerry's age is 39
        <NAME>'s age is 39
        Done!
        """
    )

    def only_print_ran(stdout):
        assert only_print_expected_stdout.strip() == stdout.strip()

    def both_ran(stdout):
        assert both_stdout.strip() == stdout.strip()

    # Remove minv cache.
    if six.PY2:
        CachePath('.minv').rm()
        Path('.minv').rm()
    else:
        st = Path("people.txt").stat().st_mtime if Path("people.txt").exists() else None
        ctx.run("inv get-people --clean")
        st1 = Path("people.txt").stat().st_mtime
        assert st != st1  # Clean should delete and re-run.

    def bprint(s):
        print(Style.BRIGHT + s + Style.RESET_ALL)

    # Now actually start the test. We run get-people just to seed the file,
    # it shouldn't show up in actual @skippable testing in a few lines.
    bprint("Everything should run from scratch.")
    if six.PY2:
        Path('people.txt').rm()
        assert "Wrote" in ctx.run("invoke get-people").stdout
    else:
        assert "Wrote" in ctx.run("inv get-people --force-run").stdout.strip()

    # If get-people still runs here, it means caching for skippable doesn't work.
    both_ran(ctx.run("invoke print-peoples-ages").stdout)
    only_print_ran(ctx.run("invoke print-peoples-ages").stdout)

    bprint("Since latest outputs were generated by a task with different "
           "params, everything should run again when params change.")
    both_ran(
        ctx.run(
            "invoke -D people.important_flag=True print-peoples-ages"
        ).stdout
    )
    only_print_ran(
        ctx.run(
            "invoke -D people.important_flag=True print-peoples-ages"
        ).stdout
    )
    bprint("Flags changed _again_! But we still have the return value cached :)")
    only_print_ran(ctx.run("invoke print-peoples-ages").stdout)

    bprint("Make sure clean actually cleans.")
    if six.PY2:
        # If you fail here it's because we assume how minv implemented these paths :)
        CachePath('.minv', 'tasks.get_peoples_ages').rm()
    else:
        ctx.run("invoke get-people --clean")
    both_ran(ctx.run("invoke print-peoples-ages").stdout)

    bprint("We're good!")
