#!/usr/bin/env python

# Unit test for debugging running processes

import os
import signal
import sys
import time
import threading
import unittest

from test import test_support
from support import DummyStdout, MPdbTest, MPdbTestThread, MPdbTestProc

sys.path.append('..')

import mpdb

PROTOCOL = 'tcp'
ADDRESS = ':9000'
TESTFN = os.path.abspath(os.curdir+os.path.sep+'.mpdb')

class TestProcessDebugging(unittest.TestCase):
    def child(self):
        os.chdir('./files')
        pid = os.spawnlp(os.P_NOWAIT, './proc.py', './proc.py')
        os.chdir('..')
        return pid
    
    def testTopLevelRoutine(self):
        sys.stdout = DummyStdout()

        mpdb.process_debugging()
        self.assertRaises(ValueError, mpdb.process_debugging, -1)
        self.assertRaises(TypeError, mpdb.process_debugging, 'invalid')
        self.assertRaises(ValueError, mpdb.process_debugging, signal.NSIG)

        # XXX We can't currently check the validity of the connection
        # params.

        sys.stdout = sys.__stdout__

    def no_testSignalHandler(self):
        pid = self.child()
        client = MPdbTestProc(mpdb.MPdb())
        # Allow the child process to catch up
        time.sleep(0.1)

        client.onecmd('set target-address tcp :9000')
        client.onecmd('attach %s' % str(pid))
        client.onecmd('where')
        line = client.lines[1]
        self.assertEquals(line, '  <module>\n(MPdb)')

        try:
            client.onecmd('detach')
        except KeyboardInterrupt:
            pass
        os.kill(pid, signal.SIGINT)

    def testCmdLineOption(self):
        sys.stdout = DummyStdout()

        pid = self.child()
        os.chdir('..')
        time.sleep(0.1)
        os.system("./mpdb.py -e 'detach' --pid='%s tcp :9000'" \
                   % (str(pid)))
        os.chdir('./test')
        os.kill(pid, signal.SIGINT)

        sys.stdout = sys.__stdout__

    def testFifoFilename(self):
        cls, addr = mpdb.process_debugging().split()

        pid = os.getpid()
        import tempfile
        from tempfile import gettempdir
        tmp = gettempdir()

        path = tmp + os.path.sep + str(pid) + 'mpdb'
        self.assertEquals(path, addr)

    def tearDown(self):
        try:
            os.unlink(TESTFN)
        except OSError:
            pass
            
def test_main():
    test_support.run_unittest(TestProcessDebugging)

if __name__ == '__main__':
    test_main()
