# Path: chaosmonkey/api/hal.py
# class Document(BaseDocument):
#     """Constructs a ``HAL`` document.
#     """
# 
#     def __init__(self, data=None, links=None, embedded=None, external_self=False):
#         """Initialises a new ``HAL`` Document instance. If no arguments are
#         provided a minimal viable ``HAL`` Document is created.
# 
#         Keyword Args:
#             data (dict): Data for the document
#             links (chaosmonkey.api.hal.link.Collection): A collection of ``HAL`` links
#             embedded: TBC
#             external_self: use a fully-qualified link for self
# 
#         Raises:
#             TypeError: If ``links`` is not a :class:`chaosmonkey.api.hal.link.Collection`
#         """
#         super(Document, self).__init__(data, links, embedded)
#         self.links.append(Self(external=external_self))
# 
# Path: chaosmonkey/api/executors_blueprint.py
# def trigger_to_dict(trigger):
#     """
#     Returns a dict version of the trigger
#     """
#     if isinstance(trigger, DateTrigger):
#         trigger_dict = {}
#         trigger_dict["type"] = "date"
#         trigger_dict["args"] = {"date": arrow.get(trigger.run_date).isoformat()}
#         return trigger_dict
# 
# def dict_to_trigger(trigger_dict):
#     """
#     Returns a trigger version of the trigger json
#     """
#     if trigger_dict["type"] == "date":
#         if "args" not in trigger_dict:
#             raise APIError("Missing trigger args")
#         if "date" not in trigger_dict["args"]:
#             raise APIError("Invalid trigger args")
# 
#         try:
#             trigger = DateTrigger(run_date=arrow.get(trigger_dict["args"]["date"]).datetime)
#         except arrow.parser.ParserError:
#             raise APIError("Invalid date format")
# 
#         return trigger
#     else:
#         raise APIError("Invalid trigger type")


import arrow
from apscheduler.triggers.date import DateTrigger
from flask import url_for
from chaosmonkey.api.hal import Document
from datetime import datetime, timedelta
from chaosmonkey.api.executors_blueprint import trigger_to_dict, dict_to_trigger
"""
API Tests
"""



def test_executors_list_return_empty_array(app):
    url = url_for("executors.get_executors")

    with app.test_request_context(url):

        res = app.test_client().get(url)
        assert res.status_code == 200
        assert res.mimetype == "application/hal+json"
        assert res.json == Document(embedded={"executors": []}).to_dict()


def test_get_executors(app, manager, plan):
    """" Test that the endpoint returns an array of executors """
    url = url_for("executors.get_executors")

    run_time = datetime.now() + timedelta(hours=10)
    executor = manager.add_executor(run_time, "executor name", {}, plan.id)

    with app.test_request_context(url):
        res = app.test_client().get(url)
        assert res.status_code == 200
        assert res.mimetype == "application/hal+json"

# Path: chaosmonkey/api/hal.py
# class Document(BaseDocument):
#     """Constructs a ``HAL`` document.
#     """
# 
#     def __init__(self, data=None, links=None, embedded=None, external_self=False):
#         """Initialises a new ``HAL`` Document instance. If no arguments are
#         provided a minimal viable ``HAL`` Document is created.
# 
#         Keyword Args:
#             data (dict): Data for the document
#             links (chaosmonkey.api.hal.link.Collection): A collection of ``HAL`` links
#             embedded: TBC
#             external_self: use a fully-qualified link for self
# 
#         Raises:
#             TypeError: If ``links`` is not a :class:`chaosmonkey.api.hal.link.Collection`
#         """
#         super(Document, self).__init__(data, links, embedded)
#         self.links.append(Self(external=external_self))
# 
# Path: chaosmonkey/api/executors_blueprint.py
# def trigger_to_dict(trigger):
#     """
#     Returns a dict version of the trigger
#     """
#     if isinstance(trigger, DateTrigger):
#         trigger_dict = {}
#         trigger_dict["type"] = "date"
#         trigger_dict["args"] = {"date": arrow.get(trigger.run_date).isoformat()}
#         return trigger_dict
# 
# def dict_to_trigger(trigger_dict):
#     """
#     Returns a trigger version of the trigger json
#     """
#     if trigger_dict["type"] == "date":
#         if "args" not in trigger_dict:
#             raise APIError("Missing trigger args")
#         if "date" not in trigger_dict["args"]:
#             raise APIError("Invalid trigger args")
# 
#         try:
#             trigger = DateTrigger(run_date=arrow.get(trigger_dict["args"]["date"]).datetime)
#         except arrow.parser.ParserError:
#             raise APIError("Invalid date format")
# 
#         return trigger
#     else:
#         raise APIError("Invalid trigger type")


# Path: test/unit/chaosmonkey/api/executors_blueprint_test.py
import arrow
from apscheduler.triggers.date import DateTrigger
from flask import url_for
from chaosmonkey.api.hal import Document
from datetime import datetime, timedelta
from chaosmonkey.api.executors_blueprint import trigger_to_dict, dict_to_trigger

"""
API Tests
"""



def test_executors_list_return_empty_array(app):
    url = url_for("executors.get_executors")

    with app.test_request_context(url):

        res = app.test_client().get(url)
        assert res.status_code == 200
        assert res.mimetype == "application/hal+json"
        assert res.json == Document(embedded={"executors": []}).to_dict()


def test_get_executors(app, manager, plan):
    """" Test that the endpoint returns an array of executors """
    url = url_for("executors.get_executors")

    run_time = datetime.now() + timedelta(hours=10)
    executor = manager.add_executor(run_time, "executor name", {}, plan.id)

    with app.test_request_context(url):
        res = app.test_client().get(url)
        assert res.status_code == 200
        assert res.mimetype == "application/hal+json"

        assert res.json == Document(embedded={"executors": [executor.to_dict()]}).to_dict()