"""
Rule test code for unit testing of rules generated with SMK {{ version }}.
"""


import os
import sys
import shutil
import tempfile
from pathlib import Path
from subprocess import check_output

sys.path.insert(0, os.path.dirname(__file__))


def test_{{ ruletest.name }}(conda_prefix):

    with tempfile.TemporaryDirectory() as tmpdir:
        workdir = Path(tmpdir) / "workdir"
        config_path = Path("{{ ruletest.config_path.as_posix() }}")
        data_path = Path("{{ ruletest.data_path.as_posix() }}")
        expected_path = Path("{{ ruletest.expected_path.as_posix() }}")

        # Copy config to the temporary workdir.
        shutil.copytree(config_path, workdir)

        # Copy data to the temporary workdir.
        shutil.copytree(data_path, workdir, dirs_exist_ok=True)

        # Run the test job.
        check_output(
            [
                "python",
                "-m",
                "ismk",
                {% for target in ruletest.target %}
                "{{ target }}",
                {% endfor %}
                {% if snakefile %}
                "--snakefile",
                "{{ snakefile }}",
                {% endif %}
                "-f",
                "--notemp",
                "--show-failed-logs",
                "-j1",
                "--target-files-omit-workdir-adjustment",
                {% if configfiles %}
                "--configfile",
                {% for configfile in configfiles %}
                "{{ configfile }}",
                {% endfor %}
                {% endif %}
                {% if deploy %}
                "--software-deployment-method",
                {% for sdm in deploy %}
                "{{ sdm }}",
                {% endfor %}
                {% endif %}
                "--directory",
                workdir,
            ]
            + conda_prefix
        )

        # Check the output byte by byte using cmp/zmp/bzcmp/xzcmp.
        # To modify this behavior, you can inherit from common.OutputChecker in here
        # and overwrite the method `compare_files(generated_file, expected_file), 
        # also see common.py.
        import common
        common.OutputChecker(data_path, expected_path, workdir).check()
