from testtools import TestCase
import subprocess
import tempfile
import shutil
import os

class gtester2xunitTests(TestCase):

    """A collection of functional tests for gtester2xunit"""

    xsl_file = os.getcwd() + '/gtester.xsl'
    gtester2xunit_binary = os.getcwd() + '/gtester2xunit'
    test_files = [{'gtester_output': 'gtester-output.xml',
                   'xunit_reference': 'gtester-output-xunit-reference.xml',
                   'default_output': 'gtester-output-xunit.xml'},
                 ]

    def _create_testenvironment(self):
        tmpdir = tempfile.mkdtemp()
        for test_file in self.test_files:
            shutil.copy('tests/' + test_file['gtester_output'],
                             tmpdir)
            shutil.copy('tests/' + test_file['xunit_reference'],
                             tmpdir)
        return tmpdir

    def _cleanup_testenvironment(self, tmpdir):
        call = ['rm', '-rf', tmpdir]
        subprocess.check_call(call)

    def test_with_custom_output(self):
        tmpdir = self._create_testenvironment()
        print 'Testing in %s' % (tmpdir)
        for test_file in self.test_files:
            call = [self.gtester2xunit_binary, '-x', self.xsl_file,
                    '-o', 'myoutput.xml', test_file['gtester_output']]
            print call
            subprocess.check_call(call, cwd=tmpdir)
            diff = ['diff', '-Naur', test_file['xunit_reference'],
                    'myoutput.xml']
            subprocess.check_call(diff, cwd=tmpdir)
        self._cleanup_testenvironment(tmpdir)

    def test_with_in_place_output(self):
        tmpdir = self._create_testenvironment()
        print 'Testing in %s' % (tmpdir)
        for test_file in self.test_files:
            call = [self.gtester2xunit_binary, '-i', '-x', self.xsl_file,
                    test_file['gtester_output']]
            print call
            subprocess.check_call(call, cwd=tmpdir)
            diff = ['diff', '-Naur', test_file['xunit_reference'],
                    test_file['gtester_output']]
            subprocess.check_call(diff, cwd=tmpdir)
        self._cleanup_testenvironment(tmpdir)

    def test_with_default_output(self):
        tmpdir = self._create_testenvironment()
        print 'Testing in %s' % (tmpdir)
        for test_file in self.test_files:
            call = [self.gtester2xunit_binary, '-x', self.xsl_file,
                    test_file['gtester_output']]
            print call
            subprocess.check_call(call, cwd=tmpdir)
            diff = ['diff', '-Naur', test_file['xunit_reference'],
                    test_file['default_output']]
            subprocess.check_call(diff, cwd=tmpdir)
        self._cleanup_testenvironment(tmpdir)

