import subprocess
import pytest

pytestmark = pytest.mark.slow

system_year = subprocess.check_output(['date', '+%Y'])
system_year = system_year.decode('utf8').replace('\n', '')

system_month = subprocess.check_output(['date', '+%m'])
system_month = system_month.decode('utf8').replace('\n', '').lstrip('0')

version_file_content = """
year = {}
month = {}
build = 8
""".format(system_year, system_month)

config_file_content = """
__config_version__ = 1

GLOBALS = {
    'serializer': '{{year}}.{{month}}.{{build}}',
}

FILES = ['README.md']

ACTIONS = {
    'mbuild': {
        'type': 'conditional_reset',
        'field': 'build',
        'update_fields': ['year', 'month']
    }
}

VERSION = [
    {
        'name': 'year',
        'type': 'date',
        'fmt': 'YYYY'
    },
    {
        'name': 'month',
        'type': 'date',
        'fmt': 'MM'
    },
    {
        'name': 'build',
        'type': 'integer',
        'start_value': 0
    }
]

ACTIONS = {
    'build': {
        'type': 'conditional_reset',
        'field': 'build',
        'update_fields': ['year', 'month']
    }
}
"""


def test_action_refresh(script_runner, test_environment):
    test_environment.ensure_file_is_present(
        "README.md",
        "Version {}.{}.8.".format(system_year, system_month)
    )

    test_environment.ensure_file_is_present("punch_version.py",
                                            version_file_content)

    test_environment.ensure_file_is_present("punch_config.py",
                                            config_file_content)

    ret = test_environment.call(['punch', '--action', 'build'])

    assert not ret.stderr
    assert test_environment.get_file_content("README.md") == \
        "Version {}.{}.9.".format(system_year, system_month)
