#!/usr/share/ucs-test/runner python3
## -*- coding: utf-8 -*-
## desc: check compatibility between azure- and graph-implementation
## tags: [apptest, integrationtest]
## exposure: dangerous
## packages:
##   - univention-office365

import os
import time
import logging
import argparse
import unittest

import univention.testing.ucr as testing_ucr

from univention.office365.api.graph import Graph
from univention.office365.api.exceptions import GraphError

from univention.office365.azure_handler import ApiError, AzureHandler as Azure

from helpers.random_strings import create_random_string_with_prefix


class TestTeamsAPICompatibility(unittest.TestCase):
    def setUp(self):
        '''
            initializes an instance of the Graph class and one for
            AzureHandler. Calls can then be executed against either of both and
            incompatibilities can be indentified.
        '''

        # the alias has to be one, which has the correct permissions assigned
        # to it.
        self.alias = 'o365domain'

        self.ucr = testing_ucr.UCSTestConfigRegistry()
        self.ucr.load()
        self.logger = logging.getLogger()

        # whenever we create a user, group or team, we want to delete it after
        # the test execution again. For the tearDown method we will store
        # a list of created users in the following List:
        self.test_groups = []

        self.graph = None
        self.logger.debug("Loading Graph with alias '{alias}'...".format(
            alias=self.alias)
        )
        self.graph = Graph(
            ucr=self.ucr,
            name='TestTeamsAPICompGraph',
            connection_alias=self.alias
        )
        self.azure = Azure(
            ucr=self.ucr,
            name="TestTeamsAPICompAzure",
            adconnection_alias=self.alias
        )
        self.assertIsNotNone(self.graph, msg="Graph class was not loaded.")
        self.assertIsNotNone(self.azure, msg="Azure class was not loaded.")

    def tearDown(self):
        # after creating a group it can take some time until it is available as
        # an object and can be deleted again
        self._wait_for_microsoft(60)

        for group in self.test_groups:
            try:
                self.graph.delete_team(group)
            except GraphError:
                self.logger.warning("unable to delete group with id {}".format(group))
                pass

    def _wait_for_microsoft(self, timeout=10):
        time.sleep(timeout)  # this is bad

    def test_create_group(self):
        '''
            Assertion:

            Azure: {}

            Graph: {}

            The basic functionality should work implementation independently,
            but if this test fails it means that the results from both calls
            differd:
        '''

        name_graph = create_random_string_with_prefix(8, '_test_create_group_name_')
        name_azure = create_random_string_with_prefix(8, '_test_create_group_name_')
        desc = create_random_string_with_prefix(8, '_test_create_group_desc_')

        g = dict(self.graph.create_group(name_graph, desc))
        self.test_groups.append(g['objectId'])

        a = dict(self.azure.create_group(name_azure, desc))
        self.test_groups.append(a['objectId'])

        self.assertEqual(
            g['displayName'], name_graph,
            self.test_create_group.__doc__.format(a, g)
        )
        self.assertEqual(
            a['displayName'], name_azure,
            self.test_create_group.__doc__.format(a, g)
        )

    def test_create_group_fail_because_no_name(self):
        '''
            try to break things by creating a group without a name
        '''

        try:
            self.graph.create_group(''),
        except ApiError:
            # will become GraphError after this got reimplemented with Graph
            try:
                self.azure.create_group('')
            except ApiError:
                return  # success: both calls failed
            else:
                pass
        else:
            pass


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description="Test for the Microsoft Graph API library integration",
    )
    parser.add_argument(
        '--fast',
        help='fail fast (exit after the first failed test)',
        action="store_false"
    )
    parser.add_argument(
        '-l',
        '--log',
        help='log file path',
        nargs='?',
        default='/tmp/test-{pid}.log'.format(
            pid=os.getpid()
        )
    )

    args = parser.parse_args()

    logging.basicConfig(
        level=logging.DEBUG,
        filename=args.log,
        filemode='w')

    unittest.main(failfast=args.fast)

# vim: filetype=python expandtab tabstop=4 shiftwidth=4 softtabstop=4
