#!/usr/bin/python

import unittest
from subprocess import Popen, PIPE
import difflib
import uuid
import os,sys,time
import argparse
import tempfile

verbose = 0

def diff_files(fromfile,tofile):
    n = 3 #context lines
    fromdate = time.ctime(os.stat(fromfile).st_mtime)
    todate = time.ctime(os.stat(tofile).st_mtime)
    fromlines = open(fromfile, 'U').readlines()
    tolines = open(tofile, 'U').readlines()
    diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile,
            fromdate, todate, n=n)
    l = list(diff)
    if l :
        if verbose == 2:
            sys.stdout.writelines(l)
        return False
    else :
        return True

def test_application_stdout(self,expected_file,cmd):
    print " ".join(cmd)
    (output,output_file) = tempfile.mkstemp()
    if verbose == 2:
        print " ".join(cmd)
    p = Popen(cmd, stdout=output)
    p.communicate()
    d = diff_files(output_file,expected_file)
    #output.close()
    os.remove(output_file)
    self.assertTrue(d)

def test_application_file(self,expected_file,output_file,cmd):
    print " ".join(cmd)
    p = Popen(cmd, stdout=sys.stdout)
    p.communicate()
    d = diff_files(output_file,expected_file)
    self.assertTrue(d)

class ApplicationTests(unittest.TestCase):
    def test_reduced_dist(self):
        expected_file = "tests/reduced-dist"
        cmd = [ "./reduced_dist.native", "--deb-native-arch=amd64", 
                "./tests/sid-amd64-packages-20121001.bz2", 
                "./tests/sid-sources-20121001.bz2" 
                ]
        test_application_stdout(self,expected_file,cmd)

    def test_basebuildsystem(self):
        expected_file = "tests/min-cross-sources.list"
        cmd = ["./basebuildsystem.native", "--deb-native-arch=amd64", 
                "./tests/sid-amd64-packages-20121001.bz2", 
                "./tests/sid-sources-20121001.bz2" 
                ]
        test_application_file(self,expected_file,"min-cross-sources.list",cmd)

def main():
    global verbose
    parser = argparse.ArgumentParser(description='description of you program')
    parser.add_argument('-v', '--verbose', action='store_const', const=2)
    parser.add_argument('-d', '--debug', action='store_true')
    parser.add_argument('-pwd', type=str, nargs=1, help="dose root directory")
    args = parser.parse_args()

    verbose = args.verbose

    suite = unittest.TestLoader().loadTestsFromTestCase(ApplicationTests)
    unittest.TextTestRunner(verbosity=args.verbose).run(suite)

if __name__ == '__main__':
    main()


