from __future__ import absolute_import, division, print_function

import os
import shutil

import pytest

from zict.file import File
from . import utils_test


@pytest.yield_fixture
def fn():
    filename = '.tmp'
    if os.path.exists(filename):
        shutil.rmtree(filename)

    yield filename

    if os.path.exists(filename):
        shutil.rmtree(filename)


def test_mapping(fn):
    """
    Test mapping interface for File().
    """
    z = File(fn)
    utils_test.check_mapping(z)


def test_implementation(fn):
    z = File(fn)
    assert not z

    z['x'] = b'123'
    assert os.listdir(fn) == ['x']
    with open(os.path.join(fn, 'x'), 'rb') as f:
        assert f.read() == b'123'


def test_str(fn):
    z = File(fn)
    assert fn in str(z)
    assert fn in repr(z)
    assert z.mode in str(z)
    assert z.mode in repr(z)


def test_setitem_typeerror(fn):
    z = File(fn)
    with pytest.raises(TypeError):
        z['x'] = 123


def test_contextmanager(fn):
    with File(fn) as z:
        z['x'] = b'123'

    with open(os.path.join(fn, 'x'), 'rb') as f:
        assert f.read() == b'123'


def test_delitem(fn):
    z = File(fn)

    z['x'] = b'123'
    assert os.path.exists(os.path.join(z.directory, 'x'))
    del z['x']
    assert not os.path.exists(os.path.join(z.directory, 'x'))


def test_missing_key(fn):
    z = File(fn)

    with pytest.raises(KeyError):
        z['x']


def test_arbitrary_chars(fn):
    z = File(fn)

    key = ''.join(['foo_'] + [chr(i) for i in range(1, 128)])
    with pytest.raises(KeyError):
        z[key]
    z[key] = b'foo'
    assert z[key] == b'foo'
    del z[key]
    with pytest.raises(KeyError):
        z[key]

@@ -1441,24 +1441,130 @@
 = File(fn)%0A%0A
+    # Avoid hitting the Windows max filename length%0A    chunk = 16%0A    for i in range(1, 128, chunk):%0A    
     key = ''
@@ -1607,18 +1607,38 @@
 nge(
-1, 128)%5D)%0A
+i, min(128, i + chunk))%5D)%0A    
     
@@ -1671,24 +1671,28 @@
 r):%0A        
+    
 z%5Bkey%5D%0A    z
@@ -1686,24 +1686,28 @@
  z%5Bkey%5D%0A    
+    
 z%5Bkey%5D = b'f
@@ -1706,24 +1706,28 @@
 y%5D = b'foo'%0A
+    
     assert z
@@ -1742,24 +1742,28 @@
  b'foo'%0A    
+    
 del z%5Bkey%5D%0A 
@@ -1757,24 +1757,28 @@
  del z%5Bkey%5D%0A
+    
     with pyt
@@ -1791,31 +1791,35 @@
 ises(KeyError):%0A
+    
         z%5Bkey%5D%0A

Fix test under Windows