import py
import sys, os
from rpython.tool.udir import udir

dirpath = py.path.local(__file__).dirpath().dirpath().dirpath().dirpath()
dirpath = dirpath.join('lib_pypy').join('ctypes_config_cache')


def run(filename, outputname):
    filepath = dirpath.join(filename)
    tmpdir = udir.ensure('testcache-' + os.path.splitext(filename)[0],
                         dir=True)
    tmpdir.join('dumpcache.py').write(dirpath.join('dumpcache.py').read())
    path = sys.path[:]
    sys.modules.pop('dumpcache', None)
    try:
        sys.path.insert(0, str(tmpdir))
        execfile(str(filepath), {})
    finally:
        sys.path[:] = path
        sys.modules.pop('dumpcache', None)
    #
    outputpath = tmpdir.join(outputname)
    assert outputpath.check(exists=1)
    modname = os.path.splitext(outputname)[0]
    try:
        sys.path.insert(0, str(tmpdir))
        d = {}
        execfile(str(outputpath), d)
    finally:
        sys.path[:] = path
    return d


def test_resource():
    try:
        import lib_pypy.resource
    except ImportError:
        py.test.skip('no syslog on this platform')
    d = run('resource.ctc.py', '_resource_cache.py')
    assert 'RLIM_NLIMITS' in d

def test_locale():
    d = run('locale.ctc.py', '_locale_cache.py')
    assert 'LC_ALL' in d
    assert 'CHAR_MAX' in d
