'''
Testing class for database API's archive related functions.

Authors: Ari Kairala, Petteri Ponsimaa
Originally adopted from Ivan's exercise 1 test class.
'''

import unittest, hashlib
import re, base64, copy, json, server
from database_api_test_common import BaseTestCase, db
from flask import json, jsonify
from exam_archive import ExamDatabaseErrorNotFound, ExamDatabaseErrorExists
from unittest import TestCase
from resources_common import COLLECTIONJSON, PROBLEMJSON, ARCHIVE_PROFILE, API_VERSION

class RestArchiveTestCase(BaseTestCase):
    '''
    RestArchiveTestCase contains archive related unit tests of the database API.
    '''

    # List of user credentials in exam_archive_data_dump.sql for testing purposes
    super_user = "bigboss"
    super_pw = hashlib.sha256("ultimatepw").hexdigest()
    admin_user = "antti.admin"
    admin_pw = hashlib.sha256("qwerty1234").hexdigest()
    basic_user = "testuser"
    basic_pw = hashlib.sha256("testuser").hexdigest()
    wrong_pw = "wrong-pw"

    test_archive_template_1 = {"template": {
        "data": [{"name": "archiveId", "value": 4},
                 {"name": "name", "value": "Computer Science"},
                 {"name": "organisationName", "value": "OTiT"},
                 {"name": "identificationNeeded", "value": 1}]
    }
    }
    test_archive_template_2 = {"template": {
        "data": [{"name": "archiveId", "value": 4},
                 {"name": "name", "value": "Wireless Communication Engineering"},
                 {"name": "organisationName", "value": "OTiT"},
                 {"name": "identificationNeeded", "value": 0}]
    }
    }

    archivelist_resource_url = '/exam_archive/api/archives/'

    # Set a ready header for authorized admin user
    header_auth = {'Authorization': 'Basic ' + base64.b64encode(super_user + ":" + super_pw)}

    # Define a list of the sample contents of the database, so we can later compare it to the test results

    @classmethod
    def setUpClass(cls):
        print "Testing ", cls.__name__

    def test_user_not_authorized(self):
        '''
        Check that user in not able to get user list without authenticating.
        '''
        print '(' + self.test_user_not_authorized.__name__ + ')', \
            self.test_user_not_authorized.__doc__

        # Test ArchiveList/GET
        rv = self.app.get(self.archivelist_resource_url)
        assert rv.status_code == 401
        assert PROBLEMJSON in rv.mimetype

        # Try to get Archive list as super user with wrong password
        rv = self.app.get(self.archivelist_resource_url, headers={'Authorization': 'Basic ' + \
                                                                base64.b64encode(self.super_user + ":" + self.wrong_pw)})
        assert rv.status_code == 401
        assert PROBLEMJSON in rv.mimetype