#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'Lucas Meneghel Rodrigues <lmr@redhat.com>'

import gc
import os
import subprocess
import sys
import unittest

from avocado.core import data_dir

from selftests import test_suite


CHECK_TMP_DIRS = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                              "check_tmp_dirs"))


class MyResult(unittest.TextTestResult):
    def stopTest(self, test):
        # stopTest
        super(MyResult, self).stopTest(test)
        # Destroy the data_dir.get_tmpdir ...
        data_dir._tmp_tracker.unittest_refresh_dir_tracker()
        # Rung garbage collection (run __del__s) and force-sync disk
        gc.collect()
        subprocess.Popen("sync", stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE).communicate()
        # ... and check whether some dirs were left behind
        dir_check = subprocess.Popen([sys.executable, CHECK_TMP_DIRS], stdout=subprocess.PIPE,
                                     stderr=subprocess.STDOUT)
        if dir_check.wait():
            raise AssertionError("Test %s left some tmp files behind:\n%s"
                                 % (test, dir_check.stdout.read()))


if __name__ == '__main__':
    runner = unittest.TextTestRunner(failfast=not os.environ.get("SELF_CHECK_CONTINUOUS"),
                                     verbosity=1, resultclass=MyResult)
    result = runner.run(test_suite())
    if result.failures or result.errors:
        sys.exit(1)
