#!/usr/bin/python
#
# This script checks that xserver is running
#
# (C) 2012 Canonical Ltd.
# Author: Jean-Baptiste Lallement <jean-baptiste.lallement@canonical.com>
#         Based on the original version from Michael Vogt
# License: GPL v2 or higher

import unittest
import subprocess
from time import sleep

def is_process_running(procname):
    '''Check if a process is running'''
    proclist = subprocess.Popen(["ps","-eo","comm"], stdout=subprocess.PIPE,
                                universal_newlines=True).communicate()[0]
    for line in proclist.split("\n"):
        if line == procname:
            return True
    return False

def is_desktop_install():
    '''Check that at least an *ubuntu-desktop package is installed'''
    cmd = ['dpkg-query', '-Wf', '${Status}\n', '*ubuntu-desktop']
    try:
        output = subprocess.check_output(cmd).split('\n')
    except:
        return False

    for line in output:
        if line.startswith('install'):
            return True
    return False

class TestXserver(unittest.TestCase):
    @unittest.skipIf(not is_desktop_install(), 'Not a desktop installation.')
    def test_xserver_running(self):
        '''Checking for running Xorg'''
        count = 0
        while not is_process_running('Xorg') and count<10:
            count += 1
            sleep(10)

        self.assertTrue(is_process_running('Xorg'), 'X Server not running')

if __name__ == '__main__':
    unittest.main()
