#!/usr/bin/env python2.2
import unittest
import sys
import os, time
from os.path import dirname, abspath, join

sys.path.insert(0, '..')
sys.argv[0] = dirname(sys.argv[0])

import findrox; findrox.version(1, 9, 12)

from rox import i18n
from support import shell_escape, Tmp
from formats import *
__builtins__._ = rox.i18n.translation(os.path.join(rox.app_dir, 'Messages'))

class TestSupport(unittest.TestCase):
	def testShellEscape(self):
		assert shell_escape('''  a test ''') == '  a test '
		assert shell_escape('''  "a's test" ''') == '''  "a\\'s test" '''
		assert shell_escape('''  "a\\'s test" ''') == '''  "a\\\\\\'s test" '''

	def testTmp(self):
		tmp_file = Tmp()
		tmp_file.write('Hello')
		print >>tmp_file, ' ',
		tmp_file.flush()
		os.write(tmp_file.fileno(), 'World')

		tmp_file.seek(0)
		assert tmp_file.read() == 'Hello World'

		name = tmp_file.name
		assert os.path.exists(name)
		tmp_file = None
		assert not os.path.exists(name)

class TestFormats(unittest.TestCase):
	def setUp(self):
		os.chdir('/')

	def testCompress(self):
		test_data = 'Hello\0World\n'
		src = Tmp()
		src.write(test_data)
		src.flush()
		data = FileData(src.name)
		for comp in operations:
			if not isinstance(comp, Compress): continue
			dec = [o for o in operations if isinstance(o, Decompress) and
							o.extension == comp.extension]
			assert len(dec) == 1
			dec = dec[0]
			#print "Test %s / %s" % (comp, dec)
			middle = Tmp()
			comp.save_to_stream(data, middle)
			out = Tmp()
			dec.save_to_stream(FileData(middle.name), out)
			del middle
			assert file(out.name).read() == test_data
			#print "Passed"
		del src

	def testArchive(self):
		test_data = 'Hello\0World\n'
		dir = '/tmp/archive-regression-test'
		out = dir + '.out'
		if not os.path.exists(dir): os.mkdir(dir)
		print >>file(dir + '/test', 'w'), test_data
		data = DirData(dir)

		for archive in operations:
			if not isinstance(archive, Archive): continue
			extract = [o for o in operations if isinstance(o, Extract) and
							    o.extension == archive.extension]
			if not extract:
				#print "(skipping %s; no extractor)" % archive
				continue

			if os.path.exists(out): os.system("rm -r '%s'" % out)

			assert len(extract) == 1
			extract = extract[0]
			#print "Test %s / %s" % (archive, extract)

			middle = Tmp()
			archive.save_to_stream(data, middle)
			extract.save_to_file(FileData(middle.name), dir + '.out')

			assert os.listdir(dir) == os.listdir(out)
			assert file(dir + '/test').read() == file(out + '/test').read()
			#print "Passed"
		
		os.unlink(dir + '/test')
		os.rmdir(dir)
		if os.path.exists(out): os.system("rm -r '%s'" % out)

sys.argv.append('-v')
unittest.main()
