import os.path

import pytest

import batou.vfs
from batou import ConfigurationError

from ..cron import CronJob, CronTab, PurgeCronTab


def test_collects_cronjobs_into_crontab(root):
    root.environment.vfs_sandbox = batou.vfs.Developer(root.environment, None)
    root.component += CronJob("command1", timing="* * * * *")
    root.component += CronJob("command2", timing="* * * * *")
    root.component += CronTab()
    root.component.deploy()
    cron_filename = os.path.join(
        root.environment.workdir_base, "mycomponent/crontab"
    )
    with open(cron_filename) as f:
        crontab = f.read()
    assert "command1" in crontab
    assert "command2" in crontab


def test_purge_crontab_is_empty(root):
    root.environment.vfs_sandbox = batou.vfs.Developer(root.environment, None)
    root.component += PurgeCronTab()
    root.component.deploy()
    cron_filename = os.path.join(
        root.environment.workdir_base, "mycomponent/crontab"
    )
    with open(cron_filename) as f:
        crontab = f.read()
    assert crontab == "# Generated by batou. Do not edit.\n\n\n"


def test_empty_crontab_must_raise(root):
    root.environment.vfs_sandbox = batou.vfs.Developer(root.environment, None)
    with pytest.raises(ConfigurationError):
        root.component += CronTab()


def test_non_empty_purge_crontab_must_raise(root):
    root.environment.vfs_sandbox = batou.vfs.Developer(root.environment, None)
    root.component += CronJob("command1", timing="* * * * *")
    root.component += CronJob("command2", timing="* * * * *")
    with pytest.raises(ConfigurationError):
        root.component += CronTab(purge=True)


def test_additional_envs_can_be_set(root):
    root.environment.vfs_sandbox = batou.vfs.Developer(root.environment, None)
    root.component += CronJob("command2", timing="* * * * *")
    root.component += CronTab(env=dict(PATH="/foo/bar"))
    root.component.deploy()
    cron_filename = os.path.join(
        root.environment.workdir_base, "mycomponent/crontab"
    )
    with open(cron_filename) as f:
        crontab = f.read()
    assert "PATH=/foo/bar" in crontab
