from subprocess import Popen, PIPE
from django.core.files.temp import NamedTemporaryFile

def test_no_close():
    print '*** Testing lessc without closing temp file. ***'
    temp = NamedTemporaryFile(mode='r+', suffix='.css')
    run_proc('lessc', 'test.less', temp.name)
    print 'FILE:', read_file(temp.name)
    print

def test_close():
    print '*** Testing lessc after closing temp file. ***'
    temp = NamedTemporaryFile(mode='r+', suffix='.css')
    temp.close()
    run_proc('lessc', 'test.less', temp.name)
    print 'FILE:', read_file(temp.name)
    print

def run_proc(*args):
    print args
    proc = Popen(args, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
    ret_code = proc.wait()
    out, err = proc.communicate()
    print 'Returned:', ret_code
    print 'OUT:', out
    print 'ERR:', err

def read_file(filename):
    with open(filename, 'r') as fd:
        return fd.read()

# Fails with permission error
test_no_close()
# Succeeds
test_close()
