# Path: pyFileFixity/tests/aux_tests.py
# def path_sample_files(type=None, path=None, createdir=False):
#     """ Helper function to return the full path to the test files """
#     subdir = ''
#     if not type:
#         return ''
#     elif type == 'input':
#         subdir = 'files'
#     elif type == 'results':
#         subdir = 'results'
#     elif type == 'output':
#         subdir = 'out'
# 
#     dirpath = ''
#     scriptpath = os.path.dirname(os.path.realpath(__file__))
#     if path:
#         dirpath = fullpath(os.path.join(scriptpath, subdir, path))
#     else:
#         dirpath = fullpath(os.path.join(scriptpath, subdir))
# 
#     if createdir:
#         create_dir_if_not_exist(dirpath)
# 
#     return dirpath
# 
# def create_dir_if_not_exist(path):
#     """Create a directory if it does not already exist, else nothing is done and no error is return"""
#     if not os.path.exists(path):
#         os.makedirs(path)
# 
# Path: pyFileFixity/lib/hasher.py
# class Hasher(object):
#     '''Class to provide a hasher object with various hashing algorithms. What's important is to provide the __len__ so that we can easily compute the block size of ecc entries. Must only use fixed size hashers for the rest of the script to work properly.'''
#     
#     known_algo = ["md5", "shortmd5", "shortsha256", "minimd5", "minisha256", "none"]
#     __slots__ = ['algo', 'length']
# 
#     def __init__(self, algo="md5"):
#         # Store the selected hashing algo
#         self.algo = algo.lower()
#         # Precompute length so that it's very fast to access it later
#         if self.algo == "md5":
#             self.length = 32
#         elif self.algo == "shortmd5" or self.algo == "shortsha256":
#             self.length = 8
#         elif self.algo == "minimd5" or self.algo == "minisha256":
#             self.length = 4
#         elif self.algo == "none":
#             self.length = 0
#         else:
#             raise NameError('Hashing algorithm %s is unknown!' % algo)
# 
#     def hash(self, mes):
#         # use hashlib.algorithms_guaranteed to list algorithms
#         if self.algo == "md5":
#             return hashlib.md5(mes).hexdigest()
#         elif self.algo == "shortmd5": # from: http://www.peterbe.com/plog/best-hashing-function-in-python
#             return hashlib.md5(mes).hexdigest().encode('base64')[:8]
#         elif self.algo == "shortsha256":
#             return hashlib.sha256(mes).hexdigest().encode('base64')[:8]
#         elif self.algo == "minimd5":
#             return hashlib.md5(mes).hexdigest().encode('base64')[:4]
#         elif self.algo == "minisha256":
#             return hashlib.sha256(mes).hexdigest().encode('base64')[:4]
#         elif self.algo == "none":
#             return ''
#         else:
#             raise NameError('Hashing algorithm %s is unknown!' % self.algo)
# 
#     def __len__(self):
#         return self.length


from nose.tools import assert_raises
from .aux_tests import path_sample_files, create_dir_if_not_exist
from ..lib.hasher import Hasher
import sys
import os
import shutil




def setup_module():
    """ Initialize the tests by emptying the out directory """
    outfolder = path_sample_files('output')
    shutil.rmtree(outfolder, ignore_errors=True)
    create_dir_if_not_exist(outfolder)

def test_hasher():
    """ hasher: test hashes """
    instring = "Lorem ipsum and some more stuff\nThe answer to the question of life, universe and everything is... 42."
    # Put all hashing algo results here (format: "algo_name": [length, result_for_instring])
    algo_params = {"md5": [32, '173efbe0280ce506ddbfbfc9aeb44a1a'],
                   "shortmd5": [8, 'MTczZWZi'],
                   "shortsha256": [8, 'NjgzMjRk'],
                   "minimd5":  [4, 'MTcz'],
                   "minisha256": [4, 'Njgz'],
                   "none": [0, ''],
                  }
    # For each hashing algo, produce a hash and check the length and hash
    for algo in Hasher.known_algo:
        h = Hasher(algo)
        shash = h.hash(instring)
        #print(algo+": "+shash) # debug
        assert len(shash) == algo_params[algo][0]
        assert shash == algo_params[algo][1]
    # Check that unknown algorithms raise an exception
    with assert_raises(NameError) as cm:

# Path: pyFileFixity/tests/aux_tests.py
# def path_sample_files(type=None, path=None, createdir=False):
#     """ Helper function to return the full path to the test files """
#     subdir = ''
#     if not type:
#         return ''
#     elif type == 'input':
#         subdir = 'files'
#     elif type == 'results':
#         subdir = 'results'
#     elif type == 'output':
#         subdir = 'out'
# 
#     dirpath = ''
#     scriptpath = os.path.dirname(os.path.realpath(__file__))
#     if path:
#         dirpath = fullpath(os.path.join(scriptpath, subdir, path))
#     else:
#         dirpath = fullpath(os.path.join(scriptpath, subdir))
# 
#     if createdir:
#         create_dir_if_not_exist(dirpath)
# 
#     return dirpath
# 
# def create_dir_if_not_exist(path):
#     """Create a directory if it does not already exist, else nothing is done and no error is return"""
#     if not os.path.exists(path):
#         os.makedirs(path)
# 
# Path: pyFileFixity/lib/hasher.py
# class Hasher(object):
#     '''Class to provide a hasher object with various hashing algorithms. What's important is to provide the __len__ so that we can easily compute the block size of ecc entries. Must only use fixed size hashers for the rest of the script to work properly.'''
#     
#     known_algo = ["md5", "shortmd5", "shortsha256", "minimd5", "minisha256", "none"]
#     __slots__ = ['algo', 'length']
# 
#     def __init__(self, algo="md5"):
#         # Store the selected hashing algo
#         self.algo = algo.lower()
#         # Precompute length so that it's very fast to access it later
#         if self.algo == "md5":
#             self.length = 32
#         elif self.algo == "shortmd5" or self.algo == "shortsha256":
#             self.length = 8
#         elif self.algo == "minimd5" or self.algo == "minisha256":
#             self.length = 4
#         elif self.algo == "none":
#             self.length = 0
#         else:
#             raise NameError('Hashing algorithm %s is unknown!' % algo)
# 
#     def hash(self, mes):
#         # use hashlib.algorithms_guaranteed to list algorithms
#         if self.algo == "md5":
#             return hashlib.md5(mes).hexdigest()
#         elif self.algo == "shortmd5": # from: http://www.peterbe.com/plog/best-hashing-function-in-python
#             return hashlib.md5(mes).hexdigest().encode('base64')[:8]
#         elif self.algo == "shortsha256":
#             return hashlib.sha256(mes).hexdigest().encode('base64')[:8]
#         elif self.algo == "minimd5":
#             return hashlib.md5(mes).hexdigest().encode('base64')[:4]
#         elif self.algo == "minisha256":
#             return hashlib.sha256(mes).hexdigest().encode('base64')[:4]
#         elif self.algo == "none":
#             return ''
#         else:
#             raise NameError('Hashing algorithm %s is unknown!' % self.algo)
# 
#     def __len__(self):
#         return self.length


# Path: pyFileFixity/tests/test_hasher.py
from nose.tools import assert_raises
from .aux_tests import path_sample_files, create_dir_if_not_exist
from ..lib.hasher import Hasher
import sys
import os
import shutil





def setup_module():
    """ Initialize the tests by emptying the out directory """
    outfolder = path_sample_files('output')
    shutil.rmtree(outfolder, ignore_errors=True)
    create_dir_if_not_exist(outfolder)

def test_hasher():
    """ hasher: test hashes """
    instring = "Lorem ipsum and some more stuff\nThe answer to the question of life, universe and everything is... 42."
    # Put all hashing algo results here (format: "algo_name": [length, result_for_instring])
    algo_params = {"md5": [32, '173efbe0280ce506ddbfbfc9aeb44a1a'],
                   "shortmd5": [8, 'MTczZWZi'],
                   "shortsha256": [8, 'NjgzMjRk'],
                   "minimd5":  [4, 'MTcz'],
                   "minisha256": [4, 'Njgz'],
                   "none": [0, ''],
                  }
    # For each hashing algo, produce a hash and check the length and hash
    for algo in Hasher.known_algo:
        h = Hasher(algo)
        shash = h.hash(instring)
        #print(algo+": "+shash) # debug
        assert len(shash) == algo_params[algo][0]
        assert shash == algo_params[algo][1]
    # Check that unknown algorithms raise an exception
    with assert_raises(NameError) as cm:

        h = Hasher("unknown_algo")