"""
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/lib/test/utest_stored_file.py $
$Id: utest_stored_file.py 31156 2008-09-18 15:54:17Z dbinger $
"""
from dulcinea.common import CommonTest
from dulcinea.stored_file import path_check, new_file
from dulcinea.user import DulcineaUser
from durus.utils import as_bytes
from qp.pub.common import site_now
from sancho.utest import raises
import os, shutil

TEST_ROOT_DIR = '/tmp/storedfiletest'
TEST_CONTENT = as_bytes("Contents of a file go here.")

import dulcinea.stored_file
def get_file_store():
    return TEST_ROOT_DIR
dulcinea.stored_file.get_file_store = get_file_store

assert dulcinea.stored_file.get_file_store() == TEST_ROOT_DIR

class StoredFileTest (CommonTest):

    def check_file(self):
        if os.path.exists(TEST_ROOT_DIR):
            shutil.rmtree(TEST_ROOT_DIR)
        os.mkdir(TEST_ROOT_DIR)
        user = DulcineaUser('a')
        content_filename = os.path.join(TEST_ROOT_DIR, 'test_content')
        content = open(content_filename, 'wb')
        content.write(TEST_CONTENT)
        content.close()
        sf = new_file(open(content_filename, 'rb'))
        f = sf.open()
        assert f.read() == TEST_CONTENT
        f.close()
        assert sf.get_size() == len(TEST_CONTENT)
        raises(ValueError, sf.set_mime_type, "textplain")
        sf.set_mime_type("text/plain")
        sf.set_filename("foo")
        assert sf.get_filename() == 'foo'
        sf.set_description("boo")
        assert sf.get_description() == 'boo'
        u = DulcineaUser(None)
        sf.set_owner(u)
        assert sf.get_owner() == u
        assert sf.has_manage_access(u)
        adate = site_now()
        sf.set_date(adate)
        assert sf.get_date() == adate
        shutil.rmtree(TEST_ROOT_DIR)
        del content_filename

    def check_Path_check(self):
        assert path_check("Abc") == 'abc'
        assert path_check("abc/../../../etc/passwd") == None
        assert path_check("/special/characters/-_@.cif") == (
                      "/special/characters/-_@.cif")
        assert path_check("/illegal/characters\001/") == None


if __name__ == "__main__":
    StoredFileTest()
