import os
import stat
import shutil
import tempfile
import unittest
import contextlib

from .. import archivebot


def touch(path):
    with open(path, "wb"):
        pass


@contextlib.contextmanager
def tmpdir():
    tmp = tempfile.mkdtemp()
    try:
        yield tmp
    finally:
        shutil.rmtree(tmp)


class TestUniqueWritableFile(unittest.TestCase):
    def test_should_create_a_file_without_a_sequence_number_when_no_files_exist(self):
        with tmpdir() as tmp:
            with archivebot._unique_writable_file(tmp, "filename", ".ext") as (filename, _):
                self.assertEqual(filename, os.path.join(tmp, "filename.ext"))

    def test_should_pick_the_next_sequential_number_when_files_exist(self):
        with tmpdir() as tmp:
            touch(os.path.join(tmp, "filename.ext"))
            touch(os.path.join(tmp, "filename-00000001.ext"))
            touch(os.path.join(tmp, "filename-00000002.ext"))

            with archivebot._unique_writable_file(tmp, "filename", ".ext") as (filename, _):
                self.assertEqual(filename, os.path.join(tmp, "filename-00000003.ext"))

    def test_should_raise_OSError_other_than_EEXIST(self):
        def try_to_create(tmp):
            with archivebot._unique_writable_file(tmp, "filename", ".ext"):
                pass

        with tmpdir() as tmp:
            os.chmod(os.path.join(tmp), stat.S_IREAD)
            self.assertRaises(OSError, try_to_create, tmp)


class TestRename(unittest.TestCase):
    def test_valid_rename(self):
        try:
            tmp = tempfile.NamedTemporaryFile()
            new_tmp = archivebot._rename(tmp.name)
            self.assertFalse(os.path.isfile(tmp.name))
            self.assertTrue(os.path.isfile(new_tmp))
            self.assertTrue(new_tmp.find(".compress") > 1)
        finally:
            for file in [tmp.name, new_tmp]:
                if os.path.isfile(file):
                    os.remove(file)


class TestCompress(unittest.TestCase):
    def test_dotcompress(self):
        with tempfile.NamedTemporaryFile(prefix="roomname.compress@example") as tmp:
            self.assertRaises(ValueError, archivebot._compress, tmp.name)

    def test_valid_compress(self):
        try:
            tmp = tempfile.NamedTemporaryFile(suffix=".compress-00000000", delete=False)
            tmp.write("test")
            gz_file = archivebot._compress(tmp.name)
            try:
                self.assertEqual(gz_file, tmp.name[:-18] + ".gz")
            finally:
                os.remove(gz_file)
        finally:
            if os.path.isfile(tmp.name):
                os.remove(tmp.name)

@@ -1497,37 +1497,92 @@
 est_
-valid_rename(self):%0A        t
+should_not_go_outside_the_original_directory(self):%0A        with tmpdir() as directo
 ry:%0A
@@ -1588,32 +1588,37 @@
 %0A            tmp
+_file
  = tempfile.Name
@@ -1632,16 +1632,43 @@
 aryFile(
+dir=directory, delete=False
 )%0A      
@@ -1677,19 +1677,20 @@
     new_
-tmp
+name
  = archi
@@ -1702,24 +1702,29 @@
 ._rename(tmp
+_file
 .name)%0A     
@@ -1745,40 +1745,365 @@
 sert
-False(os.path.isfile(tmp.name))%0A
+Equal(os.path.abspath(os.path.dirname(new_name)), os.path.abspath(directory))%0A%0A    def test_should_move_the_original_file(self):%0A        with tmpdir() as directory:%0A            tmp_file = tempfile.NamedTemporaryFile(dir=directory, delete=False)%0A            new_name = archivebot._rename(tmp_file.name)%0A            with open(new_name, %22rb%22) as new_file:%0A    
     
@@ -2130,26 +2130,32 @@
 rue(os.path.
-i
 s
+ameopen
 file(new_tmp
@@ -2155,210 +2155,949 @@
 new_
-tmp
+file.fileno(), tmp_file.fileno()
 ))%0A
+%0A
     
-        self.assertTrue(new_tmp.find(%22.compress%22) %3E 1)%0A        finally:%0A            for file in %5Btmp
+def test_should_not_keep_the_original_file(self):%0A        with tmpdir() as directory:%0A            tmp_file = tempfile.NamedTemporaryFile(dir=directory, delete=False)%0A            archivebot._rename(tmp_file.name)%0A            self.assertFalse(os.path.isfile(tmp_file.name))%0A%0A    def test_should_change_the_file_name(self):%0A        with tmpdir() as directory:%0A            tmp_file = tempfile.NamedTemporaryFile(dir=directory, delete=False)%0A            new_name = archivebot._rename(tmp_file.name)%0A            self.assertNotEqual(os.path.abspath(tmp_file
 .name
+)
 , 
-new_tmp%5D:%0A                if os.path.isfile(file):%0A                    os.remove(file
+os.path.abspath(new_name))%0A%0A    def test_should_create_a_filename_with_the_dotcompress_suffix(self):%0A        with tmpdir() as directory:%0A            tmp_file = tempfile.NamedTemporaryFile(dir=directory, delete=False)%0A            new_name = archivebot._rename(tmp_file.name)%0A            self.assertTrue(%22.compress%22 in os.path.basename(new_name)
 )%0A%0A%0A
@@ -3362,33 +3362,56 @@
 (self):%0A        
-t
+with tmpdir() as directo
 ry:%0A            
@@ -3472,16 +3472,31 @@
 000000%22,
+ dir=directory,
  delete=
@@ -3681,32 +3681,32 @@
        finally:%0A
+
                 
@@ -3728,98 +3728,4 @@
 le)%0A
-        finally:%0A            if os.path.isfile(tmp.name):%0A                os.remove(tmp.name)%0A

Fix tempfile __del__ errors, add tests