WTF_CSRF_ENABLED = True
SECRET_KEY = 'you-will-never-guess'
CURRENT_TICKET_LIFETIME = 720
QUEUED_TICKET_LIFETIME = 2 class EnvironmentNotFound(Exception):
    def __init__(self, environment):
        self.message = "Environment " + environment + " not found."
        self.status_code = 404 class ServiceAlreadyExists(Exception):
    def __init__(self):
        self.message = "Service with this name already exists" class ServiceNameNotValid(Exception):
    def __init__(self):
        self.message = "Service name not valid. Should not empty or contains dots" class NotFound(Exception):
    def __init__(self):
        self.message = "Service or Group not found"
        self.status_code = 404 class GateStateNotValid(Exception):
    def __init__(self):
        self.message = "state must be open or closed" class JsonStructureError(Exception):
    def __init__(self, message=""):
        self.message = "Your json contains invalid information. " + message class TicketNotFound(Exception):
    def __init__(self):
        self.message = "Ticket does not exist"
        self.status_code = 404 def get_by_list(dic, keys):
    return reduce(dict.get, keys, dic) class ApiHelper:
    def __init__(self, environment):
        print('Run tests on environment ' + environment)
        self.app = create_app(environment=environment, port=8080)
        self.app.config.update(
            DEBUG=True,
            SECRET_KEY='secret_key',
            WTF_CSRF_ENABLED=False
        )
        self.headers = [('Content-Type', 'text/plain')]
        self.content_json = [('Content-Type', 'application/json')]
        self.api = self.app.test_client()

    def create_gate(self, group, name, data):
        response = self.api.post('/api/gates/' + group + "/" + name,
                                 headers=self.content_json,
                                 data=json.dumps(data))
        return load_json(response.data)

    def update_gate(self, group, name, data):
        response = self.api.put('/api/gates/' + group + "/" + name,
                                headers=self.content_json,
                                data=json.dumps(data))
        return load_json(response.data)

    def remove_gate(self, group, name):
        return load_json(self.api.delete('/api/gates/' + group + "/" + name).data)

    def get_gate(self, group, name):
        return load_json(self.api.get('/api/gates/' + group + "/" + name).data)

    def open_gate(self, group, service, environment):
        return self.set_state(group, service, environment, 'open')

    def close_gate(self, group, service, environment):
        return self.set_state(group, service, environment, 'closed')

    def set_state(self, group, service, environment, state):
        return load_json(self.api.put('/api/gates/' + group + "/" + service + '/' + environment,
                                      headers=self.headers,
                                      data=json.dumps({"state": state})).data)

    def set_message(self, group, service, message):
        return self.set_message_on(group, service, message, 'develop')

    def set_message_on(self, group, service, message, environment):
        return load_json(
            self.api.put('/api/gates/' + group + "/" + service + '/' + environment, headers=self.headers,
                         data=json.dumps({"message": message})).data)

    def set_gate(self, data):
        return load_json(self.api.put('/api/gates',
                                      headers=self.content_json,
                                      data=json.dumps(data)).data)

    def set_gate_or_queue_ticket(self, data):
        return load_json(self.api.put('/api/gates?queue=true',
                                      headers=self.content_json,
                                      data=json.dumps(data)).data)

    def delete_ticket(self, ticket_id):
        return load_json(self.api.delete('/api/tickets/' + ticket_id,
                                         headers=self.content_json).data)

    def get_html(self, page):
        return self.api.get(page, content_type='text/html')

    def set_holiday(self, holidays):
        return load_json(self.api.post('/api/holidays/', headers=self.headers,
                                       data=json.dumps(holidays)).data)

    def get_holidays(self):
        return load_json(self.api.get('/api/holidays/').data) class DatabaseHelper:
    def __init__(self, environment):
        config_loader = ConfigLoader(verify=False)
        self.config = config_loader.load_config("resources/", environment)
        self.mongo = MongoConnect(self.config)
        state.mongo = self.mongo

    def decrease_ticket_expiration_date_by(self, ticket_id, delta):
        self.mongo.update_ticket(ticket_id, {"expiration_date": self.mongo.get_expiration_date(delta)})

    def create_holiday(self, days_offset, reason, environments):
        mongo = MongoConnect(self.config)
        mongo.add_holiday({
            'date': (datetime.now() + timedelta(days=days_offset)).strftime('%Y-%m-%d'),
            'reason': reason,
            'environments': environments
        })

    def clear_database(self):
        mongo = MongoConnect(self.config)
        mongo.collection.drop()
        mongo.tickets.drop()
        mongo.holidays.drop() class TestDataHelper:
    def __init__(self, api_helper):
        self.api_helper = api_helper

    def prepare_test_and_set_data(self):
        service, group = self.create_default_gate()

        set_data = {
            "gates": {
                group: {
                    service: ['develop']
                }
            }
        }

        return service, group, set_data

    @staticmethod
    def create_service_name():
        return 'test-gate_' + str(uuid.uuid4())

    @staticmethod
    def create_group_name():
        return 'test-group_' + str(uuid.uuid4())

    def create_default_gate(self):
        service = self.create_service_name()
        group = self.create_group_name()
        self.create_default_gate_with(group, service, ['develop', 'live'])
        return service, group

    def create_default_gate_with(self, group, service, environments):
        gate_data = {
            'environments': environments
        }
        return self.api_helper.create_gate(group, service, gate_data)
import unittest
import uuid
from delorean import Delorean
from mock import mock
from app import config
from app.errors import EnvironmentNotFound, ServiceAlreadyExists, ServiceNameNotValid, NotFound, \
    GateStateNotValid, JsonStructureError, TicketNotFound
from app.util import get_by_list
from tests.helpers.api_helper import ApiHelper
from tests.helpers.database_helper import DatabaseHelper
from tests.helpers.testdata_helper import TestDataHelper



class TestApi(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.maxDiff = None

        cls.gateAlreadyExists = ServiceAlreadyExists().message
        cls.notFound = NotFound().message
        cls.gateNameNotValid = ServiceNameNotValid().message
        cls.gateStateNotValid = GateStateNotValid().message
        cls.environmentNotFound = EnvironmentNotFound("non_existing_environment").message
        cls.ticketNotFound = TicketNotFound().message
        cls.jsonStructureError = JsonStructureError().message

        cls.api_helper = ApiHelper('test')

        cls.database_helper = DatabaseHelper('test')