# -*- coding: utf-8 -*-

import pickle

from utilities import create_temporary_pub, clean_temporary_pub

from wcs.qommon.storage import StorableObject
from wcs.roles import Role, get_user_roles

def setup_module(module):
    pub = create_temporary_pub()
    pub.cfg['language'] = {'language': 'en'}
    pub.cfg['misc'] = {'charset': 'utf-8'}

def teardown_module(module):
    clean_temporary_pub()

def test_slug():
    Role.wipe()
    role = Role(name='Hello world')
    role.store()
    assert role.slug == 'hello-world'

def test_duplicated_name():
    Role.wipe()
    role = Role(name='Hello world')
    role.store()
    assert role.slug == 'hello-world'
    role = Role(name='Hello world')
    role.store()
    assert role.slug == 'hello-world-1'

def test_migrate():
    Role.wipe()
    role = Role(name='Hello world')
    role.store()
    obj = pickle.load(open(role.get_object_filename(), 'rb'))
    del obj.slug
    pickle.dump(obj, open(role.get_object_filename(), 'wb'))
    assert pickle.load(open(role.get_object_filename(), 'rb')).slug is None
    assert Role.get(role.id).slug == 'hello-world'

def test_get_user_roles():
    Role.wipe()
    Role(name='f1').store()
    Role(name='é1').store()
    Role(name='a1').store()
    assert [x[1] for x in get_user_roles()] == ['a1', 'é1', 'f1']
