Source

fsdict / tests / fsdict_tests.py

# −*− coding: UTF−8 −*−
from __future__ import with_statement
from nose import with_setup
from nose.tools import nottest, assert_equal, assert_true, assert_false
from fsdict import FSPickleDict
import pickle
from pickle import loads, dumps
import os
import os.path
from os.path import join as pathjoin
from os.path import exists as pathexists

def test_fsdict_pickles():
    "occasionally something goes wrong with pickling"
    d1 = FSPickleDict(mktmp=True)
    d1.update({'a':'b'})
    d2 = loads(dumps(d1))
    yield assert_equal, d1, d2
    yield assert_equal, d1.path, d2.path

def test_fsdict_loads():
    import pickle
    
    d = FSPickleDict(mktmp=True)
    d.update({'a':'b'})
    yield assert_true, pathexists(d.path)
    yield assert_true, pathexists(pathjoin(d.path, 'a'))
    yield assert_equal, d['a'], 'b'
    yield assert_true, 'a' in d
    yield assert_false, 'q' in d
    for key in d:
        yield assert_equal, key, 'a'
    for key, val in d.iteritems():
        yield assert_equal, key, 'a'
        yield assert_equal, val, 'b'
    for val in d.itervalues():
        yield assert_equal, val, 'b'
    yield assert_equal, d.values(), ['b']
    yield assert_equal, d['a'], 'b'
    subdir = pathjoin(d.path, 'a')
    # os.makedirs(pathjoin(d.path, 'd'))
    # os.makedirs(subdir)
    pickle.dump('c', open(subdir, 'w'))
    yield assert_equal, d['a'], 'c'
    del(d['a'])
    yield assert_false, pathexists(pathjoin(d.path, 'a'))
    d.delete()
    yield assert_false, pathexists(d.path)
    e=FSPickleDict(mktmp=True)
    yield assert_true, pathexists(e.path)
    f=FSPickleDict(mktmp=True)
    yield assert_true, pathexists(f.path)
    e.delete()
    f.delete()
    yield assert_false, pathexists(e.path)
    yield assert_false, pathexists(f.path)

def test_fsdict_equals():
    """
    as far as equality goes, we want these things to equate as normal dicts
    """
    fsd = FSPickleDict(mktmp=True)
    fsd.update({'a':'b'})
    d1 = {'a':'b'}
    d2 = {'c':'b'}
    d3 = {'a':'c'}
    assert d1 == fsd
    assert d2 != fsd
    assert d3 != fsd
    assert "foo" != fsd
    
def test_fsdict_setdefault():
    """does setdefault work as expected?"""
    d = FSPickleDict(mktmp=True)
    yield assert_equal, d.setdefault('a',2), 2
    #sure, but did that REALLY go to the FS?
    yield assert_true, pathexists(pathjoin(d.path, 'a'))
    yield assert_equal, d.setdefault('a',3), 2
    d.delete()