import json
import os
from eve.methods.common import parse

from eve.tests import TestMinimal
from flask.ext.pymongo import MongoClient
from app.utils import get_resource_name

import importlib

class TestBase(TestMinimal):
    def setUp(self, settings_file=None, url_converters=None):
        from app.app import app
        app.config['MONGO_DBNAME'] = 'DeviceHubTest'
        self.MONGO_DBNAME = app.config['MONGO_DBNAME']
        self.MONGO_HOST = app.config['MONGO_HOST']
        self.MONGO_PORT = app.config['MONGO_PORT']
        self.app = app

        self.connection = None
        self.known_resource_count = 101
        self.setupDB()

        self.test_client = self.app.test_client()
        self.domain = self.app.config['DOMAIN']

        self.token = self._login()
        self.auth_header = ('authorization', 'Basic ' + self.token)

    def setupDB(self):
        self.connection = MongoClient(self.MONGO_HOST, self.MONGO_PORT)
        self.connection.drop_database(self.MONGO_DBNAME)
        self.db = self.connection[self.MONGO_DBNAME]
        self.create_dummy_user()

    def create_dummy_user(self):
        self.db.accounts.insert(
            {'email': "a@a.a", 'password': "1234", 'role': 'superuser', 'token': 'NOFATDNNUB'}
        )

    def get(self, resource, query='', item=None):
        if resource in self.domain:
            resource = self.domain[resource]['url']
        if item:
            request = '/%s/%s%s' % (resource, item, query)
        else:
            request = '/%s%s' % (resource, query)
        r = self.test_client.get(request, environ_base={'HTTP_AUTHORIZATION': 'Basic ' + self.token})
        return self.parse_response(r)

    def post(self, url, data, headers=None, content_type='application/json'):
        if headers is None:
            headers = []
        return super(TestBase, self).post(url, data, headers + [self.auth_header], content_type)

    def patch(self, url, data, headers=None):
        if headers is None:
            headers = []
        return super(TestBase, self).patch(url, data, headers + [self.auth_header])

    def delete(self, url, headers=None):
        if headers is None:
            headers = []
        return super(TestBase, self).delete(url, headers + [self.auth_header])

    def _login(self) -> str:
        return super(TestBase, self).post('/login', {"email": "a@a.a", "password": "1234"})[0]['token']


class TestStandard(TestBase):
    def get_json_from_file(self, filename: str, directory: str=None) -> dict:
        """

        :type filename: str
        :param directory: Optionall. Directory to get the file from. If nothing, it is taken from the actual directory.
        :return:
        """
        if directory is None:
            directory = os.path.dirname(os.path.realpath(__file__))
        with open(os.path.abspath(os.path.join(directory, filename))) as data_file:
            value = json.load(data_file)
        with self.app.app_context():
            event = parse(value, get_resource_name(value['@type']))
            if 'components' in event:
                for device in event['components'] + [event['device']]:
                    device.update(parse(device, get_resource_name(device['@type'])))
            return event


    def isType(self,type:str,item:dict):
        return item['@type'] == type

    def assertType(self, type: str, item: dict):
        self.assertEqual(type, item['@type'])

    def assertLen(self, list: list, length: int):
        self.assertEqual(len(list), length)


@@ -129,16 +129,70 @@
 oClient%0A
+from passlib.handlers.sha2_crypt import sha256_crypt%0A%0A
 from app
@@ -372,16 +372,18 @@
 %0A       
+ #
  app.con
@@ -420,16 +420,161 @@
 ubTest'%0A
+        # app.config%5B'DATABASES'%5D = %5B'dht1', 'dht2'%5D%0A        # app.config%5B'DHT1_DBNAME'%5D = 'dht_1'%0A        # app.config%5B'DHT2_DBNAME'%5D = 'dht_2'%0A
         
@@ -1366,45 +1366,116 @@
    %7B
-'email': %22a@a.a%22, 'password': %221234%22,
+%0A                'email': %22a@a.a%22,%0A                'password': sha256_crypt.encrypt('1234'),%0A               
  'ro
@@ -1491,16 +1491,32 @@
 eruser',
+%0A               
  'token'
@@ -1533,18 +1533,435 @@
 NUB'
-%7D%0A        
+,%0A                'databases': self.app.config%5B'DATABASES'%5D,%0A                'defaultDatabase': self.app.config%5B'DATABASES'%5D%5B0%5D%0A            %7D%0A        )%0A%0A    def dropDB(self):%0A        self.connection = MongoClient(self.MONGO_HOST, self.MONGO_PORT)%0A        self.connection.drop_database('dh_db1')%0A        self.connection.drop_database('dh_db2')%0A        self.connection.drop_database('dh__accounts')%0A        self.connection.close(
 )%0A%0A 
@@ -2270,16 +2270,50 @@
 ent.get(
+self.app.config%5B'DATABASES'%5D%5B0%5D + 
 request,
@@ -2585,16 +2585,56 @@
 f).post(
+self.app.config%5B'DATABASES'%5D%5B0%5D + '/' + 
 url, dat
@@ -2823,16 +2823,56 @@
 ).patch(
+self.app.config%5B'DATABASES'%5D%5B0%5D + '/' + 
 url, dat
@@ -3043,16 +3043,56 @@
 .delete(
+self.app.config%5B'DATABASES'%5D%5B0%5D + '/' + 
 url, hea

Update tests for multiple databases